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