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