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