chiark / gitweb /
ef001a98bfc1c193ead87be6fd4f673731058f6e
[elogind.git] / src / swap.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <errno.h>
23 #include <limits.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/epoll.h>
27 #include <sys/stat.h>
28 #include <sys/swap.h>
29 #include <libudev.h>
30
31 #include "unit.h"
32 #include "swap.h"
33 #include "load-fragment.h"
34 #include "load-dropin.h"
35 #include "unit-name.h"
36 #include "dbus-swap.h"
37 #include "special.h"
38 #include "bus-errors.h"
39 #include "exit-status.h"
40 #include "def.h"
41
42 static const UnitActiveState state_translation_table[_SWAP_STATE_MAX] = {
43         [SWAP_DEAD] = UNIT_INACTIVE,
44         [SWAP_ACTIVATING] = UNIT_ACTIVATING,
45         [SWAP_ACTIVE] = UNIT_ACTIVE,
46         [SWAP_DEACTIVATING] = UNIT_DEACTIVATING,
47         [SWAP_ACTIVATING_SIGTERM] = UNIT_DEACTIVATING,
48         [SWAP_ACTIVATING_SIGKILL] = UNIT_DEACTIVATING,
49         [SWAP_DEACTIVATING_SIGTERM] = UNIT_DEACTIVATING,
50         [SWAP_DEACTIVATING_SIGKILL] = UNIT_DEACTIVATING,
51         [SWAP_FAILED] = UNIT_FAILED
52 };
53
54 static void swap_unset_proc_swaps(Swap *s) {
55         Swap *first;
56
57         assert(s);
58
59         if (!s->parameters_proc_swaps.what)
60                 return;
61
62         /* Remove this unit from the chain of swaps which share the
63          * same kernel swap device. */
64
65         first = hashmap_get(s->meta.manager->swaps_by_proc_swaps, s->parameters_proc_swaps.what);
66         LIST_REMOVE(Swap, same_proc_swaps, first, s);
67
68         if (first)
69                 hashmap_remove_and_replace(s->meta.manager->swaps_by_proc_swaps, s->parameters_proc_swaps.what, first->parameters_proc_swaps.what, first);
70         else
71                 hashmap_remove(s->meta.manager->swaps_by_proc_swaps, s->parameters_proc_swaps.what);
72
73         free(s->parameters_proc_swaps.what);
74         s->parameters_proc_swaps.what = NULL;
75 }
76
77  static void swap_init(Unit *u) {
78         Swap *s = SWAP(u);
79
80         assert(s);
81         assert(s->meta.load_state == UNIT_STUB);
82
83         s->timeout_usec = DEFAULT_TIMEOUT_USEC;
84
85         exec_context_init(&s->exec_context);
86         s->exec_context.std_output = EXEC_OUTPUT_KMSG;
87
88         s->parameters_etc_fstab.priority = s->parameters_proc_swaps.priority = s->parameters_fragment.priority = -1;
89
90         s->timer_watch.type = WATCH_INVALID;
91
92         s->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
93
94         s->meta.ignore_on_isolate = true;
95 }
96
97 static void swap_unwatch_control_pid(Swap *s) {
98         assert(s);
99
100         if (s->control_pid <= 0)
101                 return;
102
103         unit_unwatch_pid(UNIT(s), s->control_pid);
104         s->control_pid = 0;
105 }
106
107 static void swap_done(Unit *u) {
108         Swap *s = SWAP(u);
109
110         assert(s);
111
112         swap_unset_proc_swaps(s);
113
114         free(s->what);
115         s->what = NULL;
116
117         free(s->parameters_etc_fstab.what);
118         free(s->parameters_fragment.what);
119         s->parameters_etc_fstab.what = s->parameters_fragment.what = NULL;
120
121         exec_context_done(&s->exec_context);
122         exec_command_done_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX);
123         s->control_command = NULL;
124
125         swap_unwatch_control_pid(s);
126
127         unit_unwatch_timer(u, &s->timer_watch);
128 }
129
130 int swap_add_one_mount_link(Swap *s, Mount *m) {
131          int r;
132
133         assert(s);
134         assert(m);
135
136         if (s->meta.load_state != UNIT_LOADED ||
137             m->meta.load_state != UNIT_LOADED)
138                 return 0;
139
140         if (is_device_path(s->what))
141                 return 0;
142
143         if (!path_startswith(s->what, m->where))
144                 return 0;
145
146         if ((r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true)) < 0)
147                 return r;
148
149         return 0;
150 }
151
152 static int swap_add_mount_links(Swap *s) {
153         Meta *other;
154         int r;
155
156         assert(s);
157
158         LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_MOUNT])
159                 if ((r = swap_add_one_mount_link(s, (Mount*) other)) < 0)
160                         return r;
161
162         return 0;
163 }
164
165 static int swap_add_target_links(Swap *s) {
166         Unit *tu;
167         SwapParameters *p;
168         int r;
169
170         assert(s);
171
172         if (s->from_fragment)
173                 p = &s->parameters_fragment;
174         else if (s->from_etc_fstab)
175                 p = &s->parameters_etc_fstab;
176         else
177                 return 0;
178
179         if ((r = manager_load_unit(s->meta.manager, SPECIAL_SWAP_TARGET, NULL, NULL, &tu)) < 0)
180                 return r;
181
182         if (!p->noauto &&
183             !p->nofail &&
184             (p->handle || s->meta.manager->swap_auto) &&
185             s->from_etc_fstab &&
186             s->meta.manager->running_as == MANAGER_SYSTEM)
187                 if ((r = unit_add_dependency(tu, UNIT_WANTS, UNIT(s), true)) < 0)
188                         return r;
189
190         return unit_add_dependency(UNIT(s), UNIT_BEFORE, tu, true);
191 }
192
193 static int swap_add_device_links(Swap *s) {
194         SwapParameters *p;
195
196         assert(s);
197
198         if (!s->what)
199                 return 0;
200
201         if (s->from_fragment)
202                 p = &s->parameters_fragment;
203         else if (s->from_etc_fstab)
204                 p = &s->parameters_etc_fstab;
205         else
206                 return 0;
207
208         if (is_device_path(s->what))
209                 return unit_add_node_link(UNIT(s), s->what,
210                                           !p->noauto && p->nofail &&
211                                           s->meta.manager->running_as == MANAGER_SYSTEM);
212         else
213                 /* File based swap devices need to be ordered after
214                  * remount-rootfs.service, since they might need a
215                  * writable file system. */
216                 return unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_REMOUNT_ROOTFS_SERVICE, NULL, true);
217 }
218
219 static int swap_add_default_dependencies(Swap *s) {
220         int r;
221
222         assert(s);
223
224         if (s->meta.manager->running_as == MANAGER_SYSTEM) {
225
226                 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, NULL, true)) < 0)
227                         return r;
228         }
229
230         return 0;
231 }
232
233 static int swap_verify(Swap *s) {
234         bool b;
235         char *e;
236
237         if (s->meta.load_state != UNIT_LOADED)
238                   return 0;
239
240         if (!(e = unit_name_from_path(s->what, ".swap")))
241                   return -ENOMEM;
242
243         b = unit_has_name(UNIT(s), e);
244         free(e);
245
246         if (!b) {
247                 log_error("%s: Value of \"What\" and unit name do not match, not loading.\n", s->meta.id);
248                 return -EINVAL;
249         }
250
251         if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
252                 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
253                 return -EINVAL;
254         }
255
256         return 0;
257 }
258
259 static int swap_load(Unit *u) {
260         int r;
261         Swap *s = SWAP(u);
262
263         assert(s);
264         assert(u->meta.load_state == UNIT_STUB);
265
266         /* Load a .swap file */
267         if ((r = unit_load_fragment_and_dropin_optional(u)) < 0)
268                 return r;
269
270         if (u->meta.load_state == UNIT_LOADED) {
271                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
272                         return r;
273
274                 if (s->meta.fragment_path)
275                         s->from_fragment = true;
276
277                 if (!s->what) {
278                         if (s->parameters_fragment.what)
279                                 s->what = strdup(s->parameters_fragment.what);
280                         else if (s->parameters_etc_fstab.what)
281                                 s->what = strdup(s->parameters_etc_fstab.what);
282                         else if (s->parameters_proc_swaps.what)
283                                 s->what = strdup(s->parameters_proc_swaps.what);
284                         else
285                                 s->what = unit_name_to_path(u->meta.id);
286
287                         if (!s->what)
288                                 return -ENOMEM;
289                 }
290
291                 path_kill_slashes(s->what);
292
293                 if (!s->meta.description)
294                         if ((r = unit_set_description(u, s->what)) < 0)
295                                 return r;
296
297                 if ((r = swap_add_device_links(s)) < 0)
298                         return r;
299
300                 if ((r = swap_add_mount_links(s)) < 0)
301                         return r;
302
303                 if ((r = swap_add_target_links(s)) < 0)
304                         return r;
305
306                 if ((r = unit_add_default_cgroups(u)) < 0)
307                         return r;
308
309                 if (s->meta.default_dependencies)
310                         if ((r = swap_add_default_dependencies(s)) < 0)
311                                 return r;
312         }
313
314         return swap_verify(s);
315 }
316
317 int swap_add_one(
318                 Manager *m,
319                 const char *what,
320                 const char *what_proc_swaps,
321                 int priority,
322                 bool noauto,
323                 bool nofail,
324                 bool handle,
325                 bool set_flags) {
326
327         Unit *u = NULL;
328         char *e = NULL, *wp = NULL;
329         bool delete = false;
330         int r;
331         SwapParameters *p;
332
333         assert(m);
334         assert(what);
335
336         if (!(e = unit_name_from_path(what, ".swap")))
337                 return -ENOMEM;
338
339         u = manager_get_unit(m, e);
340
341         if (what_proc_swaps &&
342             u &&
343             SWAP(u)->from_proc_swaps &&
344             !path_equal(SWAP(u)->parameters_proc_swaps.what, what_proc_swaps))
345                 return -EEXIST;
346
347         if (!u) {
348                 delete = true;
349
350                 if (!(u = unit_new(m))) {
351                         free(e);
352                         return -ENOMEM;
353                 }
354
355                 if ((r = unit_add_name(u, e)) < 0)
356                         goto fail;
357
358                 if (!(SWAP(u)->what = strdup(what))) {
359                         r = -ENOMEM;
360                         goto fail;
361                 }
362
363                 unit_add_to_load_queue(u);
364         } else
365                 delete = false;
366
367         if (what_proc_swaps) {
368                 Swap *first;
369
370                 p = &SWAP(u)->parameters_proc_swaps;
371
372                 if (!p->what) {
373                         if (!(wp = strdup(what_proc_swaps))) {
374                                 r = -ENOMEM;
375                                 goto fail;
376                         }
377
378                         if (!m->swaps_by_proc_swaps)
379                                 if (!(m->swaps_by_proc_swaps = hashmap_new(string_hash_func, string_compare_func))) {
380                                         r = -ENOMEM;
381                                         goto fail;
382                                 }
383
384                         free(p->what);
385                         p->what = wp;
386
387                         first = hashmap_get(m->swaps_by_proc_swaps, wp);
388                         LIST_PREPEND(Swap, same_proc_swaps, first, SWAP(u));
389
390                         if ((r = hashmap_replace(m->swaps_by_proc_swaps, wp, first)) < 0)
391                                 goto fail;
392                 }
393
394                 if (set_flags) {
395                         SWAP(u)->is_active = true;
396                         SWAP(u)->just_activated = !SWAP(u)->from_proc_swaps;
397                 }
398
399                 SWAP(u)->from_proc_swaps = true;
400
401         } else {
402                 p = &SWAP(u)->parameters_etc_fstab;
403
404                 if (!(wp = strdup(what))) {
405                         r = -ENOMEM;
406                         goto fail;
407                 }
408
409                 free(p->what);
410                 p->what = wp;
411
412                 SWAP(u)->from_etc_fstab = true;
413         }
414
415         p->priority = priority;
416         p->noauto = noauto;
417         p->nofail = nofail;
418         p->handle = handle;
419
420         unit_add_to_dbus_queue(u);
421
422         free(e);
423
424         return 0;
425
426 fail:
427         log_warning("Failed to load swap unit: %s", strerror(-r));
428
429         free(wp);
430         free(e);
431
432         if (delete && u)
433                 unit_free(u);
434
435         return r;
436 }
437
438 static int swap_process_new_swap(Manager *m, const char *device, int prio, bool set_flags) {
439         struct stat st;
440         int r = 0, k;
441
442         assert(m);
443
444         if (stat(device, &st) >= 0 && S_ISBLK(st.st_mode)) {
445                 struct udev_device *d;
446                 const char *dn;
447                 struct udev_list_entry *item = NULL, *first = NULL;
448
449                 /* So this is a proper swap device. Create swap units
450                  * for all names this swap device is known under */
451
452                 if (!(d = udev_device_new_from_devnum(m->udev, 'b', st.st_rdev)))
453                         return -ENOMEM;
454
455                 if ((dn = udev_device_get_devnode(d)))
456                         r = swap_add_one(m, dn, device, prio, false, false, false, set_flags);
457
458                 /* Add additional units for all symlinks */
459                 first = udev_device_get_devlinks_list_entry(d);
460                 udev_list_entry_foreach(item, first) {
461                         const char *p;
462
463                         /* Don't bother with the /dev/block links */
464                         p = udev_list_entry_get_name(item);
465
466                         if (path_startswith(p, "/dev/block/"))
467                                 continue;
468
469                         if (stat(p, &st) >= 0)
470                                 if ((!S_ISBLK(st.st_mode)) || st.st_rdev != udev_device_get_devnum(d))
471                                         continue;
472
473                         if ((k = swap_add_one(m, p, device, prio, false, false, false, set_flags)) < 0)
474                                 r = k;
475                 }
476
477                 udev_device_unref(d);
478         }
479
480         if ((k = swap_add_one(m, device, device, prio, false, false, false, set_flags)) < 0)
481                 r = k;
482
483         return r;
484 }
485
486 static void swap_set_state(Swap *s, SwapState state) {
487         SwapState old_state;
488
489         assert(s);
490
491         old_state = s->state;
492         s->state = state;
493
494         if (state != SWAP_ACTIVATING &&
495             state != SWAP_ACTIVATING_SIGTERM &&
496             state != SWAP_ACTIVATING_SIGKILL &&
497             state != SWAP_DEACTIVATING &&
498             state != SWAP_DEACTIVATING_SIGTERM &&
499             state != SWAP_DEACTIVATING_SIGKILL) {
500                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
501                 swap_unwatch_control_pid(s);
502                 s->control_command = NULL;
503                 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
504         }
505
506         if (state != old_state)
507                 log_debug("%s changed %s -> %s",
508                           s->meta.id,
509                           swap_state_to_string(old_state),
510                           swap_state_to_string(state));
511
512         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
513 }
514
515 static int swap_coldplug(Unit *u) {
516         Swap *s = SWAP(u);
517         SwapState new_state = SWAP_DEAD;
518         int r;
519
520         assert(s);
521         assert(s->state == SWAP_DEAD);
522
523         if (s->deserialized_state != s->state)
524                 new_state = s->deserialized_state;
525         else if (s->from_proc_swaps)
526                 new_state = SWAP_ACTIVE;
527
528         if (new_state != s->state) {
529
530                 if (new_state == SWAP_ACTIVATING ||
531                     new_state == SWAP_ACTIVATING_SIGTERM ||
532                     new_state == SWAP_ACTIVATING_SIGKILL ||
533                     new_state == SWAP_DEACTIVATING ||
534                     new_state == SWAP_DEACTIVATING_SIGTERM ||
535                     new_state == SWAP_DEACTIVATING_SIGKILL) {
536
537                         if (s->control_pid <= 0)
538                                 return -EBADMSG;
539
540                         if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
541                                 return r;
542
543                         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
544                                 return r;
545                 }
546
547                 swap_set_state(s, new_state);
548         }
549
550         return 0;
551 }
552
553 static void swap_dump(Unit *u, FILE *f, const char *prefix) {
554         Swap *s = SWAP(u);
555         SwapParameters *p;
556
557         assert(s);
558         assert(f);
559
560         if (s->from_proc_swaps)
561                 p = &s->parameters_proc_swaps;
562         else if (s->from_fragment)
563                 p = &s->parameters_fragment;
564         else
565                 p = &s->parameters_etc_fstab;
566
567         fprintf(f,
568                 "%sSwap State: %s\n"
569                 "%sWhat: %s\n"
570                 "%sPriority: %i\n"
571                 "%sNoAuto: %s\n"
572                 "%sNoFail: %s\n"
573                 "%sHandle: %s\n"
574                 "%sFrom /etc/fstab: %s\n"
575                 "%sFrom /proc/swaps: %s\n"
576                 "%sFrom fragment: %s\n",
577                 prefix, swap_state_to_string(s->state),
578                 prefix, s->what,
579                 prefix, p->priority,
580                 prefix, yes_no(p->noauto),
581                 prefix, yes_no(p->nofail),
582                 prefix, yes_no(p->handle),
583                 prefix, yes_no(s->from_etc_fstab),
584                 prefix, yes_no(s->from_proc_swaps),
585                 prefix, yes_no(s->from_fragment));
586
587         if (s->control_pid > 0)
588                 fprintf(f,
589                         "%sControl PID: %lu\n",
590                         prefix, (unsigned long) s->control_pid);
591
592         exec_context_dump(&s->exec_context, f, prefix);
593 }
594
595 static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) {
596         pid_t pid;
597         int r;
598
599         assert(s);
600         assert(c);
601         assert(_pid);
602
603         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
604                 goto fail;
605
606         if ((r = exec_spawn(c,
607                             NULL,
608                             &s->exec_context,
609                             NULL, 0,
610                             s->meta.manager->environment,
611                             true,
612                             true,
613                             true,
614                             s->meta.manager->confirm_spawn,
615                             s->meta.cgroup_bondings,
616                             &pid)) < 0)
617                 goto fail;
618
619         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
620                 /* FIXME: we need to do something here */
621                 goto fail;
622
623         *_pid = pid;
624
625         return 0;
626
627 fail:
628         unit_unwatch_timer(UNIT(s), &s->timer_watch);
629
630         return r;
631 }
632
633 static void swap_enter_dead(Swap *s, bool success) {
634         assert(s);
635
636         if (!success)
637                 s->failure = true;
638
639         swap_set_state(s, s->failure ? SWAP_FAILED : SWAP_DEAD);
640 }
641
642 static void swap_enter_active(Swap *s, bool success) {
643         assert(s);
644
645         if (!success)
646                 s->failure = true;
647
648         swap_set_state(s, SWAP_ACTIVE);
649 }
650
651 static void swap_enter_signal(Swap *s, SwapState state, bool success) {
652         int r;
653         Set *pid_set = NULL;
654         bool wait_for_exit = false;
655
656         assert(s);
657
658         if (!success)
659                 s->failure = true;
660
661         if (s->exec_context.kill_mode != KILL_NONE) {
662                 int sig = (state == SWAP_ACTIVATING_SIGTERM ||
663                            state == SWAP_DEACTIVATING_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
664
665                 if (s->control_pid > 0) {
666                         if (kill_and_sigcont(s->control_pid, sig) < 0 && errno != ESRCH)
667
668                                 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
669                         else
670                                 wait_for_exit = true;
671                 }
672
673                 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
674
675                         if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
676                                 r = -ENOMEM;
677                                 goto fail;
678                         }
679
680                         /* Exclude the control pid from being killed via the cgroup */
681                         if (s->control_pid > 0)
682                                 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
683                                         goto fail;
684
685                         if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, true, pid_set)) < 0) {
686                                 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
687                                         log_warning("Failed to kill control group: %s", strerror(-r));
688                         } else if (r > 0)
689                                 wait_for_exit = true;
690
691                         set_free(pid_set);
692                         pid_set = NULL;
693                 }
694         }
695
696         if (wait_for_exit) {
697                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
698                         goto fail;
699
700                 swap_set_state(s, state);
701         } else
702                 swap_enter_dead(s, true);
703
704         return;
705
706 fail:
707         log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
708
709         swap_enter_dead(s, false);
710
711         if (pid_set)
712                 set_free(pid_set);
713 }
714
715 static void swap_enter_activating(Swap *s) {
716         int r, priority;
717
718         assert(s);
719
720         s->control_command_id = SWAP_EXEC_ACTIVATE;
721         s->control_command = s->exec_command + SWAP_EXEC_ACTIVATE;
722
723         if (s->from_fragment)
724                 priority = s->parameters_fragment.priority;
725         else if (s->from_etc_fstab)
726                 priority = s->parameters_etc_fstab.priority;
727         else
728                 priority = -1;
729
730         if (priority >= 0) {
731                 char p[LINE_MAX];
732
733                 snprintf(p, sizeof(p), "%i", priority);
734                 char_array_0(p);
735
736                 r = exec_command_set(
737                                 s->control_command,
738                                 "/sbin/swapon",
739                                 "-p",
740                                 p,
741                                 s->what,
742                                 NULL);
743         } else
744                 r = exec_command_set(
745                                 s->control_command,
746                                 "/sbin/swapon",
747                                 s->what,
748                                 NULL);
749
750         if (r < 0)
751                 goto fail;
752
753         swap_unwatch_control_pid(s);
754
755         if ((r = swap_spawn(s, s->control_command, &s->control_pid)) < 0)
756                 goto fail;
757
758         swap_set_state(s, SWAP_ACTIVATING);
759
760         return;
761
762 fail:
763         log_warning("%s failed to run 'swapon' task: %s", s->meta.id, strerror(-r));
764         swap_enter_dead(s, false);
765 }
766
767 static void swap_enter_deactivating(Swap *s, bool success) {
768         int r;
769
770         assert(s);
771
772         if (!success)
773                 s->failure = true;
774
775         s->control_command_id = SWAP_EXEC_DEACTIVATE;
776         s->control_command = s->exec_command + SWAP_EXEC_DEACTIVATE;
777
778         if ((r = exec_command_set(
779                              s->control_command,
780                              "/sbin/swapoff",
781                              s->what,
782                              NULL)) < 0)
783                 goto fail;
784
785         swap_unwatch_control_pid(s);
786
787         if ((r = swap_spawn(s, s->control_command, &s->control_pid)) < 0)
788                 goto fail;
789
790         swap_set_state(s, SWAP_DEACTIVATING);
791
792         return;
793
794 fail:
795         log_warning("%s failed to run 'swapoff' task: %s", s->meta.id, strerror(-r));
796         swap_enter_active(s, false);
797 }
798
799 static int swap_start(Unit *u) {
800         Swap *s = SWAP(u);
801
802         assert(s);
803
804         /* We cannot fulfill this request right now, try again later
805          * please! */
806
807         if (s->state == SWAP_DEACTIVATING ||
808             s->state == SWAP_DEACTIVATING_SIGTERM ||
809             s->state == SWAP_DEACTIVATING_SIGKILL ||
810             s->state == SWAP_ACTIVATING_SIGTERM ||
811             s->state == SWAP_ACTIVATING_SIGKILL)
812                 return -EAGAIN;
813
814         if (s->state == SWAP_ACTIVATING)
815                 return 0;
816
817         assert(s->state == SWAP_DEAD || s->state == SWAP_FAILED);
818
819         s->failure = false;
820         swap_enter_activating(s);
821         return 0;
822 }
823
824 static int swap_stop(Unit *u) {
825         Swap *s = SWAP(u);
826
827         assert(s);
828
829         if (s->state == SWAP_DEACTIVATING ||
830             s->state == SWAP_DEACTIVATING_SIGTERM ||
831             s->state == SWAP_DEACTIVATING_SIGKILL ||
832             s->state == SWAP_ACTIVATING_SIGTERM ||
833             s->state == SWAP_ACTIVATING_SIGKILL)
834                 return 0;
835
836         assert(s->state == SWAP_ACTIVATING ||
837                s->state == SWAP_ACTIVE);
838
839         swap_enter_deactivating(s, true);
840         return 0;
841 }
842
843 static int swap_serialize(Unit *u, FILE *f, FDSet *fds) {
844         Swap *s = SWAP(u);
845
846         assert(s);
847         assert(f);
848         assert(fds);
849
850         unit_serialize_item(u, f, "state", swap_state_to_string(s->state));
851         unit_serialize_item(u, f, "failure", yes_no(s->failure));
852
853         if (s->control_pid > 0)
854                 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
855
856         if (s->control_command_id >= 0)
857                 unit_serialize_item(u, f, "control-command", swap_exec_command_to_string(s->control_command_id));
858
859         return 0;
860 }
861
862 static int swap_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
863         Swap *s = SWAP(u);
864
865         assert(s);
866         assert(fds);
867
868         if (streq(key, "state")) {
869                 SwapState state;
870
871                 if ((state = swap_state_from_string(value)) < 0)
872                         log_debug("Failed to parse state value %s", value);
873                 else
874                         s->deserialized_state = state;
875         } else if (streq(key, "failure")) {
876                 int b;
877
878                 if ((b = parse_boolean(value)) < 0)
879                         log_debug("Failed to parse failure value %s", value);
880                 else
881                         s->failure = b || s->failure;
882
883         } else if (streq(key, "control-pid")) {
884                 pid_t pid;
885
886                 if (parse_pid(value, &pid) < 0)
887                         log_debug("Failed to parse control-pid value %s", value);
888                 else
889                         s->control_pid = pid;
890
891         } else if (streq(key, "control-command")) {
892                 SwapExecCommand id;
893
894                 if ((id = swap_exec_command_from_string(value)) < 0)
895                         log_debug("Failed to parse exec-command value %s", value);
896                 else {
897                         s->control_command_id = id;
898                         s->control_command = s->exec_command + id;
899                 }
900
901         } else
902                 log_debug("Unknown serialization key '%s'", key);
903
904         return 0;
905 }
906
907 static UnitActiveState swap_active_state(Unit *u) {
908         assert(u);
909
910         return state_translation_table[SWAP(u)->state];
911 }
912
913 static const char *swap_sub_state_to_string(Unit *u) {
914         assert(u);
915
916         return swap_state_to_string(SWAP(u)->state);
917 }
918
919 static bool swap_check_gc(Unit *u) {
920         Swap *s = SWAP(u);
921
922         assert(s);
923
924         return s->from_etc_fstab || s->from_proc_swaps;
925 }
926
927 static void swap_sigchld_event(Unit *u, pid_t pid, int code, int status) {
928         Swap *s = SWAP(u);
929         bool success;
930
931         assert(s);
932         assert(pid >= 0);
933
934         if (pid != s->control_pid)
935                 return;
936
937         s->control_pid = 0;
938
939         success = is_clean_exit(code, status);
940         s->failure = s->failure || !success;
941
942         if (s->control_command) {
943                 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
944                 s->control_command = NULL;
945                 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
946         }
947
948         log_full(success ? LOG_DEBUG : LOG_NOTICE,
949                  "%s swap process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
950
951         switch (s->state) {
952
953         case SWAP_ACTIVATING:
954         case SWAP_ACTIVATING_SIGTERM:
955         case SWAP_ACTIVATING_SIGKILL:
956
957                 if (success)
958                         swap_enter_active(s, true);
959                 else
960                         swap_enter_dead(s, false);
961                 break;
962
963         case SWAP_DEACTIVATING:
964         case SWAP_DEACTIVATING_SIGKILL:
965         case SWAP_DEACTIVATING_SIGTERM:
966
967                 if (success)
968                         swap_enter_dead(s, true);
969                 else
970                         swap_enter_dead(s, false);
971                 break;
972
973         default:
974                 assert_not_reached("Uh, control process died at wrong time.");
975         }
976
977         /* Notify clients about changed exit status */
978         unit_add_to_dbus_queue(u);
979
980         /* Request a reload of /proc/swaps, so that following units
981          * can follow our state change */
982         u->meta.manager->request_reload = true;
983 }
984
985 static void swap_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
986         Swap *s = SWAP(u);
987
988         assert(s);
989         assert(elapsed == 1);
990         assert(w == &s->timer_watch);
991
992         switch (s->state) {
993
994         case SWAP_ACTIVATING:
995                 log_warning("%s activation timed out. Stopping.", u->meta.id);
996                 swap_enter_signal(s, SWAP_ACTIVATING_SIGTERM, false);
997                 break;
998
999         case SWAP_DEACTIVATING:
1000                 log_warning("%s deactivation timed out. Stopping.", u->meta.id);
1001                 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, false);
1002                 break;
1003
1004         case SWAP_ACTIVATING_SIGTERM:
1005                 if (s->exec_context.send_sigkill) {
1006                         log_warning("%s activation timed out. Killing.", u->meta.id);
1007                         swap_enter_signal(s, SWAP_ACTIVATING_SIGKILL, false);
1008                 } else {
1009                         log_warning("%s activation timed out. Skipping SIGKILL. Ignoring.", u->meta.id);
1010                         swap_enter_dead(s, false);
1011                 }
1012                 break;
1013
1014         case SWAP_DEACTIVATING_SIGTERM:
1015                 if (s->exec_context.send_sigkill) {
1016                         log_warning("%s deactivation timed out. Killing.", u->meta.id);
1017                         swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, false);
1018                 } else {
1019                         log_warning("%s deactivation timed out. Skipping SIGKILL. Ignoring.", u->meta.id);
1020                         swap_enter_dead(s, false);
1021                 }
1022                 break;
1023
1024         case SWAP_ACTIVATING_SIGKILL:
1025         case SWAP_DEACTIVATING_SIGKILL:
1026                 log_warning("%s swap process still around after SIGKILL. Ignoring.", u->meta.id);
1027                 swap_enter_dead(s, false);
1028                 break;
1029
1030         default:
1031                 assert_not_reached("Timeout at wrong time.");
1032         }
1033 }
1034
1035 static int swap_load_proc_swaps(Manager *m, bool set_flags) {
1036         unsigned i;
1037         int r = 0;
1038
1039         assert(m);
1040
1041         rewind(m->proc_swaps);
1042
1043         (void) fscanf(m->proc_swaps, "%*s %*s %*s %*s %*s\n");
1044
1045         for (i = 1;; i++) {
1046                 char *dev = NULL, *d;
1047                 int prio = 0, k;
1048
1049                 if ((k = fscanf(m->proc_swaps,
1050                                 "%ms "  /* device/file */
1051                                 "%*s "  /* type of swap */
1052                                 "%*s "  /* swap size */
1053                                 "%*s "  /* used */
1054                                 "%i\n", /* priority */
1055                                 &dev, &prio)) != 2) {
1056
1057                         if (k == EOF)
1058                                 break;
1059
1060                         log_warning("Failed to parse /proc/swaps:%u.", i);
1061                         free(dev);
1062                         continue;
1063                 }
1064
1065                 d = cunescape(dev);
1066                 free(dev);
1067
1068                 if (!d)
1069                         return -ENOMEM;
1070
1071                 k = swap_process_new_swap(m, d, prio, set_flags);
1072                 free(d);
1073
1074                 if (k < 0)
1075                         r = k;
1076         }
1077
1078         return r;
1079 }
1080
1081 int swap_dispatch_reload(Manager *m) {
1082         /* This function should go as soon as the kernel properly notifies us */
1083
1084         if (_likely_(!m->request_reload))
1085                 return 0;
1086
1087         m->request_reload = false;
1088
1089         return swap_fd_event(m, EPOLLPRI);
1090 }
1091
1092 int swap_fd_event(Manager *m, int events) {
1093         Meta *meta;
1094         int r;
1095
1096         assert(m);
1097         assert(events & EPOLLPRI);
1098
1099         if ((r = swap_load_proc_swaps(m, true)) < 0) {
1100                 log_error("Failed to reread /proc/swaps: %s", strerror(-r));
1101
1102                 /* Reset flags, just in case, for late calls */
1103                 LIST_FOREACH(units_per_type, meta, m->units_per_type[UNIT_SWAP]) {
1104                         Swap *swap = (Swap*) meta;
1105
1106                         swap->is_active = swap->just_activated = false;
1107                 }
1108
1109                 return 0;
1110         }
1111
1112         manager_dispatch_load_queue(m);
1113
1114         LIST_FOREACH(units_per_type, meta, m->units_per_type[UNIT_SWAP]) {
1115                 Swap *swap = (Swap*) meta;
1116
1117                 if (!swap->is_active) {
1118                         /* This has just been deactivated */
1119
1120                         swap->from_proc_swaps = false;
1121                         swap_unset_proc_swaps(swap);
1122
1123                         switch (swap->state) {
1124
1125                         case SWAP_ACTIVE:
1126                                 swap_enter_dead(swap, true);
1127                                 break;
1128
1129                         default:
1130                                 swap_set_state(swap, swap->state);
1131                                 break;
1132                         }
1133
1134                 } else if (swap->just_activated) {
1135
1136                         /* New swap entry */
1137
1138                         switch (swap->state) {
1139
1140                         case SWAP_DEAD:
1141                         case SWAP_FAILED:
1142                                 swap_enter_active(swap, true);
1143                                 break;
1144
1145                         default:
1146                                 /* Nothing really changed, but let's
1147                                  * issue an notification call
1148                                  * nonetheless, in case somebody is
1149                                  * waiting for this. */
1150                                 swap_set_state(swap, swap->state);
1151                                 break;
1152                         }
1153                 }
1154
1155                 /* Reset the flags for later calls */
1156                 swap->is_active = swap->just_activated = false;
1157         }
1158
1159         return 1;
1160 }
1161
1162 static Unit *swap_following(Unit *u) {
1163         Swap *s = SWAP(u);
1164         Swap *other, *first = NULL;
1165
1166         assert(s);
1167
1168         if (streq_ptr(s->what, s->parameters_proc_swaps.what))
1169                 return NULL;
1170
1171         /* Make everybody follow the unit that's named after the swap
1172          * device in the kernel */
1173
1174         LIST_FOREACH_AFTER(same_proc_swaps, other, s)
1175                 if (streq_ptr(other->what, other->parameters_proc_swaps.what))
1176                         return UNIT(other);
1177
1178         LIST_FOREACH_BEFORE(same_proc_swaps, other, s) {
1179                 if (streq_ptr(other->what, other->parameters_proc_swaps.what))
1180                         return UNIT(other);
1181
1182                 first = other;
1183         }
1184
1185         return UNIT(first);
1186 }
1187
1188 static int swap_following_set(Unit *u, Set **_set) {
1189         Swap *s = SWAP(u);
1190         Swap *other;
1191         Set *set;
1192         int r;
1193
1194         assert(s);
1195         assert(_set);
1196
1197         if (LIST_JUST_US(same_proc_swaps, s)) {
1198                 *_set = NULL;
1199                 return 0;
1200         }
1201
1202         if (!(set = set_new(NULL, NULL)))
1203                 return -ENOMEM;
1204
1205         LIST_FOREACH_AFTER(same_proc_swaps, other, s)
1206                 if ((r = set_put(set, other)) < 0)
1207                         goto fail;
1208
1209         LIST_FOREACH_BEFORE(same_proc_swaps, other, s)
1210                 if ((r = set_put(set, other)) < 0)
1211                         goto fail;
1212
1213         *_set = set;
1214         return 1;
1215
1216 fail:
1217         set_free(set);
1218         return r;
1219 }
1220
1221 static void swap_shutdown(Manager *m) {
1222         assert(m);
1223
1224         if (m->proc_swaps) {
1225                 fclose(m->proc_swaps);
1226                 m->proc_swaps = NULL;
1227         }
1228
1229         hashmap_free(m->swaps_by_proc_swaps);
1230         m->swaps_by_proc_swaps = NULL;
1231 }
1232
1233 static int swap_enumerate(Manager *m) {
1234         int r;
1235         struct epoll_event ev;
1236         assert(m);
1237
1238         if (!m->proc_swaps) {
1239                 if (!(m->proc_swaps = fopen("/proc/swaps", "re")))
1240                         return -errno;
1241
1242                 m->swap_watch.type = WATCH_SWAP;
1243                 m->swap_watch.fd = fileno(m->proc_swaps);
1244
1245                 zero(ev);
1246                 ev.events = EPOLLPRI;
1247                 ev.data.ptr = &m->swap_watch;
1248
1249                 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->swap_watch.fd, &ev) < 0)
1250                         return -errno;
1251         }
1252
1253         /* We rely on mount.c to load /etc/fstab for us */
1254
1255         if ((r = swap_load_proc_swaps(m, false)) < 0)
1256                 swap_shutdown(m);
1257
1258         return r;
1259 }
1260
1261 static void swap_reset_failed(Unit *u) {
1262         Swap *s = SWAP(u);
1263
1264         assert(s);
1265
1266         if (s->state == SWAP_FAILED)
1267                 swap_set_state(s, SWAP_DEAD);
1268
1269         s->failure = false;
1270 }
1271
1272 static int swap_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
1273         Swap *s = SWAP(u);
1274         int r = 0;
1275         Set *pid_set = NULL;
1276
1277         assert(s);
1278
1279         if (who == KILL_MAIN) {
1280                 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "Swap units have no main processes");
1281                 return -EINVAL;
1282         }
1283
1284         if (s->control_pid <= 0 && who == KILL_CONTROL) {
1285                 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
1286                 return -ENOENT;
1287         }
1288
1289         if (s->control_pid > 0)
1290                 if (kill(s->control_pid, signo) < 0)
1291                         r = -errno;
1292
1293         if (mode == KILL_CONTROL_GROUP) {
1294                 int q;
1295
1296                 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
1297                         return -ENOMEM;
1298
1299                 /* Exclude the control pid from being killed via the cgroup */
1300                 if (s->control_pid > 0)
1301                         if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
1302                                 r = q;
1303                                 goto finish;
1304                         }
1305
1306                 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, false, pid_set)) < 0)
1307                         if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1308                                 r = q;
1309         }
1310
1311 finish:
1312         if (pid_set)
1313                 set_free(pid_set);
1314
1315         return r;
1316 }
1317
1318 static const char* const swap_state_table[_SWAP_STATE_MAX] = {
1319         [SWAP_DEAD] = "dead",
1320         [SWAP_ACTIVATING] = "activating",
1321         [SWAP_ACTIVE] = "active",
1322         [SWAP_DEACTIVATING] = "deactivating",
1323         [SWAP_ACTIVATING_SIGTERM] = "activating-sigterm",
1324         [SWAP_ACTIVATING_SIGKILL] = "activating-sigkill",
1325         [SWAP_DEACTIVATING_SIGTERM] = "deactivating-sigterm",
1326         [SWAP_DEACTIVATING_SIGKILL] = "deactivating-sigkill",
1327         [SWAP_FAILED] = "failed"
1328 };
1329
1330 DEFINE_STRING_TABLE_LOOKUP(swap_state, SwapState);
1331
1332 static const char* const swap_exec_command_table[_SWAP_EXEC_COMMAND_MAX] = {
1333         [SWAP_EXEC_ACTIVATE] = "ExecActivate",
1334         [SWAP_EXEC_DEACTIVATE] = "ExecDeactivate",
1335 };
1336
1337 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command, SwapExecCommand);
1338
1339 const UnitVTable swap_vtable = {
1340         .suffix = ".swap",
1341
1342         .no_alias = true,
1343         .no_instances = true,
1344         .show_status = true,
1345
1346         .init = swap_init,
1347         .load = swap_load,
1348         .done = swap_done,
1349
1350         .coldplug = swap_coldplug,
1351
1352         .dump = swap_dump,
1353
1354         .start = swap_start,
1355         .stop = swap_stop,
1356
1357         .kill = swap_kill,
1358
1359         .serialize = swap_serialize,
1360         .deserialize_item = swap_deserialize_item,
1361
1362         .active_state = swap_active_state,
1363         .sub_state_to_string = swap_sub_state_to_string,
1364
1365         .check_gc = swap_check_gc,
1366
1367         .sigchld_event = swap_sigchld_event,
1368         .timer_event = swap_timer_event,
1369
1370         .reset_failed = swap_reset_failed,
1371
1372         .bus_interface = "org.freedesktop.systemd1.Swap",
1373         .bus_message_handler = bus_swap_message_handler,
1374         .bus_invalidating_properties =  bus_swap_invalidating_properties,
1375
1376         .following = swap_following,
1377         .following_set = swap_following_set,
1378
1379         .enumerate = swap_enumerate,
1380         .shutdown = swap_shutdown
1381 };