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