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