1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <errno.h>
4 #include <sys/epoll.h>
5 #include <sys/stat.h>
6 #include <unistd.h>
7 
8 #include "sd-device.h"
9 
10 #include "alloc-util.h"
11 #include "dbus-swap.h"
12 #include "dbus-unit.h"
13 #include "device-util.h"
14 #include "device.h"
15 #include "escape.h"
16 #include "exit-status.h"
17 #include "fd-util.h"
18 #include "format-util.h"
19 #include "fstab-util.h"
20 #include "parse-util.h"
21 #include "path-util.h"
22 #include "process-util.h"
23 #include "serialize.h"
24 #include "special.h"
25 #include "string-table.h"
26 #include "string-util.h"
27 #include "swap.h"
28 #include "unit-name.h"
29 #include "unit.h"
30 #include "virt.h"
31 
32 static const UnitActiveState state_translation_table[_SWAP_STATE_MAX] = {
33         [SWAP_DEAD] = UNIT_INACTIVE,
34         [SWAP_ACTIVATING] = UNIT_ACTIVATING,
35         [SWAP_ACTIVATING_DONE] = UNIT_ACTIVE,
36         [SWAP_ACTIVE] = UNIT_ACTIVE,
37         [SWAP_DEACTIVATING] = UNIT_DEACTIVATING,
38         [SWAP_DEACTIVATING_SIGTERM] = UNIT_DEACTIVATING,
39         [SWAP_DEACTIVATING_SIGKILL] = UNIT_DEACTIVATING,
40         [SWAP_FAILED] = UNIT_FAILED,
41         [SWAP_CLEANING] = UNIT_MAINTENANCE,
42 };
43 
44 static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
45 static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
46 static int swap_process_proc_swaps(Manager *m);
47 
SWAP_STATE_WITH_PROCESS(SwapState state)48 static bool SWAP_STATE_WITH_PROCESS(SwapState state) {
49         return IN_SET(state,
50                       SWAP_ACTIVATING,
51                       SWAP_ACTIVATING_DONE,
52                       SWAP_DEACTIVATING,
53                       SWAP_DEACTIVATING_SIGTERM,
54                       SWAP_DEACTIVATING_SIGKILL,
55                       SWAP_CLEANING);
56 }
57 
swap_active_state(Unit * u)58 _pure_ static UnitActiveState swap_active_state(Unit *u) {
59         assert(u);
60 
61         return state_translation_table[SWAP(u)->state];
62 }
63 
swap_sub_state_to_string(Unit * u)64 _pure_ static const char *swap_sub_state_to_string(Unit *u) {
65         assert(u);
66 
67         return swap_state_to_string(SWAP(u)->state);
68 }
69 
swap_may_gc(Unit * u)70 _pure_ static bool swap_may_gc(Unit *u) {
71         Swap *s = SWAP(u);
72 
73         assert(s);
74 
75         if (s->from_proc_swaps)
76                 return false;
77 
78         return true;
79 }
80 
swap_is_extrinsic(Unit * u)81 _pure_ static bool swap_is_extrinsic(Unit *u) {
82         assert(SWAP(u));
83 
84         return MANAGER_IS_USER(u->manager);
85 }
86 
swap_unset_proc_swaps(Swap * s)87 static void swap_unset_proc_swaps(Swap *s) {
88         assert(s);
89 
90         if (!s->from_proc_swaps)
91                 return;
92 
93         s->parameters_proc_swaps.what = mfree(s->parameters_proc_swaps.what);
94         s->from_proc_swaps = false;
95 }
96 
swap_set_devnode(Swap * s,const char * devnode)97 static int swap_set_devnode(Swap *s, const char *devnode) {
98         Hashmap *swaps;
99         Swap *first;
100         int r;
101 
102         assert(s);
103 
104         r = hashmap_ensure_allocated(&UNIT(s)->manager->swaps_by_devnode, &path_hash_ops);
105         if (r < 0)
106                 return r;
107 
108         swaps = UNIT(s)->manager->swaps_by_devnode;
109 
110         if (s->devnode) {
111                 first = hashmap_get(swaps, s->devnode);
112 
113                 LIST_REMOVE(same_devnode, first, s);
114                 if (first)
115                         hashmap_replace(swaps, first->devnode, first);
116                 else
117                         hashmap_remove(swaps, s->devnode);
118 
119                 s->devnode = mfree(s->devnode);
120         }
121 
122         if (devnode) {
123                 s->devnode = strdup(devnode);
124                 if (!s->devnode)
125                         return -ENOMEM;
126 
127                 first = hashmap_get(swaps, s->devnode);
128                 LIST_PREPEND(same_devnode, first, s);
129 
130                 return hashmap_replace(swaps, first->devnode, first);
131         }
132 
133         return 0;
134 }
135 
swap_init(Unit * u)136 static void swap_init(Unit *u) {
137         Swap *s = SWAP(u);
138 
139         assert(s);
140         assert(UNIT(s)->load_state == UNIT_STUB);
141 
142         s->timeout_usec = u->manager->default_timeout_start_usec;
143 
144         s->exec_context.std_output = u->manager->default_std_output;
145         s->exec_context.std_error = u->manager->default_std_error;
146 
147         s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
148 
149         u->ignore_on_isolate = true;
150 }
151 
swap_unwatch_control_pid(Swap * s)152 static void swap_unwatch_control_pid(Swap *s) {
153         assert(s);
154 
155         if (s->control_pid <= 0)
156                 return;
157 
158         unit_unwatch_pid(UNIT(s), TAKE_PID(s->control_pid));
159 }
160 
swap_done(Unit * u)161 static void swap_done(Unit *u) {
162         Swap *s = SWAP(u);
163 
164         assert(s);
165 
166         swap_unset_proc_swaps(s);
167         swap_set_devnode(s, NULL);
168 
169         s->what = mfree(s->what);
170         s->parameters_fragment.what = mfree(s->parameters_fragment.what);
171         s->parameters_fragment.options = mfree(s->parameters_fragment.options);
172 
173         s->exec_runtime = exec_runtime_unref(s->exec_runtime, false);
174         exec_command_done_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX);
175         s->control_command = NULL;
176 
177         dynamic_creds_unref(&s->dynamic_creds);
178 
179         swap_unwatch_control_pid(s);
180 
181         s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
182 }
183 
swap_arm_timer(Swap * s,usec_t usec)184 static int swap_arm_timer(Swap *s, usec_t usec) {
185         int r;
186 
187         assert(s);
188 
189         if (s->timer_event_source) {
190                 r = sd_event_source_set_time(s->timer_event_source, usec);
191                 if (r < 0)
192                         return r;
193 
194                 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
195         }
196 
197         if (usec == USEC_INFINITY)
198                 return 0;
199 
200         r = sd_event_add_time(
201                         UNIT(s)->manager->event,
202                         &s->timer_event_source,
203                         CLOCK_MONOTONIC,
204                         usec, 0,
205                         swap_dispatch_timer, s);
206         if (r < 0)
207                 return r;
208 
209         (void) sd_event_source_set_description(s->timer_event_source, "swap-timer");
210 
211         return 0;
212 }
213 
swap_get_parameters(Swap * s)214 static SwapParameters* swap_get_parameters(Swap *s) {
215         assert(s);
216 
217         if (s->from_proc_swaps)
218                 return &s->parameters_proc_swaps;
219 
220         if (s->from_fragment)
221                 return &s->parameters_fragment;
222 
223         return NULL;
224 }
225 
swap_add_device_dependencies(Swap * s)226 static int swap_add_device_dependencies(Swap *s) {
227         UnitDependencyMask mask;
228         SwapParameters *p;
229         int r;
230 
231         assert(s);
232 
233         if (!s->what)
234                 return 0;
235 
236         p = swap_get_parameters(s);
237         if (!p || !p->what)
238                 return 0;
239 
240         mask = s->from_proc_swaps ? UNIT_DEPENDENCY_PROC_SWAP : UNIT_DEPENDENCY_FILE;
241 
242         if (is_device_path(p->what)) {
243                 r = unit_add_node_dependency(UNIT(s), p->what, UNIT_REQUIRES, mask);
244                 if (r < 0)
245                         return r;
246 
247                 return unit_add_blockdev_dependency(UNIT(s), p->what, mask);
248         }
249 
250         /* File based swap devices need to be ordered after systemd-remount-fs.service, since they might need
251          * a writable file system. */
252         return unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_REMOUNT_FS_SERVICE, true, mask);
253 }
254 
swap_add_default_dependencies(Swap * s)255 static int swap_add_default_dependencies(Swap *s) {
256         int r;
257 
258         assert(s);
259 
260         if (!UNIT(s)->default_dependencies)
261                 return 0;
262 
263         if (!MANAGER_IS_SYSTEM(UNIT(s)->manager))
264                 return 0;
265 
266         if (detect_container() > 0)
267                 return 0;
268 
269         /* swap units generated for the swap dev links are missing the
270          * ordering dep against the swap target. */
271         r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SWAP_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
272         if (r < 0)
273                 return r;
274 
275         return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
276 }
277 
swap_verify(Swap * s)278 static int swap_verify(Swap *s) {
279         _cleanup_free_ char *e = NULL;
280         int r;
281 
282         assert(UNIT(s)->load_state == UNIT_LOADED);
283 
284         r = unit_name_from_path(s->what, ".swap", &e);
285         if (r < 0)
286                 return log_unit_error_errno(UNIT(s), r, "Failed to generate unit name from path: %m");
287 
288         if (!unit_has_name(UNIT(s), e))
289                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Value of What= and unit name do not match, not loading.");
290 
291         if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP)
292                 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.");
293 
294         return 0;
295 }
296 
swap_load_devnode(Swap * s)297 static int swap_load_devnode(Swap *s) {
298         _cleanup_(sd_device_unrefp) sd_device *d = NULL;
299         struct stat st;
300         const char *p;
301         int r;
302 
303         assert(s);
304 
305         if (stat(s->what, &st) < 0 || !S_ISBLK(st.st_mode))
306                 return 0;
307 
308         r = sd_device_new_from_stat_rdev(&d, &st);
309         if (r < 0) {
310                 log_unit_full_errno(UNIT(s), r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
311                                     "Failed to allocate device for swap %s: %m", s->what);
312                 return 0;
313         }
314 
315         if (sd_device_get_devname(d, &p) < 0)
316                 return 0;
317 
318         return swap_set_devnode(s, p);
319 }
320 
swap_add_extras(Swap * s)321 static int swap_add_extras(Swap *s) {
322         int r;
323 
324         assert(s);
325 
326         if (UNIT(s)->fragment_path)
327                 s->from_fragment = true;
328 
329         if (!s->what) {
330                 if (s->parameters_fragment.what)
331                         s->what = strdup(s->parameters_fragment.what);
332                 else if (s->parameters_proc_swaps.what)
333                         s->what = strdup(s->parameters_proc_swaps.what);
334                 else {
335                         r = unit_name_to_path(UNIT(s)->id, &s->what);
336                         if (r < 0)
337                                 return r;
338                 }
339 
340                 if (!s->what)
341                         return -ENOMEM;
342         }
343 
344         path_simplify(s->what);
345 
346         if (!UNIT(s)->description) {
347                 r = unit_set_description(UNIT(s), s->what);
348                 if (r < 0)
349                         return r;
350         }
351 
352         r = unit_require_mounts_for(UNIT(s), s->what, UNIT_DEPENDENCY_IMPLICIT);
353         if (r < 0)
354                 return r;
355 
356         r = swap_add_device_dependencies(s);
357         if (r < 0)
358                 return r;
359 
360         r = swap_load_devnode(s);
361         if (r < 0)
362                 return r;
363 
364         r = unit_patch_contexts(UNIT(s));
365         if (r < 0)
366                 return r;
367 
368         r = unit_add_exec_dependencies(UNIT(s), &s->exec_context);
369         if (r < 0)
370                 return r;
371 
372         r = unit_set_default_slice(UNIT(s));
373         if (r < 0)
374                 return r;
375 
376         r = swap_add_default_dependencies(s);
377         if (r < 0)
378                 return r;
379 
380         return 0;
381 }
382 
swap_load(Unit * u)383 static int swap_load(Unit *u) {
384         Swap *s = SWAP(u);
385         int r, q = 0;
386 
387         assert(s);
388         assert(u->load_state == UNIT_STUB);
389 
390         /* Load a .swap file */
391         bool fragment_optional = s->from_proc_swaps;
392         r = unit_load_fragment_and_dropin(u, !fragment_optional);
393 
394         /* Add in some extras, and do so either when we successfully loaded something or when /proc/swaps is
395          * already active. */
396         if (u->load_state == UNIT_LOADED || s->from_proc_swaps)
397                 q = swap_add_extras(s);
398 
399         if (r < 0)
400                 return r;
401         if (q < 0)
402                 return q;
403         if (u->load_state != UNIT_LOADED)
404                 return 0;
405 
406         return swap_verify(s);
407 }
408 
swap_setup_unit(Manager * m,const char * what,const char * what_proc_swaps,int priority,bool set_flags)409 static int swap_setup_unit(
410                 Manager *m,
411                 const char *what,
412                 const char *what_proc_swaps,
413                 int priority,
414                 bool set_flags) {
415 
416         _cleanup_free_ char *e = NULL;
417         bool delete = false;
418         Unit *u = NULL;
419         int r;
420         SwapParameters *p;
421 
422         assert(m);
423         assert(what);
424         assert(what_proc_swaps);
425 
426         r = unit_name_from_path(what, ".swap", &e);
427         if (r < 0)
428                 return log_unit_error_errno(u, r, "Failed to generate unit name from path: %m");
429 
430         u = manager_get_unit(m, e);
431         if (u &&
432             SWAP(u)->from_proc_swaps &&
433             !path_equal(SWAP(u)->parameters_proc_swaps.what, what_proc_swaps))
434                 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
435                                        "Swap %s appeared twice with different device paths %s and %s",
436                                        e, SWAP(u)->parameters_proc_swaps.what, what_proc_swaps);
437 
438         if (!u) {
439                 delete = true;
440 
441                 r = unit_new_for_name(m, sizeof(Swap), e, &u);
442                 if (r < 0)
443                         goto fail;
444 
445                 SWAP(u)->what = strdup(what);
446                 if (!SWAP(u)->what) {
447                         r = -ENOMEM;
448                         goto fail;
449                 }
450 
451                 unit_add_to_load_queue(u);
452         } else
453                 delete = false;
454 
455         p = &SWAP(u)->parameters_proc_swaps;
456 
457         if (!p->what) {
458                 p->what = strdup(what_proc_swaps);
459                 if (!p->what) {
460                         r = -ENOMEM;
461                         goto fail;
462                 }
463         }
464 
465         /* The unit is definitely around now, mark it as loaded if it was previously referenced but could not be
466          * loaded. After all we can load it now, from the data in /proc/swaps. */
467         if (IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_BAD_SETTING, UNIT_ERROR)) {
468                 u->load_state = UNIT_LOADED;
469                 u->load_error = 0;
470         }
471 
472         if (set_flags) {
473                 SWAP(u)->is_active = true;
474                 SWAP(u)->just_activated = !SWAP(u)->from_proc_swaps;
475         }
476 
477         SWAP(u)->from_proc_swaps = true;
478 
479         p->priority = priority;
480         p->priority_set = true;
481 
482         unit_add_to_dbus_queue(u);
483         return 0;
484 
485 fail:
486         log_unit_warning_errno(u, r, "Failed to load swap unit: %m");
487 
488         if (delete)
489                 unit_free(u);
490 
491         return r;
492 }
493 
swap_process_new(Manager * m,const char * device,int prio,bool set_flags)494 static void swap_process_new(Manager *m, const char *device, int prio, bool set_flags) {
495         _cleanup_(sd_device_unrefp) sd_device *d = NULL;
496         const char *dn, *devlink;
497         struct stat st, st_link;
498         int r;
499 
500         assert(m);
501 
502         if (swap_setup_unit(m, device, device, prio, set_flags) < 0)
503                 return;
504 
505         /* If this is a block device, then let's add duplicates for
506          * all other names of this block device */
507         if (stat(device, &st) < 0 || !S_ISBLK(st.st_mode))
508                 return;
509 
510         r = sd_device_new_from_stat_rdev(&d, &st);
511         if (r < 0)
512                 return (void) log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
513                                              "Failed to allocate device for swap %s: %m", device);
514 
515         /* Add the main device node */
516         if (sd_device_get_devname(d, &dn) >= 0 && !streq(dn, device))
517                 (void) swap_setup_unit(m, dn, device, prio, set_flags);
518 
519         /* Add additional units for all symlinks */
520         FOREACH_DEVICE_DEVLINK(d, devlink) {
521 
522                 /* Don't bother with the /dev/block links */
523                 if (streq(devlink, device))
524                         continue;
525 
526                 if (path_startswith(devlink, "/dev/block/"))
527                         continue;
528 
529                 if (stat(devlink, &st_link) >= 0 &&
530                     (!S_ISBLK(st_link.st_mode) ||
531                      st_link.st_rdev != st.st_rdev))
532                         continue;
533 
534                 (void) swap_setup_unit(m, devlink, device, prio, set_flags);
535         }
536 }
537 
swap_set_state(Swap * s,SwapState state)538 static void swap_set_state(Swap *s, SwapState state) {
539         SwapState old_state;
540 
541         assert(s);
542 
543         if (s->state != state)
544                 bus_unit_send_pending_change_signal(UNIT(s), false);
545 
546         old_state = s->state;
547         s->state = state;
548 
549         if (!SWAP_STATE_WITH_PROCESS(state)) {
550                 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
551                 swap_unwatch_control_pid(s);
552                 s->control_command = NULL;
553                 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
554         }
555 
556         if (state != old_state)
557                 log_unit_debug(UNIT(s), "Changed %s -> %s", swap_state_to_string(old_state), swap_state_to_string(state));
558 
559         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], 0);
560 
561         /* If there other units for the same device node have a job
562            queued it might be worth checking again if it is runnable
563            now. This is necessary, since swap_start() refuses
564            operation with EAGAIN if there's already another job for
565            the same device node queued. */
566         LIST_FOREACH_OTHERS(same_devnode, other, s)
567                 if (UNIT(other)->job)
568                         job_add_to_run_queue(UNIT(other)->job);
569 }
570 
swap_coldplug(Unit * u)571 static int swap_coldplug(Unit *u) {
572         Swap *s = SWAP(u);
573         SwapState new_state = SWAP_DEAD;
574         int r;
575 
576         assert(s);
577         assert(s->state == SWAP_DEAD);
578 
579         if (s->deserialized_state != s->state)
580                 new_state = s->deserialized_state;
581         else if (s->from_proc_swaps)
582                 new_state = SWAP_ACTIVE;
583 
584         if (new_state == s->state)
585                 return 0;
586 
587         if (s->control_pid > 0 &&
588             pid_is_unwaited(s->control_pid) &&
589             SWAP_STATE_WITH_PROCESS(new_state)) {
590 
591                 r = unit_watch_pid(UNIT(s), s->control_pid, false);
592                 if (r < 0)
593                         return r;
594 
595                 r = swap_arm_timer(s, usec_add(u->state_change_timestamp.monotonic, s->timeout_usec));
596                 if (r < 0)
597                         return r;
598         }
599 
600         if (!IN_SET(new_state, SWAP_DEAD, SWAP_FAILED)) {
601                 (void) unit_setup_dynamic_creds(u);
602                 (void) unit_setup_exec_runtime(u);
603         }
604 
605         swap_set_state(s, new_state);
606         return 0;
607 }
608 
swap_dump(Unit * u,FILE * f,const char * prefix)609 static void swap_dump(Unit *u, FILE *f, const char *prefix) {
610         Swap *s = SWAP(u);
611         SwapParameters *p;
612 
613         assert(s);
614         assert(f);
615 
616         if (s->from_proc_swaps)
617                 p = &s->parameters_proc_swaps;
618         else if (s->from_fragment)
619                 p = &s->parameters_fragment;
620         else
621                 p = NULL;
622 
623         fprintf(f,
624                 "%sSwap State: %s\n"
625                 "%sResult: %s\n"
626                 "%sClean Result: %s\n"
627                 "%sWhat: %s\n"
628                 "%sFrom /proc/swaps: %s\n"
629                 "%sFrom fragment: %s\n"
630                 "%sExtrinsic: %s\n",
631                 prefix, swap_state_to_string(s->state),
632                 prefix, swap_result_to_string(s->result),
633                 prefix, swap_result_to_string(s->clean_result),
634                 prefix, s->what,
635                 prefix, yes_no(s->from_proc_swaps),
636                 prefix, yes_no(s->from_fragment),
637                 prefix, yes_no(swap_is_extrinsic(u)));
638 
639         if (s->devnode)
640                 fprintf(f, "%sDevice Node: %s\n", prefix, s->devnode);
641 
642         if (p)
643                 fprintf(f,
644                         "%sPriority: %i\n"
645                         "%sOptions: %s\n",
646                         prefix, p->priority,
647                         prefix, strempty(p->options));
648 
649         fprintf(f,
650                 "%sTimeoutSec: %s\n",
651                 prefix, FORMAT_TIMESPAN(s->timeout_usec, USEC_PER_SEC));
652 
653         if (s->control_pid > 0)
654                 fprintf(f,
655                         "%sControl PID: "PID_FMT"\n",
656                         prefix, s->control_pid);
657 
658         exec_context_dump(&s->exec_context, f, prefix);
659         kill_context_dump(&s->kill_context, f, prefix);
660         cgroup_context_dump(UNIT(s), f, prefix);
661 }
662 
swap_spawn(Swap * s,ExecCommand * c,pid_t * _pid)663 static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) {
664 
665         _cleanup_(exec_params_clear) ExecParameters exec_params = {
666                 .flags     = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
667                 .stdin_fd  = -1,
668                 .stdout_fd = -1,
669                 .stderr_fd = -1,
670                 .exec_fd   = -1,
671         };
672         pid_t pid;
673         int r;
674 
675         assert(s);
676         assert(c);
677         assert(_pid);
678 
679         r = unit_prepare_exec(UNIT(s));
680         if (r < 0)
681                 return r;
682 
683         r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
684         if (r < 0)
685                 goto fail;
686 
687         r = unit_set_exec_params(UNIT(s), &exec_params);
688         if (r < 0)
689                 goto fail;
690 
691         r = exec_spawn(UNIT(s),
692                        c,
693                        &s->exec_context,
694                        &exec_params,
695                        s->exec_runtime,
696                        &s->dynamic_creds,
697                        &pid);
698         if (r < 0)
699                 goto fail;
700 
701         r = unit_watch_pid(UNIT(s), pid, true);
702         if (r < 0)
703                 goto fail;
704 
705         *_pid = pid;
706 
707         return 0;
708 
709 fail:
710         s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
711 
712         return r;
713 }
714 
swap_enter_dead(Swap * s,SwapResult f)715 static void swap_enter_dead(Swap *s, SwapResult f) {
716         assert(s);
717 
718         if (s->result == SWAP_SUCCESS)
719                 s->result = f;
720 
721         unit_log_result(UNIT(s), s->result == SWAP_SUCCESS, swap_result_to_string(s->result));
722         unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_stop);
723         swap_set_state(s, s->result != SWAP_SUCCESS ? SWAP_FAILED : SWAP_DEAD);
724 
725         s->exec_runtime = exec_runtime_unref(s->exec_runtime, true);
726 
727         unit_destroy_runtime_data(UNIT(s), &s->exec_context);
728 
729         unit_unref_uid_gid(UNIT(s), true);
730 
731         dynamic_creds_destroy(&s->dynamic_creds);
732 }
733 
swap_enter_active(Swap * s,SwapResult f)734 static void swap_enter_active(Swap *s, SwapResult f) {
735         assert(s);
736 
737         if (s->result == SWAP_SUCCESS)
738                 s->result = f;
739 
740         swap_set_state(s, SWAP_ACTIVE);
741 }
742 
swap_enter_dead_or_active(Swap * s,SwapResult f)743 static void swap_enter_dead_or_active(Swap *s, SwapResult f) {
744         assert(s);
745 
746         if (s->from_proc_swaps) {
747                 swap_enter_active(s, f);
748 
749                 LIST_FOREACH_OTHERS(same_devnode, other, s)
750                         if (UNIT(other)->job)
751                                 swap_enter_dead_or_active(other, f);
752         } else
753                 swap_enter_dead(s, f);
754 }
755 
state_to_kill_operation(Swap * s,SwapState state)756 static int state_to_kill_operation(Swap *s, SwapState state) {
757         if (state == SWAP_DEACTIVATING_SIGTERM) {
758                 if (unit_has_job_type(UNIT(s), JOB_RESTART))
759                         return KILL_RESTART;
760                 else
761                         return KILL_TERMINATE;
762         }
763 
764         return KILL_KILL;
765 }
766 
swap_enter_signal(Swap * s,SwapState state,SwapResult f)767 static void swap_enter_signal(Swap *s, SwapState state, SwapResult f) {
768         int r;
769 
770         assert(s);
771 
772         if (s->result == SWAP_SUCCESS)
773                 s->result = f;
774 
775         r = unit_kill_context(UNIT(s),
776                               &s->kill_context,
777                               state_to_kill_operation(s, state),
778                               -1,
779                               s->control_pid,
780                               false);
781         if (r < 0)
782                 goto fail;
783 
784         if (r > 0) {
785                 r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
786                 if (r < 0)
787                         goto fail;
788 
789                 swap_set_state(s, state);
790         } else if (state == SWAP_DEACTIVATING_SIGTERM && s->kill_context.send_sigkill)
791                 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_SUCCESS);
792         else
793                 swap_enter_dead_or_active(s, SWAP_SUCCESS);
794 
795         return;
796 
797 fail:
798         log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
799         swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES);
800 }
801 
swap_enter_activating(Swap * s)802 static void swap_enter_activating(Swap *s) {
803         _cleanup_free_ char *opts = NULL;
804         int r;
805 
806         assert(s);
807 
808         unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_start);
809 
810         s->control_command_id = SWAP_EXEC_ACTIVATE;
811         s->control_command = s->exec_command + SWAP_EXEC_ACTIVATE;
812 
813         if (s->from_fragment) {
814                 int priority = 0;
815 
816                 r = fstab_find_pri(s->parameters_fragment.options, &priority);
817                 if (r < 0)
818                         log_unit_warning_errno(UNIT(s), r, "Failed to parse swap priority \"%s\", ignoring: %m", s->parameters_fragment.options);
819                 else if (r > 0 && s->parameters_fragment.priority_set)
820                         log_unit_warning(UNIT(s), "Duplicate swap priority configuration by Priority= and Options= fields.");
821 
822                 if (r <= 0 && s->parameters_fragment.priority_set) {
823                         if (s->parameters_fragment.options)
824                                 r = asprintf(&opts, "%s,pri=%i", s->parameters_fragment.options, s->parameters_fragment.priority);
825                         else
826                                 r = asprintf(&opts, "pri=%i", s->parameters_fragment.priority);
827                         if (r < 0) {
828                                 r = -ENOMEM;
829                                 goto fail;
830                         }
831                 }
832         }
833 
834         r = exec_command_set(s->control_command, "/sbin/swapon", NULL);
835         if (r < 0)
836                 goto fail;
837 
838         if (s->parameters_fragment.options || opts) {
839                 r = exec_command_append(s->control_command, "-o",
840                                 opts ?: s->parameters_fragment.options, NULL);
841                 if (r < 0)
842                         goto fail;
843         }
844 
845         r = exec_command_append(s->control_command, s->what, NULL);
846         if (r < 0)
847                 goto fail;
848 
849         swap_unwatch_control_pid(s);
850 
851         r = swap_spawn(s, s->control_command, &s->control_pid);
852         if (r < 0)
853                 goto fail;
854 
855         swap_set_state(s, SWAP_ACTIVATING);
856         return;
857 
858 fail:
859         log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapon' task: %m");
860         swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES);
861 }
862 
swap_enter_deactivating(Swap * s)863 static void swap_enter_deactivating(Swap *s) {
864         int r;
865 
866         assert(s);
867 
868         s->control_command_id = SWAP_EXEC_DEACTIVATE;
869         s->control_command = s->exec_command + SWAP_EXEC_DEACTIVATE;
870 
871         r = exec_command_set(s->control_command,
872                              "/sbin/swapoff",
873                              s->what,
874                              NULL);
875         if (r < 0)
876                 goto fail;
877 
878         swap_unwatch_control_pid(s);
879 
880         r = swap_spawn(s, s->control_command, &s->control_pid);
881         if (r < 0)
882                 goto fail;
883 
884         swap_set_state(s, SWAP_DEACTIVATING);
885 
886         return;
887 
888 fail:
889         log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapoff' task: %m");
890         swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES);
891 }
892 
swap_cycle_clear(Swap * s)893 static void swap_cycle_clear(Swap *s) {
894         assert(s);
895 
896         s->result = SWAP_SUCCESS;
897         exec_command_reset_status_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX);
898         UNIT(s)->reset_accounting = true;
899 }
900 
swap_start(Unit * u)901 static int swap_start(Unit *u) {
902         Swap *s = SWAP(u);
903         int r;
904 
905         assert(s);
906 
907         /* We cannot fulfill this request right now, try again later please! */
908         if (IN_SET(s->state,
909                    SWAP_DEACTIVATING,
910                    SWAP_DEACTIVATING_SIGTERM,
911                    SWAP_DEACTIVATING_SIGKILL,
912                    SWAP_CLEANING))
913                 return -EAGAIN;
914 
915         /* Already on it! */
916         if (s->state == SWAP_ACTIVATING)
917                 return 0;
918 
919         assert(IN_SET(s->state, SWAP_DEAD, SWAP_FAILED));
920 
921         if (detect_container() > 0)
922                 return -EPERM;
923 
924         /* If there's a job for another swap unit for the same node
925          * running, then let's not dispatch this one for now, and wait
926          * until that other job has finished. */
927         LIST_FOREACH_OTHERS(same_devnode, other, s)
928                 if (UNIT(other)->job && UNIT(other)->job->state == JOB_RUNNING)
929                         return -EAGAIN;
930 
931         r = unit_acquire_invocation_id(u);
932         if (r < 0)
933                 return r;
934 
935         swap_cycle_clear(s);
936         swap_enter_activating(s);
937         return 1;
938 }
939 
swap_stop(Unit * u)940 static int swap_stop(Unit *u) {
941         Swap *s = SWAP(u);
942 
943         assert(s);
944 
945         switch (s->state) {
946 
947         case SWAP_DEACTIVATING:
948         case SWAP_DEACTIVATING_SIGTERM:
949         case SWAP_DEACTIVATING_SIGKILL:
950                 /* Already on it */
951                 return 0;
952 
953         case SWAP_ACTIVATING:
954         case SWAP_ACTIVATING_DONE:
955                 /* There's a control process pending, directly enter kill mode */
956                 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_SUCCESS);
957                 return 0;
958 
959         case SWAP_ACTIVE:
960                 if (detect_container() > 0)
961                         return -EPERM;
962 
963                 swap_enter_deactivating(s);
964                 return 1;
965 
966         case SWAP_CLEANING:
967                 /* If we are currently cleaning, then abort it, brutally. */
968                 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_SUCCESS);
969                 return 0;
970 
971         default:
972                 assert_not_reached();
973         }
974 }
975 
swap_serialize(Unit * u,FILE * f,FDSet * fds)976 static int swap_serialize(Unit *u, FILE *f, FDSet *fds) {
977         Swap *s = SWAP(u);
978 
979         assert(s);
980         assert(f);
981         assert(fds);
982 
983         (void) serialize_item(f, "state", swap_state_to_string(s->state));
984         (void) serialize_item(f, "result", swap_result_to_string(s->result));
985 
986         if (s->control_pid > 0)
987                 (void) serialize_item_format(f, "control-pid", PID_FMT, s->control_pid);
988 
989         if (s->control_command_id >= 0)
990                 (void) serialize_item(f, "control-command", swap_exec_command_to_string(s->control_command_id));
991 
992         return 0;
993 }
994 
swap_deserialize_item(Unit * u,const char * key,const char * value,FDSet * fds)995 static int swap_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
996         Swap *s = SWAP(u);
997 
998         assert(s);
999         assert(fds);
1000 
1001         if (streq(key, "state")) {
1002                 SwapState state;
1003 
1004                 state = swap_state_from_string(value);
1005                 if (state < 0)
1006                         log_unit_debug(u, "Failed to parse state value: %s", value);
1007                 else
1008                         s->deserialized_state = state;
1009         } else if (streq(key, "result")) {
1010                 SwapResult f;
1011 
1012                 f = swap_result_from_string(value);
1013                 if (f < 0)
1014                         log_unit_debug(u, "Failed to parse result value: %s", value);
1015                 else if (f != SWAP_SUCCESS)
1016                         s->result = f;
1017         } else if (streq(key, "control-pid")) {
1018                 pid_t pid;
1019 
1020                 if (parse_pid(value, &pid) < 0)
1021                         log_unit_debug(u, "Failed to parse control-pid value: %s", value);
1022                 else
1023                         s->control_pid = pid;
1024 
1025         } else if (streq(key, "control-command")) {
1026                 SwapExecCommand id;
1027 
1028                 id = swap_exec_command_from_string(value);
1029                 if (id < 0)
1030                         log_unit_debug(u, "Failed to parse exec-command value: %s", value);
1031                 else {
1032                         s->control_command_id = id;
1033                         s->control_command = s->exec_command + id;
1034                 }
1035         } else
1036                 log_unit_debug(u, "Unknown serialization key: %s", key);
1037 
1038         return 0;
1039 }
1040 
swap_sigchld_event(Unit * u,pid_t pid,int code,int status)1041 static void swap_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1042         Swap *s = SWAP(u);
1043         SwapResult f;
1044 
1045         assert(s);
1046         assert(pid >= 0);
1047 
1048         if (pid != s->control_pid)
1049                 return;
1050 
1051         /* Let's scan /proc/swaps before we process SIGCHLD. For the reasoning see the similar code in
1052          * mount.c */
1053         (void) swap_process_proc_swaps(u->manager);
1054 
1055         s->control_pid = 0;
1056 
1057         if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
1058                 f = SWAP_SUCCESS;
1059         else if (code == CLD_EXITED)
1060                 f = SWAP_FAILURE_EXIT_CODE;
1061         else if (code == CLD_KILLED)
1062                 f = SWAP_FAILURE_SIGNAL;
1063         else if (code == CLD_DUMPED)
1064                 f = SWAP_FAILURE_CORE_DUMP;
1065         else
1066                 assert_not_reached();
1067 
1068         if (s->result == SWAP_SUCCESS)
1069                 s->result = f;
1070 
1071         if (s->control_command) {
1072                 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
1073 
1074                 s->control_command = NULL;
1075                 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
1076         }
1077 
1078         unit_log_process_exit(
1079                         u,
1080                         "Swap process",
1081                         swap_exec_command_to_string(s->control_command_id),
1082                         f == SWAP_SUCCESS,
1083                         code, status);
1084 
1085         switch (s->state) {
1086 
1087         case SWAP_ACTIVATING:
1088         case SWAP_ACTIVATING_DONE:
1089 
1090                 if (f == SWAP_SUCCESS || s->from_proc_swaps)
1091                         swap_enter_active(s, f);
1092                 else
1093                         swap_enter_dead(s, f);
1094                 break;
1095 
1096         case SWAP_DEACTIVATING:
1097         case SWAP_DEACTIVATING_SIGKILL:
1098         case SWAP_DEACTIVATING_SIGTERM:
1099 
1100                 swap_enter_dead_or_active(s, f);
1101                 break;
1102 
1103         case SWAP_CLEANING:
1104                 if (s->clean_result == SWAP_SUCCESS)
1105                         s->clean_result = f;
1106 
1107                 swap_enter_dead(s, SWAP_SUCCESS);
1108                 break;
1109 
1110         default:
1111                 assert_not_reached();
1112         }
1113 
1114         /* Notify clients about changed exit status */
1115         unit_add_to_dbus_queue(u);
1116 }
1117 
swap_dispatch_timer(sd_event_source * source,usec_t usec,void * userdata)1118 static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
1119         Swap *s = SWAP(userdata);
1120 
1121         assert(s);
1122         assert(s->timer_event_source == source);
1123 
1124         switch (s->state) {
1125 
1126         case SWAP_ACTIVATING:
1127         case SWAP_ACTIVATING_DONE:
1128                 log_unit_warning(UNIT(s), "Activation timed out. Stopping.");
1129                 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
1130                 break;
1131 
1132         case SWAP_DEACTIVATING:
1133                 log_unit_warning(UNIT(s), "Deactivation timed out. Stopping.");
1134                 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
1135                 break;
1136 
1137         case SWAP_DEACTIVATING_SIGTERM:
1138                 if (s->kill_context.send_sigkill) {
1139                         log_unit_warning(UNIT(s), "Swap process timed out. Killing.");
1140                         swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_FAILURE_TIMEOUT);
1141                 } else {
1142                         log_unit_warning(UNIT(s), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1143                         swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT);
1144                 }
1145                 break;
1146 
1147         case SWAP_DEACTIVATING_SIGKILL:
1148                 log_unit_warning(UNIT(s), "Swap process still around after SIGKILL. Ignoring.");
1149                 swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT);
1150                 break;
1151 
1152         case SWAP_CLEANING:
1153                 log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
1154 
1155                 if (s->clean_result == SWAP_SUCCESS)
1156                         s->clean_result = SWAP_FAILURE_TIMEOUT;
1157 
1158                 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, 0);
1159                 break;
1160 
1161         default:
1162                 assert_not_reached();
1163         }
1164 
1165         return 0;
1166 }
1167 
swap_load_proc_swaps(Manager * m,bool set_flags)1168 static int swap_load_proc_swaps(Manager *m, bool set_flags) {
1169         assert(m);
1170 
1171         rewind(m->proc_swaps);
1172 
1173         (void) fscanf(m->proc_swaps, "%*s %*s %*s %*s %*s\n");
1174 
1175         for (unsigned i = 1;; i++) {
1176                 _cleanup_free_ char *dev = NULL, *d = NULL;
1177                 int prio = 0, k;
1178 
1179                 k = fscanf(m->proc_swaps,
1180                            "%ms "  /* device/file */
1181                            "%*s "  /* type of swap */
1182                            "%*s "  /* swap size */
1183                            "%*s "  /* used */
1184                            "%i\n", /* priority */
1185                            &dev, &prio);
1186                 if (k != 2) {
1187                         if (k == EOF)
1188                                 break;
1189 
1190                         log_warning("Failed to parse /proc/swaps:%u.", i);
1191                         continue;
1192                 }
1193 
1194                 ssize_t l = cunescape(dev, UNESCAPE_RELAX, &d);
1195                 if (l < 0)
1196                         return log_error_errno(l, "Failed to unescape device path: %m");
1197 
1198                 device_found_node(m, d, DEVICE_FOUND_SWAP, DEVICE_FOUND_SWAP);
1199 
1200                 (void) swap_process_new(m, d, prio, set_flags);
1201         }
1202 
1203         return 0;
1204 }
1205 
swap_process_proc_swaps(Manager * m)1206 static int swap_process_proc_swaps(Manager *m) {
1207         int r;
1208 
1209         assert(m);
1210 
1211         r = swap_load_proc_swaps(m, true);
1212         if (r < 0) {
1213                 log_error_errno(r, "Failed to reread /proc/swaps: %m");
1214 
1215                 /* Reset flags, just in case, for late calls */
1216                 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) {
1217                         Swap *swap = SWAP(u);
1218 
1219                         assert(swap);
1220 
1221                         swap->is_active = swap->just_activated = false;
1222                 }
1223 
1224                 return 0;
1225         }
1226 
1227         manager_dispatch_load_queue(m);
1228 
1229         LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) {
1230                 Swap *swap = SWAP(u);
1231 
1232                 assert(swap);
1233 
1234                 if (!swap->is_active) {
1235 
1236                         swap_unset_proc_swaps(swap);
1237 
1238                         switch (swap->state) {
1239 
1240                         case SWAP_ACTIVE:
1241                                 /* This has just been deactivated */
1242                                 swap_enter_dead(swap, SWAP_SUCCESS);
1243                                 break;
1244 
1245                         default:
1246                                 /* Fire again */
1247                                 swap_set_state(swap, swap->state);
1248                                 break;
1249                         }
1250 
1251                         if (swap->what)
1252                                 device_found_node(m, swap->what, DEVICE_NOT_FOUND, DEVICE_FOUND_SWAP);
1253 
1254                 } else if (swap->just_activated) {
1255 
1256                         /* New swap entry */
1257 
1258                         switch (swap->state) {
1259 
1260                         case SWAP_DEAD:
1261                         case SWAP_FAILED:
1262                                 (void) unit_acquire_invocation_id(u);
1263                                 swap_cycle_clear(swap);
1264                                 swap_enter_active(swap, SWAP_SUCCESS);
1265                                 break;
1266 
1267                         case SWAP_ACTIVATING:
1268                                 swap_set_state(swap, SWAP_ACTIVATING_DONE);
1269                                 break;
1270 
1271                         default:
1272                                 /* Nothing really changed, but let's
1273                                  * issue an notification call
1274                                  * nonetheless, in case somebody is
1275                                  * waiting for this. */
1276                                 swap_set_state(swap, swap->state);
1277                                 break;
1278                         }
1279                 }
1280 
1281                 /* Reset the flags for later calls */
1282                 swap->is_active = swap->just_activated = false;
1283         }
1284 
1285         return 1;
1286 }
1287 
swap_dispatch_io(sd_event_source * source,int fd,uint32_t revents,void * userdata)1288 static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1289         Manager *m = userdata;
1290 
1291         assert(m);
1292         assert(revents & EPOLLPRI);
1293 
1294         return swap_process_proc_swaps(m);
1295 }
1296 
swap_following(Unit * u)1297 static Unit *swap_following(Unit *u) {
1298         Swap *s = SWAP(u);
1299         Swap *first = NULL;
1300 
1301         assert(s);
1302 
1303         /* If the user configured the swap through /etc/fstab or
1304          * a device unit, follow that. */
1305 
1306         if (s->from_fragment)
1307                 return NULL;
1308 
1309         LIST_FOREACH_OTHERS(same_devnode, other, s)
1310                 if (other->from_fragment)
1311                         return UNIT(other);
1312 
1313         /* Otherwise, make everybody follow the unit that's named after
1314          * the swap device in the kernel */
1315 
1316         if (streq_ptr(s->what, s->devnode))
1317                 return NULL;
1318 
1319         LIST_FOREACH(same_devnode, other, s->same_devnode_next)
1320                 if (streq_ptr(other->what, other->devnode))
1321                         return UNIT(other);
1322 
1323         LIST_FOREACH_BACKWARDS(same_devnode, other, s->same_devnode_prev) {
1324                 if (streq_ptr(other->what, other->devnode))
1325                         return UNIT(other);
1326 
1327                 first = other;
1328         }
1329 
1330         /* Fall back to the first on the list */
1331         return UNIT(first);
1332 }
1333 
swap_following_set(Unit * u,Set ** _set)1334 static int swap_following_set(Unit *u, Set **_set) {
1335         Swap *s = SWAP(u);
1336         _cleanup_set_free_ Set *set = NULL;
1337         int r;
1338 
1339         assert(s);
1340         assert(_set);
1341 
1342         if (LIST_JUST_US(same_devnode, s)) {
1343                 *_set = NULL;
1344                 return 0;
1345         }
1346 
1347         set = set_new(NULL);
1348         if (!set)
1349                 return -ENOMEM;
1350 
1351         LIST_FOREACH_OTHERS(same_devnode, other, s) {
1352                 r = set_put(set, other);
1353                 if (r < 0)
1354                         return r;
1355         }
1356 
1357         *_set = TAKE_PTR(set);
1358         return 1;
1359 }
1360 
swap_shutdown(Manager * m)1361 static void swap_shutdown(Manager *m) {
1362         assert(m);
1363 
1364         m->swap_event_source = sd_event_source_disable_unref(m->swap_event_source);
1365         m->proc_swaps = safe_fclose(m->proc_swaps);
1366         m->swaps_by_devnode = hashmap_free(m->swaps_by_devnode);
1367 }
1368 
swap_enumerate(Manager * m)1369 static void swap_enumerate(Manager *m) {
1370         int r;
1371 
1372         assert(m);
1373 
1374         if (!m->proc_swaps) {
1375                 m->proc_swaps = fopen("/proc/swaps", "re");
1376                 if (!m->proc_swaps) {
1377                         if (errno == ENOENT)
1378                                 log_debug_errno(errno, "Not swap enabled, skipping enumeration.");
1379                         else
1380                                 log_warning_errno(errno, "Failed to open /proc/swaps, ignoring: %m");
1381 
1382                         return;
1383                 }
1384 
1385                 r = sd_event_add_io(m->event, &m->swap_event_source, fileno(m->proc_swaps), EPOLLPRI, swap_dispatch_io, m);
1386                 if (r < 0) {
1387                         log_error_errno(r, "Failed to watch /proc/swaps: %m");
1388                         goto fail;
1389                 }
1390 
1391                 /* Dispatch this before we dispatch SIGCHLD, so that
1392                  * we always get the events from /proc/swaps before
1393                  * the SIGCHLD of /sbin/swapon. */
1394                 r = sd_event_source_set_priority(m->swap_event_source, SD_EVENT_PRIORITY_NORMAL-10);
1395                 if (r < 0) {
1396                         log_error_errno(r, "Failed to change /proc/swaps priority: %m");
1397                         goto fail;
1398                 }
1399 
1400                 (void) sd_event_source_set_description(m->swap_event_source, "swap-proc");
1401         }
1402 
1403         r = swap_load_proc_swaps(m, false);
1404         if (r < 0)
1405                 goto fail;
1406 
1407         return;
1408 
1409 fail:
1410         swap_shutdown(m);
1411 }
1412 
swap_process_device_new(Manager * m,sd_device * dev)1413 int swap_process_device_new(Manager *m, sd_device *dev) {
1414         _cleanup_free_ char *e = NULL;
1415         const char *dn, *devlink;
1416         Unit *u;
1417         int r;
1418 
1419         assert(m);
1420         assert(dev);
1421 
1422         if (sd_device_get_devname(dev, &dn) < 0)
1423                 return 0;
1424 
1425         r = unit_name_from_path(dn, ".swap", &e);
1426         if (r < 0) {
1427                 log_debug_errno(r, "Cannot convert device name '%s' to unit name, ignoring: %m", dn);
1428                 return 0;
1429         }
1430 
1431         u = manager_get_unit(m, e);
1432         if (u)
1433                 r = swap_set_devnode(SWAP(u), dn);
1434 
1435         FOREACH_DEVICE_DEVLINK(dev, devlink) {
1436                 _cleanup_free_ char *n = NULL;
1437                 int q;
1438 
1439                 q = unit_name_from_path(devlink, ".swap", &n);
1440                 if (IN_SET(q, -EINVAL, -ENAMETOOLONG)) /* If name too long or otherwise not convertible to
1441                                                         * unit name, we can't manage it */
1442                         continue;
1443                 if (q < 0)
1444                         return q;
1445 
1446                 u = manager_get_unit(m, n);
1447                 if (u) {
1448                         q = swap_set_devnode(SWAP(u), dn);
1449                         if (q < 0)
1450                                 r = q;
1451                 }
1452         }
1453 
1454         return r;
1455 }
1456 
swap_process_device_remove(Manager * m,sd_device * dev)1457 int swap_process_device_remove(Manager *m, sd_device *dev) {
1458         const char *dn;
1459         int r;
1460         Swap *s;
1461 
1462         r = sd_device_get_devname(dev, &dn);
1463         if (r < 0)
1464                 return 0;
1465 
1466         while ((s = hashmap_get(m->swaps_by_devnode, dn))) {
1467                 int q;
1468 
1469                 q = swap_set_devnode(s, NULL);
1470                 if (q < 0)
1471                         r = q;
1472         }
1473 
1474         return r;
1475 }
1476 
swap_reset_failed(Unit * u)1477 static void swap_reset_failed(Unit *u) {
1478         Swap *s = SWAP(u);
1479 
1480         assert(s);
1481 
1482         if (s->state == SWAP_FAILED)
1483                 swap_set_state(s, SWAP_DEAD);
1484 
1485         s->result = SWAP_SUCCESS;
1486         s->clean_result = SWAP_SUCCESS;
1487 }
1488 
swap_kill(Unit * u,KillWho who,int signo,sd_bus_error * error)1489 static int swap_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
1490         return unit_kill_common(u, who, signo, -1, SWAP(u)->control_pid, error);
1491 }
1492 
swap_get_timeout(Unit * u,usec_t * timeout)1493 static int swap_get_timeout(Unit *u, usec_t *timeout) {
1494         Swap *s = SWAP(u);
1495         usec_t t;
1496         int r;
1497 
1498         assert(s);
1499         assert(u);
1500 
1501         if (!s->timer_event_source)
1502                 return 0;
1503 
1504         r = sd_event_source_get_time(s->timer_event_source, &t);
1505         if (r < 0)
1506                 return r;
1507         if (t == USEC_INFINITY)
1508                 return 0;
1509 
1510         *timeout = t;
1511         return 1;
1512 }
1513 
swap_supported(void)1514 static bool swap_supported(void) {
1515         static int supported = -1;
1516 
1517         /* If swap support is not available in the kernel, or we are
1518          * running in a container we don't support swap units, and any
1519          * attempts to starting one should fail immediately. */
1520 
1521         if (supported < 0)
1522                 supported =
1523                         access("/proc/swaps", F_OK) >= 0 &&
1524                         detect_container() <= 0;
1525 
1526         return supported;
1527 }
1528 
swap_control_pid(Unit * u)1529 static int swap_control_pid(Unit *u) {
1530         Swap *s = SWAP(u);
1531 
1532         assert(s);
1533 
1534         return s->control_pid;
1535 }
1536 
swap_clean(Unit * u,ExecCleanMask mask)1537 static int swap_clean(Unit *u, ExecCleanMask mask) {
1538         _cleanup_strv_free_ char **l = NULL;
1539         Swap *s = SWAP(u);
1540         int r;
1541 
1542         assert(s);
1543         assert(mask != 0);
1544 
1545         if (s->state != SWAP_DEAD)
1546                 return -EBUSY;
1547 
1548         r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
1549         if (r < 0)
1550                 return r;
1551 
1552         if (strv_isempty(l))
1553                 return -EUNATCH;
1554 
1555         swap_unwatch_control_pid(s);
1556         s->clean_result = SWAP_SUCCESS;
1557         s->control_command = NULL;
1558         s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
1559 
1560         r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->exec_context.timeout_clean_usec));
1561         if (r < 0)
1562                 goto fail;
1563 
1564         r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
1565         if (r < 0)
1566                 goto fail;
1567 
1568         swap_set_state(s, SWAP_CLEANING);
1569 
1570         return 0;
1571 
1572 fail:
1573         log_unit_warning_errno(u, r, "Failed to initiate cleaning: %m");
1574         s->clean_result = SWAP_FAILURE_RESOURCES;
1575         s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
1576         return r;
1577 }
1578 
swap_can_clean(Unit * u,ExecCleanMask * ret)1579 static int swap_can_clean(Unit *u, ExecCleanMask *ret) {
1580         Swap *s = SWAP(u);
1581 
1582         assert(s);
1583 
1584         return exec_context_get_clean_mask(&s->exec_context, ret);
1585 }
1586 
swap_can_start(Unit * u)1587 static int swap_can_start(Unit *u) {
1588         Swap *s = SWAP(u);
1589         int r;
1590 
1591         assert(s);
1592 
1593         r = unit_test_start_limit(u);
1594         if (r < 0) {
1595                 swap_enter_dead(s, SWAP_FAILURE_START_LIMIT_HIT);
1596                 return r;
1597         }
1598 
1599         return 1;
1600 }
1601 
1602 static const char* const swap_exec_command_table[_SWAP_EXEC_COMMAND_MAX] = {
1603         [SWAP_EXEC_ACTIVATE]   = "ExecActivate",
1604         [SWAP_EXEC_DEACTIVATE] = "ExecDeactivate",
1605 };
1606 
1607 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command, SwapExecCommand);
1608 
1609 static const char* const swap_result_table[_SWAP_RESULT_MAX] = {
1610         [SWAP_SUCCESS]                 = "success",
1611         [SWAP_FAILURE_RESOURCES]       = "resources",
1612         [SWAP_FAILURE_TIMEOUT]         = "timeout",
1613         [SWAP_FAILURE_EXIT_CODE]       = "exit-code",
1614         [SWAP_FAILURE_SIGNAL]          = "signal",
1615         [SWAP_FAILURE_CORE_DUMP]       = "core-dump",
1616         [SWAP_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
1617 };
1618 
1619 DEFINE_STRING_TABLE_LOOKUP(swap_result, SwapResult);
1620 
1621 const UnitVTable swap_vtable = {
1622         .object_size = sizeof(Swap),
1623         .exec_context_offset = offsetof(Swap, exec_context),
1624         .cgroup_context_offset = offsetof(Swap, cgroup_context),
1625         .kill_context_offset = offsetof(Swap, kill_context),
1626         .exec_runtime_offset = offsetof(Swap, exec_runtime),
1627         .dynamic_creds_offset = offsetof(Swap, dynamic_creds),
1628 
1629         .sections =
1630                 "Unit\0"
1631                 "Swap\0"
1632                 "Install\0",
1633         .private_section = "Swap",
1634 
1635         .can_fail = true,
1636 
1637         .init = swap_init,
1638         .load = swap_load,
1639         .done = swap_done,
1640 
1641         .coldplug = swap_coldplug,
1642 
1643         .dump = swap_dump,
1644 
1645         .start = swap_start,
1646         .stop = swap_stop,
1647 
1648         .kill = swap_kill,
1649         .clean = swap_clean,
1650         .can_clean = swap_can_clean,
1651 
1652         .get_timeout = swap_get_timeout,
1653 
1654         .serialize = swap_serialize,
1655         .deserialize_item = swap_deserialize_item,
1656 
1657         .active_state = swap_active_state,
1658         .sub_state_to_string = swap_sub_state_to_string,
1659 
1660         .will_restart = unit_will_restart_default,
1661 
1662         .may_gc = swap_may_gc,
1663         .is_extrinsic = swap_is_extrinsic,
1664 
1665         .sigchld_event = swap_sigchld_event,
1666 
1667         .reset_failed = swap_reset_failed,
1668 
1669         .control_pid = swap_control_pid,
1670 
1671         .bus_set_property = bus_swap_set_property,
1672         .bus_commit_properties = bus_swap_commit_properties,
1673 
1674         .following = swap_following,
1675         .following_set = swap_following_set,
1676 
1677         .enumerate = swap_enumerate,
1678         .shutdown = swap_shutdown,
1679         .supported = swap_supported,
1680 
1681         .status_message_formats = {
1682                 .starting_stopping = {
1683                         [0] = "Activating swap %s...",
1684                         [1] = "Deactivating swap %s...",
1685                 },
1686                 .finished_start_job = {
1687                         [JOB_DONE]       = "Activated swap %s.",
1688                         [JOB_FAILED]     = "Failed to activate swap %s.",
1689                         [JOB_TIMEOUT]    = "Timed out activating swap %s.",
1690                 },
1691                 .finished_stop_job = {
1692                         [JOB_DONE]       = "Deactivated swap %s.",
1693                         [JOB_FAILED]     = "Failed deactivating swap %s.",
1694                         [JOB_TIMEOUT]    = "Timed out deactivating swap %s.",
1695                 },
1696         },
1697 
1698         .can_start = swap_can_start,
1699 };
1700