]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/swap.c
6dc6bca34b89e9a7017acc6ab684e5ea3be4c72d
[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), TAKE_PID(s->control_pid));
159 }
160
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
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 goto fail;
440
441 SWAP(u)->what = strdup(what);
442 if (!SWAP(u)->what) {
443 r = -ENOMEM;
444 goto fail;
445 }
446
447 unit_add_to_load_queue(u);
448 } else
449 delete = false;
450
451 p = &SWAP(u)->parameters_proc_swaps;
452
453 if (!p->what) {
454 p->what = strdup(what_proc_swaps);
455 if (!p->what) {
456 r = -ENOMEM;
457 goto fail;
458 }
459 }
460
461 /* The unit is definitely around now, mark it as loaded if it was previously referenced but could not be
462 * loaded. After all we can load it now, from the data in /proc/swaps. */
463 if (IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_BAD_SETTING, UNIT_ERROR)) {
464 u->load_state = UNIT_LOADED;
465 u->load_error = 0;
466 }
467
468 if (set_flags) {
469 SWAP(u)->is_active = true;
470 SWAP(u)->just_activated = !SWAP(u)->from_proc_swaps;
471 }
472
473 SWAP(u)->from_proc_swaps = true;
474
475 p->priority = priority;
476 p->priority_set = true;
477
478 unit_add_to_dbus_queue(u);
479 return 0;
480
481 fail:
482 log_unit_warning_errno(u, r, "Failed to load swap unit: %m");
483
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, *devlink;
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], 0);
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 (s->control_pid > 0 &&
584 pid_is_unwaited(s->control_pid) &&
585 SWAP_STATE_WITH_PROCESS(new_state)) {
586
587 r = unit_watch_pid(UNIT(s), s->control_pid, 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_dynamic_creds(u);
598 (void) unit_setup_exec_runtime(u);
599 }
600
601 swap_set_state(s, new_state);
602 return 0;
603 }
604
605 static void swap_dump(Unit *u, FILE *f, const char *prefix) {
606 Swap *s = SWAP(u);
607 SwapParameters *p;
608
609 assert(s);
610 assert(f);
611
612 if (s->from_proc_swaps)
613 p = &s->parameters_proc_swaps;
614 else if (s->from_fragment)
615 p = &s->parameters_fragment;
616 else
617 p = NULL;
618
619 fprintf(f,
620 "%sSwap State: %s\n"
621 "%sResult: %s\n"
622 "%sClean Result: %s\n"
623 "%sWhat: %s\n"
624 "%sFrom /proc/swaps: %s\n"
625 "%sFrom fragment: %s\n"
626 "%sExtrinsic: %s\n",
627 prefix, swap_state_to_string(s->state),
628 prefix, swap_result_to_string(s->result),
629 prefix, swap_result_to_string(s->clean_result),
630 prefix, s->what,
631 prefix, yes_no(s->from_proc_swaps),
632 prefix, yes_no(s->from_fragment),
633 prefix, yes_no(swap_is_extrinsic(u)));
634
635 if (s->devnode)
636 fprintf(f, "%sDevice Node: %s\n", prefix, s->devnode);
637
638 if (p)
639 fprintf(f,
640 "%sPriority: %i\n"
641 "%sOptions: %s\n",
642 prefix, p->priority,
643 prefix, strempty(p->options));
644
645 fprintf(f,
646 "%sTimeoutSec: %s\n",
647 prefix, FORMAT_TIMESPAN(s->timeout_usec, USEC_PER_SEC));
648
649 if (s->control_pid > 0)
650 fprintf(f,
651 "%sControl PID: "PID_FMT"\n",
652 prefix, s->control_pid);
653
654 exec_context_dump(&s->exec_context, f, prefix);
655 kill_context_dump(&s->kill_context, f, prefix);
656 cgroup_context_dump(UNIT(s), f, prefix);
657 }
658
659 static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) {
660
661 _cleanup_(exec_params_clear) ExecParameters exec_params = {
662 .flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
663 .stdin_fd = -1,
664 .stdout_fd = -1,
665 .stderr_fd = -1,
666 .exec_fd = -1,
667 };
668 pid_t pid;
669 int r;
670
671 assert(s);
672 assert(c);
673 assert(_pid);
674
675 r = unit_prepare_exec(UNIT(s));
676 if (r < 0)
677 return r;
678
679 r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
680 if (r < 0)
681 goto fail;
682
683 r = unit_set_exec_params(UNIT(s), &exec_params);
684 if (r < 0)
685 goto fail;
686
687 r = exec_spawn(UNIT(s),
688 c,
689 &s->exec_context,
690 &exec_params,
691 s->exec_runtime,
692 &s->dynamic_creds,
693 &pid);
694 if (r < 0)
695 goto fail;
696
697 r = unit_watch_pid(UNIT(s), pid, true);
698 if (r < 0)
699 goto fail;
700
701 *_pid = pid;
702
703 return 0;
704
705 fail:
706 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
707
708 return r;
709 }
710
711 static void swap_enter_dead(Swap *s, SwapResult f) {
712 assert(s);
713
714 if (s->result == SWAP_SUCCESS)
715 s->result = f;
716
717 unit_log_result(UNIT(s), s->result == SWAP_SUCCESS, swap_result_to_string(s->result));
718 unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_stop);
719 swap_set_state(s, s->result != SWAP_SUCCESS ? SWAP_FAILED : SWAP_DEAD);
720
721 s->exec_runtime = exec_runtime_unref(s->exec_runtime, true);
722
723 unit_destroy_runtime_data(UNIT(s), &s->exec_context);
724
725 unit_unref_uid_gid(UNIT(s), true);
726
727 dynamic_creds_destroy(&s->dynamic_creds);
728 }
729
730 static void swap_enter_active(Swap *s, SwapResult f) {
731 assert(s);
732
733 if (s->result == SWAP_SUCCESS)
734 s->result = f;
735
736 swap_set_state(s, SWAP_ACTIVE);
737 }
738
739 static void swap_enter_dead_or_active(Swap *s, SwapResult f) {
740 assert(s);
741
742 if (s->from_proc_swaps) {
743 swap_enter_active(s, f);
744
745 LIST_FOREACH_OTHERS(same_devnode, other, s)
746 if (UNIT(other)->job)
747 swap_enter_dead_or_active(other, f);
748 } else
749 swap_enter_dead(s, f);
750 }
751
752 static int state_to_kill_operation(Swap *s, SwapState state) {
753 if (state == SWAP_DEACTIVATING_SIGTERM) {
754 if (unit_has_job_type(UNIT(s), JOB_RESTART))
755 return KILL_RESTART;
756 else
757 return KILL_TERMINATE;
758 }
759
760 return KILL_KILL;
761 }
762
763 static void swap_enter_signal(Swap *s, SwapState state, SwapResult f) {
764 int r;
765
766 assert(s);
767
768 if (s->result == SWAP_SUCCESS)
769 s->result = f;
770
771 r = unit_kill_context(UNIT(s),
772 &s->kill_context,
773 state_to_kill_operation(s, state),
774 -1,
775 s->control_pid,
776 false);
777 if (r < 0)
778 goto fail;
779
780 if (r > 0) {
781 r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
782 if (r < 0)
783 goto fail;
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 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
795 swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES);
796 }
797
798 static void swap_enter_activating(Swap *s) {
799 _cleanup_free_ char *opts = NULL;
800 int r;
801
802 assert(s);
803
804 unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_start);
805
806 s->control_command_id = SWAP_EXEC_ACTIVATE;
807 s->control_command = s->exec_command + SWAP_EXEC_ACTIVATE;
808
809 if (s->from_fragment) {
810 int priority = 0;
811
812 r = fstab_find_pri(s->parameters_fragment.options, &priority);
813 if (r < 0)
814 log_unit_warning_errno(UNIT(s), r, "Failed to parse swap priority \"%s\", ignoring: %m", s->parameters_fragment.options);
815 else if (r > 0 && s->parameters_fragment.priority_set)
816 log_unit_warning(UNIT(s), "Duplicate swap priority configuration by Priority= and Options= fields.");
817
818 if (r <= 0 && s->parameters_fragment.priority_set) {
819 if (s->parameters_fragment.options)
820 r = asprintf(&opts, "%s,pri=%i", s->parameters_fragment.options, s->parameters_fragment.priority);
821 else
822 r = asprintf(&opts, "pri=%i", s->parameters_fragment.priority);
823 if (r < 0) {
824 r = -ENOMEM;
825 goto fail;
826 }
827 }
828 }
829
830 r = exec_command_set(s->control_command, "/sbin/swapon", NULL);
831 if (r < 0)
832 goto fail;
833
834 if (s->parameters_fragment.options || opts) {
835 r = exec_command_append(s->control_command, "-o",
836 opts ?: s->parameters_fragment.options, NULL);
837 if (r < 0)
838 goto fail;
839 }
840
841 r = exec_command_append(s->control_command, s->what, NULL);
842 if (r < 0)
843 goto fail;
844
845 swap_unwatch_control_pid(s);
846
847 r = swap_spawn(s, s->control_command, &s->control_pid);
848 if (r < 0)
849 goto fail;
850
851 swap_set_state(s, SWAP_ACTIVATING);
852 return;
853
854 fail:
855 log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapon' task: %m");
856 swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES);
857 }
858
859 static void swap_enter_deactivating(Swap *s) {
860 int r;
861
862 assert(s);
863
864 s->control_command_id = SWAP_EXEC_DEACTIVATE;
865 s->control_command = s->exec_command + SWAP_EXEC_DEACTIVATE;
866
867 r = exec_command_set(s->control_command,
868 "/sbin/swapoff",
869 s->what,
870 NULL);
871 if (r < 0)
872 goto fail;
873
874 swap_unwatch_control_pid(s);
875
876 r = swap_spawn(s, s->control_command, &s->control_pid);
877 if (r < 0)
878 goto fail;
879
880 swap_set_state(s, SWAP_DEACTIVATING);
881
882 return;
883
884 fail:
885 log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapoff' task: %m");
886 swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES);
887 }
888
889 static void swap_cycle_clear(Swap *s) {
890 assert(s);
891
892 s->result = SWAP_SUCCESS;
893 exec_command_reset_status_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX);
894 UNIT(s)->reset_accounting = true;
895 }
896
897 static int swap_start(Unit *u) {
898 Swap *s = SWAP(u);
899 int r;
900
901 assert(s);
902
903 /* We cannot fulfill this request right now, try again later please! */
904 if (IN_SET(s->state,
905 SWAP_DEACTIVATING,
906 SWAP_DEACTIVATING_SIGTERM,
907 SWAP_DEACTIVATING_SIGKILL,
908 SWAP_CLEANING))
909 return -EAGAIN;
910
911 /* Already on it! */
912 if (s->state == SWAP_ACTIVATING)
913 return 0;
914
915 assert(IN_SET(s->state, SWAP_DEAD, SWAP_FAILED));
916
917 if (detect_container() > 0)
918 return -EPERM;
919
920 /* If there's a job for another swap unit for the same node
921 * running, then let's not dispatch this one for now, and wait
922 * until that other job has finished. */
923 LIST_FOREACH_OTHERS(same_devnode, other, s)
924 if (UNIT(other)->job && UNIT(other)->job->state == JOB_RUNNING)
925 return -EAGAIN;
926
927 r = unit_acquire_invocation_id(u);
928 if (r < 0)
929 return r;
930
931 swap_cycle_clear(s);
932 swap_enter_activating(s);
933 return 1;
934 }
935
936 static int swap_stop(Unit *u) {
937 Swap *s = SWAP(u);
938
939 assert(s);
940
941 switch (s->state) {
942
943 case SWAP_DEACTIVATING:
944 case SWAP_DEACTIVATING_SIGTERM:
945 case SWAP_DEACTIVATING_SIGKILL:
946 /* Already on it */
947 return 0;
948
949 case SWAP_ACTIVATING:
950 case SWAP_ACTIVATING_DONE:
951 /* There's a control process pending, directly enter kill mode */
952 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_SUCCESS);
953 return 0;
954
955 case SWAP_ACTIVE:
956 if (detect_container() > 0)
957 return -EPERM;
958
959 swap_enter_deactivating(s);
960 return 1;
961
962 case SWAP_CLEANING:
963 /* If we are currently cleaning, then abort it, brutally. */
964 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_SUCCESS);
965 return 0;
966
967 default:
968 assert_not_reached();
969 }
970 }
971
972 static int swap_serialize(Unit *u, FILE *f, FDSet *fds) {
973 Swap *s = SWAP(u);
974
975 assert(s);
976 assert(f);
977 assert(fds);
978
979 (void) serialize_item(f, "state", swap_state_to_string(s->state));
980 (void) serialize_item(f, "result", swap_result_to_string(s->result));
981
982 if (s->control_pid > 0)
983 (void) serialize_item_format(f, "control-pid", PID_FMT, s->control_pid);
984
985 if (s->control_command_id >= 0)
986 (void) serialize_item(f, "control-command", swap_exec_command_to_string(s->control_command_id));
987
988 return 0;
989 }
990
991 static int swap_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
992 Swap *s = SWAP(u);
993
994 assert(s);
995 assert(fds);
996
997 if (streq(key, "state")) {
998 SwapState state;
999
1000 state = swap_state_from_string(value);
1001 if (state < 0)
1002 log_unit_debug(u, "Failed to parse state value: %s", value);
1003 else
1004 s->deserialized_state = state;
1005 } else if (streq(key, "result")) {
1006 SwapResult f;
1007
1008 f = swap_result_from_string(value);
1009 if (f < 0)
1010 log_unit_debug(u, "Failed to parse result value: %s", value);
1011 else if (f != SWAP_SUCCESS)
1012 s->result = f;
1013 } else if (streq(key, "control-pid")) {
1014 pid_t pid;
1015
1016 if (parse_pid(value, &pid) < 0)
1017 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
1018 else
1019 s->control_pid = pid;
1020
1021 } else if (streq(key, "control-command")) {
1022 SwapExecCommand id;
1023
1024 id = swap_exec_command_from_string(value);
1025 if (id < 0)
1026 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
1027 else {
1028 s->control_command_id = id;
1029 s->control_command = s->exec_command + id;
1030 }
1031 } else
1032 log_unit_debug(u, "Unknown serialization key: %s", key);
1033
1034 return 0;
1035 }
1036
1037 static void swap_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1038 Swap *s = SWAP(u);
1039 SwapResult f;
1040
1041 assert(s);
1042 assert(pid >= 0);
1043
1044 if (pid != s->control_pid)
1045 return;
1046
1047 /* Let's scan /proc/swaps before we process SIGCHLD. For the reasoning see the similar code in
1048 * mount.c */
1049 (void) swap_process_proc_swaps(u->manager);
1050
1051 s->control_pid = 0;
1052
1053 if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
1054 f = SWAP_SUCCESS;
1055 else if (code == CLD_EXITED)
1056 f = SWAP_FAILURE_EXIT_CODE;
1057 else if (code == CLD_KILLED)
1058 f = SWAP_FAILURE_SIGNAL;
1059 else if (code == CLD_DUMPED)
1060 f = SWAP_FAILURE_CORE_DUMP;
1061 else
1062 assert_not_reached();
1063
1064 if (s->result == SWAP_SUCCESS)
1065 s->result = f;
1066
1067 if (s->control_command) {
1068 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
1069
1070 s->control_command = NULL;
1071 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
1072 }
1073
1074 unit_log_process_exit(
1075 u,
1076 "Swap process",
1077 swap_exec_command_to_string(s->control_command_id),
1078 f == SWAP_SUCCESS,
1079 code, status);
1080
1081 switch (s->state) {
1082
1083 case SWAP_ACTIVATING:
1084 case SWAP_ACTIVATING_DONE:
1085
1086 if (f == SWAP_SUCCESS || s->from_proc_swaps)
1087 swap_enter_active(s, f);
1088 else
1089 swap_enter_dead(s, f);
1090 break;
1091
1092 case SWAP_DEACTIVATING:
1093 case SWAP_DEACTIVATING_SIGKILL:
1094 case SWAP_DEACTIVATING_SIGTERM:
1095
1096 swap_enter_dead_or_active(s, f);
1097 break;
1098
1099 case SWAP_CLEANING:
1100 if (s->clean_result == SWAP_SUCCESS)
1101 s->clean_result = f;
1102
1103 swap_enter_dead(s, SWAP_SUCCESS);
1104 break;
1105
1106 default:
1107 assert_not_reached();
1108 }
1109
1110 /* Notify clients about changed exit status */
1111 unit_add_to_dbus_queue(u);
1112 }
1113
1114 static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
1115 Swap *s = SWAP(userdata);
1116
1117 assert(s);
1118 assert(s->timer_event_source == source);
1119
1120 switch (s->state) {
1121
1122 case SWAP_ACTIVATING:
1123 case SWAP_ACTIVATING_DONE:
1124 log_unit_warning(UNIT(s), "Activation timed out. Stopping.");
1125 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
1126 break;
1127
1128 case SWAP_DEACTIVATING:
1129 log_unit_warning(UNIT(s), "Deactivation timed out. Stopping.");
1130 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
1131 break;
1132
1133 case SWAP_DEACTIVATING_SIGTERM:
1134 if (s->kill_context.send_sigkill) {
1135 log_unit_warning(UNIT(s), "Swap process timed out. Killing.");
1136 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_FAILURE_TIMEOUT);
1137 } else {
1138 log_unit_warning(UNIT(s), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1139 swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT);
1140 }
1141 break;
1142
1143 case SWAP_DEACTIVATING_SIGKILL:
1144 log_unit_warning(UNIT(s), "Swap process still around after SIGKILL. Ignoring.");
1145 swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT);
1146 break;
1147
1148 case SWAP_CLEANING:
1149 log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
1150
1151 if (s->clean_result == SWAP_SUCCESS)
1152 s->clean_result = SWAP_FAILURE_TIMEOUT;
1153
1154 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, 0);
1155 break;
1156
1157 default:
1158 assert_not_reached();
1159 }
1160
1161 return 0;
1162 }
1163
1164 static int swap_load_proc_swaps(Manager *m, bool set_flags) {
1165 assert(m);
1166
1167 rewind(m->proc_swaps);
1168
1169 (void) fscanf(m->proc_swaps, "%*s %*s %*s %*s %*s\n");
1170
1171 for (unsigned i = 1;; i++) {
1172 _cleanup_free_ char *dev = NULL, *d = NULL;
1173 int prio = 0, k;
1174
1175 k = fscanf(m->proc_swaps,
1176 "%ms " /* device/file */
1177 "%*s " /* type of swap */
1178 "%*s " /* swap size */
1179 "%*s " /* used */
1180 "%i\n", /* priority */
1181 &dev, &prio);
1182 if (k != 2) {
1183 if (k == EOF)
1184 break;
1185
1186 log_warning("Failed to parse /proc/swaps:%u.", i);
1187 continue;
1188 }
1189
1190 ssize_t l = cunescape(dev, UNESCAPE_RELAX, &d);
1191 if (l < 0)
1192 return log_error_errno(l, "Failed to unescape device path: %m");
1193
1194 device_found_node(m, d, DEVICE_FOUND_SWAP, DEVICE_FOUND_SWAP);
1195
1196 (void) swap_process_new(m, d, prio, set_flags);
1197 }
1198
1199 return 0;
1200 }
1201
1202 static int swap_process_proc_swaps(Manager *m) {
1203 int r;
1204
1205 assert(m);
1206
1207 r = swap_load_proc_swaps(m, true);
1208 if (r < 0) {
1209 log_error_errno(r, "Failed to reread /proc/swaps: %m");
1210
1211 /* Reset flags, just in case, for late calls */
1212 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) {
1213 Swap *swap = SWAP(u);
1214
1215 assert(swap);
1216
1217 swap->is_active = swap->just_activated = false;
1218 }
1219
1220 return 0;
1221 }
1222
1223 manager_dispatch_load_queue(m);
1224
1225 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) {
1226 Swap *swap = SWAP(u);
1227
1228 assert(swap);
1229
1230 if (!swap->is_active) {
1231
1232 swap_unset_proc_swaps(swap);
1233
1234 switch (swap->state) {
1235
1236 case SWAP_ACTIVE:
1237 /* This has just been deactivated */
1238 swap_enter_dead(swap, SWAP_SUCCESS);
1239 break;
1240
1241 default:
1242 /* Fire again */
1243 swap_set_state(swap, swap->state);
1244 break;
1245 }
1246
1247 if (swap->what)
1248 device_found_node(m, swap->what, DEVICE_NOT_FOUND, DEVICE_FOUND_SWAP);
1249
1250 } else if (swap->just_activated) {
1251
1252 /* New swap entry */
1253
1254 switch (swap->state) {
1255
1256 case SWAP_DEAD:
1257 case SWAP_FAILED:
1258 (void) unit_acquire_invocation_id(u);
1259 swap_cycle_clear(swap);
1260 swap_enter_active(swap, SWAP_SUCCESS);
1261 break;
1262
1263 case SWAP_ACTIVATING:
1264 swap_set_state(swap, SWAP_ACTIVATING_DONE);
1265 break;
1266
1267 default:
1268 /* Nothing really changed, but let's
1269 * issue an notification call
1270 * nonetheless, in case somebody is
1271 * waiting for this. */
1272 swap_set_state(swap, swap->state);
1273 break;
1274 }
1275 }
1276
1277 /* Reset the flags for later calls */
1278 swap->is_active = swap->just_activated = false;
1279 }
1280
1281 return 1;
1282 }
1283
1284 static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1285 Manager *m = userdata;
1286
1287 assert(m);
1288 assert(revents & EPOLLPRI);
1289
1290 return swap_process_proc_swaps(m);
1291 }
1292
1293 static Unit *swap_following(Unit *u) {
1294 Swap *s = SWAP(u);
1295 Swap *first = NULL;
1296
1297 assert(s);
1298
1299 /* If the user configured the swap through /etc/fstab or
1300 * a device unit, follow that. */
1301
1302 if (s->from_fragment)
1303 return NULL;
1304
1305 LIST_FOREACH_OTHERS(same_devnode, other, s)
1306 if (other->from_fragment)
1307 return UNIT(other);
1308
1309 /* Otherwise, make everybody follow the unit that's named after
1310 * the swap device in the kernel */
1311
1312 if (streq_ptr(s->what, s->devnode))
1313 return NULL;
1314
1315 LIST_FOREACH(same_devnode, other, s->same_devnode_next)
1316 if (streq_ptr(other->what, other->devnode))
1317 return UNIT(other);
1318
1319 LIST_FOREACH_BACKWARDS(same_devnode, other, s->same_devnode_prev) {
1320 if (streq_ptr(other->what, other->devnode))
1321 return UNIT(other);
1322
1323 first = other;
1324 }
1325
1326 /* Fall back to the first on the list */
1327 return UNIT(first);
1328 }
1329
1330 static int swap_following_set(Unit *u, Set **_set) {
1331 Swap *s = SWAP(u);
1332 _cleanup_set_free_ Set *set = NULL;
1333 int r;
1334
1335 assert(s);
1336 assert(_set);
1337
1338 if (LIST_JUST_US(same_devnode, s)) {
1339 *_set = NULL;
1340 return 0;
1341 }
1342
1343 set = set_new(NULL);
1344 if (!set)
1345 return -ENOMEM;
1346
1347 LIST_FOREACH_OTHERS(same_devnode, other, s) {
1348 r = set_put(set, other);
1349 if (r < 0)
1350 return r;
1351 }
1352
1353 *_set = TAKE_PTR(set);
1354 return 1;
1355 }
1356
1357 static void swap_shutdown(Manager *m) {
1358 assert(m);
1359
1360 m->swap_event_source = sd_event_source_disable_unref(m->swap_event_source);
1361 m->proc_swaps = safe_fclose(m->proc_swaps);
1362 m->swaps_by_devnode = hashmap_free(m->swaps_by_devnode);
1363 }
1364
1365 static void swap_enumerate(Manager *m) {
1366 int r;
1367
1368 assert(m);
1369
1370 if (!m->proc_swaps) {
1371 m->proc_swaps = fopen("/proc/swaps", "re");
1372 if (!m->proc_swaps) {
1373 if (errno == ENOENT)
1374 log_debug_errno(errno, "Not swap enabled, skipping enumeration.");
1375 else
1376 log_warning_errno(errno, "Failed to open /proc/swaps, ignoring: %m");
1377
1378 return;
1379 }
1380
1381 r = sd_event_add_io(m->event, &m->swap_event_source, fileno(m->proc_swaps), EPOLLPRI, swap_dispatch_io, m);
1382 if (r < 0) {
1383 log_error_errno(r, "Failed to watch /proc/swaps: %m");
1384 goto fail;
1385 }
1386
1387 /* Dispatch this before we dispatch SIGCHLD, so that
1388 * we always get the events from /proc/swaps before
1389 * the SIGCHLD of /sbin/swapon. */
1390 r = sd_event_source_set_priority(m->swap_event_source, SD_EVENT_PRIORITY_NORMAL-10);
1391 if (r < 0) {
1392 log_error_errno(r, "Failed to change /proc/swaps priority: %m");
1393 goto fail;
1394 }
1395
1396 (void) sd_event_source_set_description(m->swap_event_source, "swap-proc");
1397 }
1398
1399 r = swap_load_proc_swaps(m, false);
1400 if (r < 0)
1401 goto fail;
1402
1403 return;
1404
1405 fail:
1406 swap_shutdown(m);
1407 }
1408
1409 int swap_process_device_new(Manager *m, sd_device *dev) {
1410 _cleanup_free_ char *e = NULL;
1411 const char *dn, *devlink;
1412 Unit *u;
1413 int r;
1414
1415 assert(m);
1416 assert(dev);
1417
1418 if (sd_device_get_devname(dev, &dn) < 0)
1419 return 0;
1420
1421 r = unit_name_from_path(dn, ".swap", &e);
1422 if (r < 0) {
1423 log_debug_errno(r, "Cannot convert device name '%s' to unit name, ignoring: %m", dn);
1424 return 0;
1425 }
1426
1427 u = manager_get_unit(m, e);
1428 if (u)
1429 r = swap_set_devnode(SWAP(u), dn);
1430
1431 FOREACH_DEVICE_DEVLINK(dev, devlink) {
1432 _cleanup_free_ char *n = NULL;
1433 int q;
1434
1435 q = unit_name_from_path(devlink, ".swap", &n);
1436 if (q == -EINVAL) /* If the name is not convertible to unit name, we can't manage it */
1437 continue;
1438 if (q < 0)
1439 return q;
1440
1441 u = manager_get_unit(m, n);
1442 if (u) {
1443 q = swap_set_devnode(SWAP(u), dn);
1444 if (q < 0)
1445 r = q;
1446 }
1447 }
1448
1449 return r;
1450 }
1451
1452 int swap_process_device_remove(Manager *m, sd_device *dev) {
1453 const char *dn;
1454 int r;
1455 Swap *s;
1456
1457 r = sd_device_get_devname(dev, &dn);
1458 if (r < 0)
1459 return 0;
1460
1461 while ((s = hashmap_get(m->swaps_by_devnode, dn))) {
1462 int q;
1463
1464 q = swap_set_devnode(s, NULL);
1465 if (q < 0)
1466 r = q;
1467 }
1468
1469 return r;
1470 }
1471
1472 static void swap_reset_failed(Unit *u) {
1473 Swap *s = SWAP(u);
1474
1475 assert(s);
1476
1477 if (s->state == SWAP_FAILED)
1478 swap_set_state(s, SWAP_DEAD);
1479
1480 s->result = SWAP_SUCCESS;
1481 s->clean_result = SWAP_SUCCESS;
1482 }
1483
1484 static int swap_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
1485 return unit_kill_common(u, who, signo, -1, SWAP(u)->control_pid, error);
1486 }
1487
1488 static int swap_get_timeout(Unit *u, usec_t *timeout) {
1489 Swap *s = SWAP(u);
1490 usec_t t;
1491 int r;
1492
1493 assert(s);
1494 assert(u);
1495
1496 if (!s->timer_event_source)
1497 return 0;
1498
1499 r = sd_event_source_get_time(s->timer_event_source, &t);
1500 if (r < 0)
1501 return r;
1502 if (t == USEC_INFINITY)
1503 return 0;
1504
1505 *timeout = t;
1506 return 1;
1507 }
1508
1509 static bool swap_supported(void) {
1510 static int supported = -1;
1511
1512 /* If swap support is not available in the kernel, or we are
1513 * running in a container we don't support swap units, and any
1514 * attempts to starting one should fail immediately. */
1515
1516 if (supported < 0)
1517 supported =
1518 access("/proc/swaps", F_OK) >= 0 &&
1519 detect_container() <= 0;
1520
1521 return supported;
1522 }
1523
1524 static int swap_control_pid(Unit *u) {
1525 Swap *s = SWAP(u);
1526
1527 assert(s);
1528
1529 return s->control_pid;
1530 }
1531
1532 static int swap_clean(Unit *u, ExecCleanMask mask) {
1533 _cleanup_strv_free_ char **l = NULL;
1534 Swap *s = SWAP(u);
1535 int r;
1536
1537 assert(s);
1538 assert(mask != 0);
1539
1540 if (s->state != SWAP_DEAD)
1541 return -EBUSY;
1542
1543 r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
1544 if (r < 0)
1545 return r;
1546
1547 if (strv_isempty(l))
1548 return -EUNATCH;
1549
1550 swap_unwatch_control_pid(s);
1551 s->clean_result = SWAP_SUCCESS;
1552 s->control_command = NULL;
1553 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
1554
1555 r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->exec_context.timeout_clean_usec));
1556 if (r < 0)
1557 goto fail;
1558
1559 r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
1560 if (r < 0)
1561 goto fail;
1562
1563 swap_set_state(s, SWAP_CLEANING);
1564
1565 return 0;
1566
1567 fail:
1568 log_unit_warning_errno(u, r, "Failed to initiate cleaning: %m");
1569 s->clean_result = SWAP_FAILURE_RESOURCES;
1570 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
1571 return r;
1572 }
1573
1574 static int swap_can_clean(Unit *u, ExecCleanMask *ret) {
1575 Swap *s = SWAP(u);
1576
1577 assert(s);
1578
1579 return exec_context_get_clean_mask(&s->exec_context, ret);
1580 }
1581
1582 static int swap_can_start(Unit *u) {
1583 Swap *s = SWAP(u);
1584 int r;
1585
1586 assert(s);
1587
1588 r = unit_test_start_limit(u);
1589 if (r < 0) {
1590 swap_enter_dead(s, SWAP_FAILURE_START_LIMIT_HIT);
1591 return r;
1592 }
1593
1594 return 1;
1595 }
1596
1597 static const char* const swap_exec_command_table[_SWAP_EXEC_COMMAND_MAX] = {
1598 [SWAP_EXEC_ACTIVATE] = "ExecActivate",
1599 [SWAP_EXEC_DEACTIVATE] = "ExecDeactivate",
1600 };
1601
1602 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command, SwapExecCommand);
1603
1604 static const char* const swap_result_table[_SWAP_RESULT_MAX] = {
1605 [SWAP_SUCCESS] = "success",
1606 [SWAP_FAILURE_RESOURCES] = "resources",
1607 [SWAP_FAILURE_TIMEOUT] = "timeout",
1608 [SWAP_FAILURE_EXIT_CODE] = "exit-code",
1609 [SWAP_FAILURE_SIGNAL] = "signal",
1610 [SWAP_FAILURE_CORE_DUMP] = "core-dump",
1611 [SWAP_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
1612 };
1613
1614 DEFINE_STRING_TABLE_LOOKUP(swap_result, SwapResult);
1615
1616 const UnitVTable swap_vtable = {
1617 .object_size = sizeof(Swap),
1618 .exec_context_offset = offsetof(Swap, exec_context),
1619 .cgroup_context_offset = offsetof(Swap, cgroup_context),
1620 .kill_context_offset = offsetof(Swap, kill_context),
1621 .exec_runtime_offset = offsetof(Swap, exec_runtime),
1622 .dynamic_creds_offset = offsetof(Swap, dynamic_creds),
1623
1624 .sections =
1625 "Unit\0"
1626 "Swap\0"
1627 "Install\0",
1628 .private_section = "Swap",
1629
1630 .can_fail = true,
1631
1632 .init = swap_init,
1633 .load = swap_load,
1634 .done = swap_done,
1635
1636 .coldplug = swap_coldplug,
1637
1638 .dump = swap_dump,
1639
1640 .start = swap_start,
1641 .stop = swap_stop,
1642
1643 .kill = swap_kill,
1644 .clean = swap_clean,
1645 .can_clean = swap_can_clean,
1646
1647 .get_timeout = swap_get_timeout,
1648
1649 .serialize = swap_serialize,
1650 .deserialize_item = swap_deserialize_item,
1651
1652 .active_state = swap_active_state,
1653 .sub_state_to_string = swap_sub_state_to_string,
1654
1655 .will_restart = unit_will_restart_default,
1656
1657 .may_gc = swap_may_gc,
1658 .is_extrinsic = swap_is_extrinsic,
1659
1660 .sigchld_event = swap_sigchld_event,
1661
1662 .reset_failed = swap_reset_failed,
1663
1664 .control_pid = swap_control_pid,
1665
1666 .bus_set_property = bus_swap_set_property,
1667 .bus_commit_properties = bus_swap_commit_properties,
1668
1669 .following = swap_following,
1670 .following_set = swap_following_set,
1671
1672 .enumerate = swap_enumerate,
1673 .shutdown = swap_shutdown,
1674 .supported = swap_supported,
1675
1676 .status_message_formats = {
1677 .starting_stopping = {
1678 [0] = "Activating swap %s...",
1679 [1] = "Deactivating swap %s...",
1680 },
1681 .finished_start_job = {
1682 [JOB_DONE] = "Activated swap %s.",
1683 [JOB_FAILED] = "Failed to activate swap %s.",
1684 [JOB_TIMEOUT] = "Timed out activating swap %s.",
1685 },
1686 .finished_stop_job = {
1687 [JOB_DONE] = "Deactivated swap %s.",
1688 [JOB_FAILED] = "Failed deactivating swap %s.",
1689 [JOB_TIMEOUT] = "Timed out deactivating swap %s.",
1690 },
1691 },
1692
1693 .can_start = swap_can_start,
1694 };