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