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