1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include "alloc-util.h"
11 #include "dbus-swap.h"
12 #include "dbus-unit.h"
13 #include "device-private.h"
14 #include "device-util.h"
17 #include "exit-status.h"
19 #include "format-util.h"
20 #include "fstab-util.h"
21 #include "parse-util.h"
22 #include "path-util.h"
23 #include "process-util.h"
24 #include "serialize.h"
26 #include "string-table.h"
27 #include "string-util.h"
29 #include "unit-name.h"
33 static const UnitActiveState state_translation_table
[_SWAP_STATE_MAX
] = {
34 [SWAP_DEAD
] = UNIT_INACTIVE
,
35 [SWAP_ACTIVATING
] = UNIT_ACTIVATING
,
36 [SWAP_ACTIVATING_DONE
] = UNIT_ACTIVE
,
37 [SWAP_ACTIVE
] = UNIT_ACTIVE
,
38 [SWAP_DEACTIVATING
] = UNIT_DEACTIVATING
,
39 [SWAP_DEACTIVATING_SIGTERM
] = UNIT_DEACTIVATING
,
40 [SWAP_DEACTIVATING_SIGKILL
] = UNIT_DEACTIVATING
,
41 [SWAP_FAILED
] = UNIT_FAILED
,
42 [SWAP_CLEANING
] = UNIT_MAINTENANCE
,
45 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
46 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
47 static int swap_process_proc_swaps(Manager
*m
);
49 static bool SWAP_STATE_WITH_PROCESS(SwapState state
) {
54 SWAP_DEACTIVATING_SIGTERM
,
55 SWAP_DEACTIVATING_SIGKILL
,
59 static void swap_unset_proc_swaps(Swap
*s
) {
62 if (!s
->from_proc_swaps
)
65 s
->parameters_proc_swaps
.what
= mfree(s
->parameters_proc_swaps
.what
);
66 s
->from_proc_swaps
= false;
69 static int swap_set_devnode(Swap
*s
, const char *devnode
) {
76 r
= hashmap_ensure_allocated(&UNIT(s
)->manager
->swaps_by_devnode
, &path_hash_ops
);
80 swaps
= UNIT(s
)->manager
->swaps_by_devnode
;
83 first
= hashmap_get(swaps
, s
->devnode
);
85 LIST_REMOVE(same_devnode
, first
, s
);
87 hashmap_replace(swaps
, first
->devnode
, first
);
89 hashmap_remove(swaps
, s
->devnode
);
91 s
->devnode
= mfree(s
->devnode
);
95 s
->devnode
= strdup(devnode
);
99 first
= hashmap_get(swaps
, s
->devnode
);
100 LIST_PREPEND(same_devnode
, first
, s
);
102 return hashmap_replace(swaps
, first
->devnode
, first
);
108 static void swap_init(Unit
*u
) {
112 assert(UNIT(s
)->load_state
== UNIT_STUB
);
114 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
116 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
117 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
119 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
121 u
->ignore_on_isolate
= true;
124 static void swap_unwatch_control_pid(Swap
*s
) {
127 if (s
->control_pid
<= 0)
130 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
134 static void swap_done(Unit
*u
) {
139 swap_unset_proc_swaps(s
);
140 swap_set_devnode(s
, NULL
);
142 s
->what
= mfree(s
->what
);
143 s
->parameters_fragment
.what
= mfree(s
->parameters_fragment
.what
);
144 s
->parameters_fragment
.options
= mfree(s
->parameters_fragment
.options
);
146 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
147 exec_command_done_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
148 s
->control_command
= NULL
;
150 dynamic_creds_unref(&s
->dynamic_creds
);
152 swap_unwatch_control_pid(s
);
154 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
157 static int swap_arm_timer(Swap
*s
, usec_t usec
) {
162 if (s
->timer_event_source
) {
163 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
167 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
170 if (usec
== USEC_INFINITY
)
173 r
= sd_event_add_time(
174 UNIT(s
)->manager
->event
,
175 &s
->timer_event_source
,
178 swap_dispatch_timer
, s
);
182 (void) sd_event_source_set_description(s
->timer_event_source
, "swap-timer");
187 static int swap_add_device_dependencies(Swap
*s
) {
193 if (!s
->from_fragment
)
196 if (is_device_path(s
->what
))
197 return unit_add_node_dependency(UNIT(s
), s
->what
, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
199 /* File based swap devices need to be ordered after systemd-remount-fs.service,
200 * since they might need a writable file system. */
201 return unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_REMOUNT_FS_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
204 static int swap_add_default_dependencies(Swap
*s
) {
209 if (!UNIT(s
)->default_dependencies
)
212 if (!MANAGER_IS_SYSTEM(UNIT(s
)->manager
))
215 if (detect_container() > 0)
218 /* swap units generated for the swap dev links are missing the
219 * ordering dep against the swap target. */
220 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SWAP_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
224 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_UMOUNT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
227 static int swap_verify(Swap
*s
) {
228 _cleanup_free_
char *e
= NULL
;
231 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
233 r
= unit_name_from_path(s
->what
, ".swap", &e
);
235 return log_unit_error_errno(UNIT(s
), r
, "Failed to generate unit name from path: %m");
237 if (!unit_has_name(UNIT(s
), e
)) {
238 log_unit_error(UNIT(s
), "Value of What= and unit name do not match, not loading.");
242 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
243 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.");
250 static int swap_load_devnode(Swap
*s
) {
251 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
258 if (stat(s
->what
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
261 r
= device_new_from_stat_rdev(&d
, &st
);
263 log_unit_full(UNIT(s
), r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
264 "Failed to allocate device for swap %s: %m", s
->what
);
268 if (sd_device_get_devname(d
, &p
) < 0)
271 return swap_set_devnode(s
, p
);
274 static int swap_add_extras(Swap
*s
) {
279 if (UNIT(s
)->fragment_path
)
280 s
->from_fragment
= true;
283 if (s
->parameters_fragment
.what
)
284 s
->what
= strdup(s
->parameters_fragment
.what
);
285 else if (s
->parameters_proc_swaps
.what
)
286 s
->what
= strdup(s
->parameters_proc_swaps
.what
);
288 r
= unit_name_to_path(UNIT(s
)->id
, &s
->what
);
297 path_simplify(s
->what
, false);
299 if (!UNIT(s
)->description
) {
300 r
= unit_set_description(UNIT(s
), s
->what
);
305 r
= unit_require_mounts_for(UNIT(s
), s
->what
, UNIT_DEPENDENCY_IMPLICIT
);
309 r
= swap_add_device_dependencies(s
);
313 r
= swap_load_devnode(s
);
317 r
= unit_patch_contexts(UNIT(s
));
321 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
325 r
= unit_set_default_slice(UNIT(s
));
329 r
= swap_add_default_dependencies(s
);
336 static int swap_load(Unit
*u
) {
341 assert(u
->load_state
== UNIT_STUB
);
343 /* Load a .swap file */
344 bool fragment_optional
= s
->from_proc_swaps
;
345 r
= unit_load_fragment_and_dropin(u
, !fragment_optional
);
347 /* Add in some extras, and do so either when we successfully loaded something or when /proc/swaps is
349 if (u
->load_state
== UNIT_LOADED
|| s
->from_proc_swaps
)
350 q
= swap_add_extras(s
);
356 if (u
->load_state
!= UNIT_LOADED
)
359 return swap_verify(s
);
362 static int swap_setup_unit(
365 const char *what_proc_swaps
,
369 _cleanup_free_
char *e
= NULL
;
377 assert(what_proc_swaps
);
379 r
= unit_name_from_path(what
, ".swap", &e
);
381 return log_unit_error_errno(u
, r
, "Failed to generate unit name from path: %m");
383 u
= manager_get_unit(m
, e
);
385 SWAP(u
)->from_proc_swaps
&&
386 !path_equal(SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
))
387 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
388 "Swap %s appeared twice with different device paths %s and %s",
389 e
, SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
);
394 r
= unit_new_for_name(m
, sizeof(Swap
), e
, &u
);
398 SWAP(u
)->what
= strdup(what
);
399 if (!SWAP(u
)->what
) {
404 unit_add_to_load_queue(u
);
408 p
= &SWAP(u
)->parameters_proc_swaps
;
411 p
->what
= strdup(what_proc_swaps
);
418 /* The unit is definitely around now, mark it as loaded if it was previously referenced but could not be
419 * loaded. After all we can load it now, from the data in /proc/swaps. */
420 if (IN_SET(u
->load_state
, UNIT_NOT_FOUND
, UNIT_BAD_SETTING
, UNIT_ERROR
)) {
421 u
->load_state
= UNIT_LOADED
;
426 SWAP(u
)->is_active
= true;
427 SWAP(u
)->just_activated
= !SWAP(u
)->from_proc_swaps
;
430 SWAP(u
)->from_proc_swaps
= true;
432 p
->priority
= priority
;
433 p
->priority_set
= true;
435 unit_add_to_dbus_queue(u
);
439 log_unit_warning_errno(u
, r
, "Failed to load swap unit: %m");
447 static int swap_process_new(Manager
*m
, const char *device
, int prio
, bool set_flags
) {
448 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
449 const char *dn
, *devlink
;
450 struct stat st
, st_link
;
455 r
= swap_setup_unit(m
, device
, device
, prio
, set_flags
);
459 /* If this is a block device, then let's add duplicates for
460 * all other names of this block device */
461 if (stat(device
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
464 r
= device_new_from_stat_rdev(&d
, &st
);
466 log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
467 "Failed to allocate device for swap %s: %m", device
);
471 /* Add the main device node */
472 if (sd_device_get_devname(d
, &dn
) >= 0 && !streq(dn
, device
))
473 swap_setup_unit(m
, dn
, device
, prio
, set_flags
);
475 /* Add additional units for all symlinks */
476 FOREACH_DEVICE_DEVLINK(d
, devlink
) {
478 /* Don't bother with the /dev/block links */
479 if (streq(devlink
, device
))
482 if (path_startswith(devlink
, "/dev/block/"))
485 if (stat(devlink
, &st_link
) >= 0 &&
486 (!S_ISBLK(st_link
.st_mode
) ||
487 st_link
.st_rdev
!= st
.st_rdev
))
490 swap_setup_unit(m
, devlink
, device
, prio
, set_flags
);
496 static void swap_set_state(Swap
*s
, SwapState state
) {
502 if (s
->state
!= state
)
503 bus_unit_send_pending_change_signal(UNIT(s
), false);
505 old_state
= s
->state
;
508 if (!SWAP_STATE_WITH_PROCESS(state
)) {
509 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
510 swap_unwatch_control_pid(s
);
511 s
->control_command
= NULL
;
512 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
515 if (state
!= old_state
)
516 log_unit_debug(UNIT(s
), "Changed %s -> %s", swap_state_to_string(old_state
), swap_state_to_string(state
));
518 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
520 /* If there other units for the same device node have a job
521 queued it might be worth checking again if it is runnable
522 now. This is necessary, since swap_start() refuses
523 operation with EAGAIN if there's already another job for
524 the same device node queued. */
525 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
526 if (UNIT(other
)->job
)
527 job_add_to_run_queue(UNIT(other
)->job
);
530 static int swap_coldplug(Unit
*u
) {
532 SwapState new_state
= SWAP_DEAD
;
536 assert(s
->state
== SWAP_DEAD
);
538 if (s
->deserialized_state
!= s
->state
)
539 new_state
= s
->deserialized_state
;
540 else if (s
->from_proc_swaps
)
541 new_state
= SWAP_ACTIVE
;
543 if (new_state
== s
->state
)
546 if (s
->control_pid
> 0 &&
547 pid_is_unwaited(s
->control_pid
) &&
548 SWAP_STATE_WITH_PROCESS(new_state
)) {
550 r
= unit_watch_pid(UNIT(s
), s
->control_pid
, false);
554 r
= swap_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
559 if (!IN_SET(new_state
, SWAP_DEAD
, SWAP_FAILED
)) {
560 (void) unit_setup_dynamic_creds(u
);
561 (void) unit_setup_exec_runtime(u
);
564 swap_set_state(s
, new_state
);
568 static void swap_dump(Unit
*u
, FILE *f
, const char *prefix
) {
569 char buf
[FORMAT_TIMESPAN_MAX
];
576 if (s
->from_proc_swaps
)
577 p
= &s
->parameters_proc_swaps
;
578 else if (s
->from_fragment
)
579 p
= &s
->parameters_fragment
;
586 "%sClean Result: %s\n"
588 "%sFrom /proc/swaps: %s\n"
589 "%sFrom fragment: %s\n",
590 prefix
, swap_state_to_string(s
->state
),
591 prefix
, swap_result_to_string(s
->result
),
592 prefix
, swap_result_to_string(s
->clean_result
),
594 prefix
, yes_no(s
->from_proc_swaps
),
595 prefix
, yes_no(s
->from_fragment
));
598 fprintf(f
, "%sDevice Node: %s\n", prefix
, s
->devnode
);
605 prefix
, strempty(p
->options
));
608 "%sTimeoutSec: %s\n",
609 prefix
, format_timespan(buf
, sizeof(buf
), s
->timeout_usec
, USEC_PER_SEC
));
611 if (s
->control_pid
> 0)
613 "%sControl PID: "PID_FMT
"\n",
614 prefix
, s
->control_pid
);
616 exec_context_dump(&s
->exec_context
, f
, prefix
);
617 kill_context_dump(&s
->kill_context
, f
, prefix
);
618 cgroup_context_dump(UNIT(s
), f
, prefix
);
621 static int swap_spawn(Swap
*s
, ExecCommand
*c
, pid_t
*_pid
) {
623 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
624 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
637 r
= unit_prepare_exec(UNIT(s
));
641 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
645 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
649 r
= exec_spawn(UNIT(s
),
659 r
= unit_watch_pid(UNIT(s
), pid
, true);
668 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
673 static void swap_enter_dead(Swap
*s
, SwapResult f
) {
676 if (s
->result
== SWAP_SUCCESS
)
679 unit_log_result(UNIT(s
), s
->result
== SWAP_SUCCESS
, swap_result_to_string(s
->result
));
680 swap_set_state(s
, s
->result
!= SWAP_SUCCESS
? SWAP_FAILED
: SWAP_DEAD
);
682 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
684 unit_destroy_runtime_directory(UNIT(s
), &s
->exec_context
);
686 unit_unref_uid_gid(UNIT(s
), true);
688 dynamic_creds_destroy(&s
->dynamic_creds
);
691 static void swap_enter_active(Swap
*s
, SwapResult f
) {
694 if (s
->result
== SWAP_SUCCESS
)
697 swap_set_state(s
, SWAP_ACTIVE
);
700 static void swap_enter_dead_or_active(Swap
*s
, SwapResult f
) {
703 if (s
->from_proc_swaps
)
704 swap_enter_active(s
, f
);
706 swap_enter_dead(s
, f
);
709 static int state_to_kill_operation(Swap
*s
, SwapState state
) {
710 if (state
== SWAP_DEACTIVATING_SIGTERM
) {
711 if (unit_has_job_type(UNIT(s
), JOB_RESTART
))
714 return KILL_TERMINATE
;
720 static void swap_enter_signal(Swap
*s
, SwapState state
, SwapResult f
) {
725 if (s
->result
== SWAP_SUCCESS
)
728 r
= unit_kill_context(UNIT(s
),
730 state_to_kill_operation(s
, state
),
738 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
742 swap_set_state(s
, state
);
743 } else if (state
== SWAP_DEACTIVATING_SIGTERM
&& s
->kill_context
.send_sigkill
)
744 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
746 swap_enter_dead_or_active(s
, SWAP_SUCCESS
);
751 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
752 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
755 static void swap_enter_activating(Swap
*s
) {
756 _cleanup_free_
char *opts
= NULL
;
761 unit_warn_leftover_processes(UNIT(s
));
763 s
->control_command_id
= SWAP_EXEC_ACTIVATE
;
764 s
->control_command
= s
->exec_command
+ SWAP_EXEC_ACTIVATE
;
766 if (s
->from_fragment
) {
769 r
= fstab_find_pri(s
->parameters_fragment
.options
, &priority
);
771 log_unit_warning_errno(UNIT(s
), r
, "Failed to parse swap priority \"%s\", ignoring: %m", s
->parameters_fragment
.options
);
772 else if (r
> 0 && s
->parameters_fragment
.priority_set
)
773 log_unit_warning(UNIT(s
), "Duplicate swap priority configuration by Priority= and Options= fields.");
775 if (r
<= 0 && s
->parameters_fragment
.priority_set
) {
776 if (s
->parameters_fragment
.options
)
777 r
= asprintf(&opts
, "%s,pri=%i", s
->parameters_fragment
.options
, s
->parameters_fragment
.priority
);
779 r
= asprintf(&opts
, "pri=%i", s
->parameters_fragment
.priority
);
787 r
= exec_command_set(s
->control_command
, "/sbin/swapon", NULL
);
791 if (s
->parameters_fragment
.options
|| opts
) {
792 r
= exec_command_append(s
->control_command
, "-o",
793 opts
?: s
->parameters_fragment
.options
, NULL
);
798 r
= exec_command_append(s
->control_command
, s
->what
, NULL
);
802 swap_unwatch_control_pid(s
);
804 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
808 swap_set_state(s
, SWAP_ACTIVATING
);
812 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapon' task: %m");
813 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
816 static void swap_enter_deactivating(Swap
*s
) {
821 s
->control_command_id
= SWAP_EXEC_DEACTIVATE
;
822 s
->control_command
= s
->exec_command
+ SWAP_EXEC_DEACTIVATE
;
824 r
= exec_command_set(s
->control_command
,
831 swap_unwatch_control_pid(s
);
833 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
837 swap_set_state(s
, SWAP_DEACTIVATING
);
842 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapoff' task: %m");
843 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
846 static void swap_cycle_clear(Swap
*s
) {
849 s
->result
= SWAP_SUCCESS
;
850 exec_command_reset_status_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
851 UNIT(s
)->reset_accounting
= true;
854 static int swap_start(Unit
*u
) {
855 Swap
*s
= SWAP(u
), *other
;
860 /* We cannot fulfill this request right now, try again later please! */
863 SWAP_DEACTIVATING_SIGTERM
,
864 SWAP_DEACTIVATING_SIGKILL
,
869 if (s
->state
== SWAP_ACTIVATING
)
872 assert(IN_SET(s
->state
, SWAP_DEAD
, SWAP_FAILED
));
874 if (detect_container() > 0)
877 /* If there's a job for another swap unit for the same node
878 * running, then let's not dispatch this one for now, and wait
879 * until that other job has finished. */
880 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
881 if (UNIT(other
)->job
&& UNIT(other
)->job
->state
== JOB_RUNNING
)
884 r
= unit_test_start_limit(u
);
886 swap_enter_dead(s
, SWAP_FAILURE_START_LIMIT_HIT
);
890 r
= unit_acquire_invocation_id(u
);
895 swap_enter_activating(s
);
899 static int swap_stop(Unit
*u
) {
906 case SWAP_DEACTIVATING
:
907 case SWAP_DEACTIVATING_SIGTERM
:
908 case SWAP_DEACTIVATING_SIGKILL
:
912 case SWAP_ACTIVATING
:
913 case SWAP_ACTIVATING_DONE
:
914 /* There's a control process pending, directly enter kill mode */
915 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_SUCCESS
);
919 if (detect_container() > 0)
922 swap_enter_deactivating(s
);
926 /* If we are currently cleaning, then abort it, brutally. */
927 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
931 assert_not_reached("Unexpected state.");
935 static int swap_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
942 (void) serialize_item(f
, "state", swap_state_to_string(s
->state
));
943 (void) serialize_item(f
, "result", swap_result_to_string(s
->result
));
945 if (s
->control_pid
> 0)
946 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
);
948 if (s
->control_command_id
>= 0)
949 (void) serialize_item(f
, "control-command", swap_exec_command_to_string(s
->control_command_id
));
954 static int swap_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
960 if (streq(key
, "state")) {
963 state
= swap_state_from_string(value
);
965 log_unit_debug(u
, "Failed to parse state value: %s", value
);
967 s
->deserialized_state
= state
;
968 } else if (streq(key
, "result")) {
971 f
= swap_result_from_string(value
);
973 log_unit_debug(u
, "Failed to parse result value: %s", value
);
974 else if (f
!= SWAP_SUCCESS
)
976 } else if (streq(key
, "control-pid")) {
979 if (parse_pid(value
, &pid
) < 0)
980 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
982 s
->control_pid
= pid
;
984 } else if (streq(key
, "control-command")) {
987 id
= swap_exec_command_from_string(value
);
989 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
991 s
->control_command_id
= id
;
992 s
->control_command
= s
->exec_command
+ id
;
995 log_unit_debug(u
, "Unknown serialization key: %s", key
);
1000 _pure_
static UnitActiveState
swap_active_state(Unit
*u
) {
1003 return state_translation_table
[SWAP(u
)->state
];
1006 _pure_
static const char *swap_sub_state_to_string(Unit
*u
) {
1009 return swap_state_to_string(SWAP(u
)->state
);
1012 _pure_
static bool swap_may_gc(Unit
*u
) {
1017 if (s
->from_proc_swaps
)
1023 static void swap_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
1030 if (pid
!= s
->control_pid
)
1033 /* Let's scan /proc/swaps before we process SIGCHLD. For the reasoning see the similar code in
1035 (void) swap_process_proc_swaps(u
->manager
);
1039 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
1041 else if (code
== CLD_EXITED
)
1042 f
= SWAP_FAILURE_EXIT_CODE
;
1043 else if (code
== CLD_KILLED
)
1044 f
= SWAP_FAILURE_SIGNAL
;
1045 else if (code
== CLD_DUMPED
)
1046 f
= SWAP_FAILURE_CORE_DUMP
;
1048 assert_not_reached("Unknown code");
1050 if (s
->result
== SWAP_SUCCESS
)
1053 if (s
->control_command
) {
1054 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
1056 s
->control_command
= NULL
;
1057 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1060 unit_log_process_exit(
1063 swap_exec_command_to_string(s
->control_command_id
),
1069 case SWAP_ACTIVATING
:
1070 case SWAP_ACTIVATING_DONE
:
1072 if (f
== SWAP_SUCCESS
|| s
->from_proc_swaps
)
1073 swap_enter_active(s
, f
);
1075 swap_enter_dead(s
, f
);
1078 case SWAP_DEACTIVATING
:
1079 case SWAP_DEACTIVATING_SIGKILL
:
1080 case SWAP_DEACTIVATING_SIGTERM
:
1082 swap_enter_dead_or_active(s
, f
);
1086 if (s
->clean_result
== SWAP_SUCCESS
)
1087 s
->clean_result
= f
;
1089 swap_enter_dead(s
, SWAP_SUCCESS
);
1093 assert_not_reached("Uh, control process died at wrong time.");
1096 /* Notify clients about changed exit status */
1097 unit_add_to_dbus_queue(u
);
1100 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
1101 Swap
*s
= SWAP(userdata
);
1104 assert(s
->timer_event_source
== source
);
1108 case SWAP_ACTIVATING
:
1109 case SWAP_ACTIVATING_DONE
:
1110 log_unit_warning(UNIT(s
), "Activation timed out. Stopping.");
1111 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1114 case SWAP_DEACTIVATING
:
1115 log_unit_warning(UNIT(s
), "Deactivation timed out. Stopping.");
1116 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1119 case SWAP_DEACTIVATING_SIGTERM
:
1120 if (s
->kill_context
.send_sigkill
) {
1121 log_unit_warning(UNIT(s
), "Swap process timed out. Killing.");
1122 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_FAILURE_TIMEOUT
);
1124 log_unit_warning(UNIT(s
), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1125 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1129 case SWAP_DEACTIVATING_SIGKILL
:
1130 log_unit_warning(UNIT(s
), "Swap process still around after SIGKILL. Ignoring.");
1131 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1135 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
1137 if (s
->clean_result
== SWAP_SUCCESS
)
1138 s
->clean_result
= SWAP_FAILURE_TIMEOUT
;
1140 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, 0);
1144 assert_not_reached("Timeout at wrong time.");
1150 static int swap_load_proc_swaps(Manager
*m
, bool set_flags
) {
1155 rewind(m
->proc_swaps
);
1157 (void) fscanf(m
->proc_swaps
, "%*s %*s %*s %*s %*s\n");
1160 _cleanup_free_
char *dev
= NULL
, *d
= NULL
;
1163 k
= fscanf(m
->proc_swaps
,
1164 "%ms " /* device/file */
1165 "%*s " /* type of swap */
1166 "%*s " /* swap size */
1168 "%i\n", /* priority */
1174 log_warning("Failed to parse /proc/swaps:%u.", i
);
1178 if (cunescape(dev
, UNESCAPE_RELAX
, &d
) < 0)
1181 device_found_node(m
, d
, DEVICE_FOUND_SWAP
, DEVICE_FOUND_SWAP
);
1183 (void) swap_process_new(m
, d
, prio
, set_flags
);
1189 static int swap_process_proc_swaps(Manager
*m
) {
1195 r
= swap_load_proc_swaps(m
, true);
1197 log_error_errno(r
, "Failed to reread /proc/swaps: %m");
1199 /* Reset flags, just in case, for late calls */
1200 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1201 Swap
*swap
= SWAP(u
);
1203 swap
->is_active
= swap
->just_activated
= false;
1209 manager_dispatch_load_queue(m
);
1211 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1212 Swap
*swap
= SWAP(u
);
1214 if (!swap
->is_active
) {
1216 swap_unset_proc_swaps(swap
);
1218 switch (swap
->state
) {
1221 /* This has just been deactivated */
1222 swap_enter_dead(swap
, SWAP_SUCCESS
);
1227 swap_set_state(swap
, swap
->state
);
1232 device_found_node(m
, swap
->what
, 0, DEVICE_FOUND_SWAP
);
1234 } else if (swap
->just_activated
) {
1236 /* New swap entry */
1238 switch (swap
->state
) {
1242 (void) unit_acquire_invocation_id(u
);
1243 swap_cycle_clear(swap
);
1244 swap_enter_active(swap
, SWAP_SUCCESS
);
1247 case SWAP_ACTIVATING
:
1248 swap_set_state(swap
, SWAP_ACTIVATING_DONE
);
1252 /* Nothing really changed, but let's
1253 * issue an notification call
1254 * nonetheless, in case somebody is
1255 * waiting for this. */
1256 swap_set_state(swap
, swap
->state
);
1261 /* Reset the flags for later calls */
1262 swap
->is_active
= swap
->just_activated
= false;
1268 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
1269 Manager
*m
= userdata
;
1272 assert(revents
& EPOLLPRI
);
1274 return swap_process_proc_swaps(m
);
1277 static Unit
*swap_following(Unit
*u
) {
1279 Swap
*other
, *first
= NULL
;
1283 /* If the user configured the swap through /etc/fstab or
1284 * a device unit, follow that. */
1286 if (s
->from_fragment
)
1289 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
1290 if (other
->from_fragment
)
1293 /* Otherwise, make everybody follow the unit that's named after
1294 * the swap device in the kernel */
1296 if (streq_ptr(s
->what
, s
->devnode
))
1299 LIST_FOREACH_AFTER(same_devnode
, other
, s
)
1300 if (streq_ptr(other
->what
, other
->devnode
))
1303 LIST_FOREACH_BEFORE(same_devnode
, other
, s
) {
1304 if (streq_ptr(other
->what
, other
->devnode
))
1310 /* Fall back to the first on the list */
1314 static int swap_following_set(Unit
*u
, Set
**_set
) {
1315 Swap
*s
= SWAP(u
), *other
;
1316 _cleanup_set_free_ Set
*set
= NULL
;
1322 if (LIST_JUST_US(same_devnode
, s
)) {
1327 set
= set_new(NULL
);
1331 LIST_FOREACH_OTHERS(same_devnode
, other
, s
) {
1332 r
= set_put(set
, other
);
1337 *_set
= TAKE_PTR(set
);
1341 static void swap_shutdown(Manager
*m
) {
1344 m
->swap_event_source
= sd_event_source_unref(m
->swap_event_source
);
1345 m
->proc_swaps
= safe_fclose(m
->proc_swaps
);
1346 m
->swaps_by_devnode
= hashmap_free(m
->swaps_by_devnode
);
1349 static void swap_enumerate(Manager
*m
) {
1354 if (!m
->proc_swaps
) {
1355 m
->proc_swaps
= fopen("/proc/swaps", "re");
1356 if (!m
->proc_swaps
) {
1357 if (errno
== ENOENT
)
1358 log_debug_errno(errno
, "Not swap enabled, skipping enumeration.");
1360 log_warning_errno(errno
, "Failed to open /proc/swaps, ignoring: %m");
1365 r
= sd_event_add_io(m
->event
, &m
->swap_event_source
, fileno(m
->proc_swaps
), EPOLLPRI
, swap_dispatch_io
, m
);
1367 log_error_errno(r
, "Failed to watch /proc/swaps: %m");
1371 /* Dispatch this before we dispatch SIGCHLD, so that
1372 * we always get the events from /proc/swaps before
1373 * the SIGCHLD of /sbin/swapon. */
1374 r
= sd_event_source_set_priority(m
->swap_event_source
, SD_EVENT_PRIORITY_NORMAL
-10);
1376 log_error_errno(r
, "Failed to change /proc/swaps priority: %m");
1380 (void) sd_event_source_set_description(m
->swap_event_source
, "swap-proc");
1383 r
= swap_load_proc_swaps(m
, false);
1393 int swap_process_device_new(Manager
*m
, sd_device
*dev
) {
1394 _cleanup_free_
char *e
= NULL
;
1395 const char *dn
, *devlink
;
1402 r
= sd_device_get_devname(dev
, &dn
);
1406 r
= unit_name_from_path(dn
, ".swap", &e
);
1410 u
= manager_get_unit(m
, e
);
1412 r
= swap_set_devnode(SWAP(u
), dn
);
1414 FOREACH_DEVICE_DEVLINK(dev
, devlink
) {
1415 _cleanup_free_
char *n
= NULL
;
1418 q
= unit_name_from_path(devlink
, ".swap", &n
);
1422 u
= manager_get_unit(m
, n
);
1424 q
= swap_set_devnode(SWAP(u
), dn
);
1433 int swap_process_device_remove(Manager
*m
, sd_device
*dev
) {
1438 r
= sd_device_get_devname(dev
, &dn
);
1442 while ((s
= hashmap_get(m
->swaps_by_devnode
, dn
))) {
1445 q
= swap_set_devnode(s
, NULL
);
1453 static void swap_reset_failed(Unit
*u
) {
1458 if (s
->state
== SWAP_FAILED
)
1459 swap_set_state(s
, SWAP_DEAD
);
1461 s
->result
= SWAP_SUCCESS
;
1462 s
->clean_result
= SWAP_SUCCESS
;
1465 static int swap_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
1466 return unit_kill_common(u
, who
, signo
, -1, SWAP(u
)->control_pid
, error
);
1469 static int swap_get_timeout(Unit
*u
, usec_t
*timeout
) {
1474 if (!s
->timer_event_source
)
1477 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
1480 if (t
== USEC_INFINITY
)
1487 static bool swap_supported(void) {
1488 static int supported
= -1;
1490 /* If swap support is not available in the kernel, or we are
1491 * running in a container we don't support swap units, and any
1492 * attempts to starting one should fail immediately. */
1496 access("/proc/swaps", F_OK
) >= 0 &&
1497 detect_container() <= 0;
1502 static int swap_control_pid(Unit
*u
) {
1507 return s
->control_pid
;
1510 static int swap_clean(Unit
*u
, ExecCleanMask mask
) {
1511 _cleanup_strv_free_
char **l
= NULL
;
1518 if (s
->state
!= SWAP_DEAD
)
1521 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
1525 if (strv_isempty(l
))
1528 swap_unwatch_control_pid(s
);
1529 s
->clean_result
= SWAP_SUCCESS
;
1530 s
->control_command
= NULL
;
1531 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1533 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->exec_context
.timeout_clean_usec
));
1537 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
1541 swap_set_state(s
, SWAP_CLEANING
);
1546 log_unit_warning_errno(u
, r
, "Failed to initiate cleaning: %m");
1547 s
->clean_result
= SWAP_FAILURE_RESOURCES
;
1548 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1552 static int swap_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
1557 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
1560 static const char* const swap_exec_command_table
[_SWAP_EXEC_COMMAND_MAX
] = {
1561 [SWAP_EXEC_ACTIVATE
] = "ExecActivate",
1562 [SWAP_EXEC_DEACTIVATE
] = "ExecDeactivate",
1565 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command
, SwapExecCommand
);
1567 static const char* const swap_result_table
[_SWAP_RESULT_MAX
] = {
1568 [SWAP_SUCCESS
] = "success",
1569 [SWAP_FAILURE_RESOURCES
] = "resources",
1570 [SWAP_FAILURE_TIMEOUT
] = "timeout",
1571 [SWAP_FAILURE_EXIT_CODE
] = "exit-code",
1572 [SWAP_FAILURE_SIGNAL
] = "signal",
1573 [SWAP_FAILURE_CORE_DUMP
] = "core-dump",
1574 [SWAP_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
1577 DEFINE_STRING_TABLE_LOOKUP(swap_result
, SwapResult
);
1579 const UnitVTable swap_vtable
= {
1580 .object_size
= sizeof(Swap
),
1581 .exec_context_offset
= offsetof(Swap
, exec_context
),
1582 .cgroup_context_offset
= offsetof(Swap
, cgroup_context
),
1583 .kill_context_offset
= offsetof(Swap
, kill_context
),
1584 .exec_runtime_offset
= offsetof(Swap
, exec_runtime
),
1585 .dynamic_creds_offset
= offsetof(Swap
, dynamic_creds
),
1591 .private_section
= "Swap",
1597 .coldplug
= swap_coldplug
,
1601 .start
= swap_start
,
1605 .clean
= swap_clean
,
1606 .can_clean
= swap_can_clean
,
1608 .get_timeout
= swap_get_timeout
,
1610 .serialize
= swap_serialize
,
1611 .deserialize_item
= swap_deserialize_item
,
1613 .active_state
= swap_active_state
,
1614 .sub_state_to_string
= swap_sub_state_to_string
,
1616 .will_restart
= unit_will_restart_default
,
1618 .may_gc
= swap_may_gc
,
1620 .sigchld_event
= swap_sigchld_event
,
1622 .reset_failed
= swap_reset_failed
,
1624 .control_pid
= swap_control_pid
,
1626 .bus_vtable
= bus_swap_vtable
,
1627 .bus_set_property
= bus_swap_set_property
,
1628 .bus_commit_properties
= bus_swap_commit_properties
,
1630 .following
= swap_following
,
1631 .following_set
= swap_following_set
,
1633 .enumerate
= swap_enumerate
,
1634 .shutdown
= swap_shutdown
,
1635 .supported
= swap_supported
,
1637 .status_message_formats
= {
1638 .starting_stopping
= {
1639 [0] = "Activating swap %s...",
1640 [1] = "Deactivating swap %s...",
1642 .finished_start_job
= {
1643 [JOB_DONE
] = "Activated swap %s.",
1644 [JOB_FAILED
] = "Failed to activate swap %s.",
1645 [JOB_TIMEOUT
] = "Timed out activating swap %s.",
1647 .finished_stop_job
= {
1648 [JOB_DONE
] = "Deactivated swap %s.",
1649 [JOB_FAILED
] = "Failed deactivating swap %s.",
1650 [JOB_TIMEOUT
] = "Timed out deactivating swap %s.",