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