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