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