1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include "alloc-util.h"
11 #include "dbus-swap.h"
12 #include "dbus-unit.h"
13 #include "device-util.h"
16 #include "exit-status.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"
25 #include "string-table.h"
26 #include "string-util.h"
28 #include "unit-name.h"
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
,
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
);
48 static bool SWAP_STATE_WITH_PROCESS(SwapState state
) {
53 SWAP_DEACTIVATING_SIGTERM
,
54 SWAP_DEACTIVATING_SIGKILL
,
58 static UnitActiveState
swap_active_state(Unit
*u
) {
61 return state_translation_table
[SWAP(u
)->state
];
64 static const char *swap_sub_state_to_string(Unit
*u
) {
67 return swap_state_to_string(SWAP(u
)->state
);
70 static bool swap_may_gc(Unit
*u
) {
75 if (s
->from_proc_swaps
)
81 static bool swap_is_extrinsic(Unit
*u
) {
84 return MANAGER_IS_USER(u
->manager
);
87 static void swap_unset_proc_swaps(Swap
*s
) {
90 if (!s
->from_proc_swaps
)
93 s
->parameters_proc_swaps
.what
= mfree(s
->parameters_proc_swaps
.what
);
94 s
->from_proc_swaps
= false;
97 static int swap_set_devnode(Swap
*s
, const char *devnode
) {
104 r
= hashmap_ensure_allocated(&UNIT(s
)->manager
->swaps_by_devnode
, &path_hash_ops
);
108 swaps
= UNIT(s
)->manager
->swaps_by_devnode
;
111 first
= hashmap_get(swaps
, s
->devnode
);
113 LIST_REMOVE(same_devnode
, first
, s
);
115 hashmap_replace(swaps
, first
->devnode
, first
);
117 hashmap_remove(swaps
, s
->devnode
);
119 s
->devnode
= mfree(s
->devnode
);
123 s
->devnode
= strdup(devnode
);
127 first
= hashmap_get(swaps
, s
->devnode
);
128 LIST_PREPEND(same_devnode
, first
, s
);
130 return hashmap_replace(swaps
, first
->devnode
, first
);
136 static void swap_init(Unit
*u
) {
140 assert(UNIT(s
)->load_state
== UNIT_STUB
);
142 s
->timeout_usec
= u
->manager
->defaults
.timeout_start_usec
;
144 s
->exec_context
.std_output
= u
->manager
->defaults
.std_output
;
145 s
->exec_context
.std_error
= u
->manager
->defaults
.std_error
;
147 s
->control_pid
= PIDREF_NULL
;
148 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
150 u
->ignore_on_isolate
= true;
153 static void swap_unwatch_control_pid(Swap
*s
) {
156 if (!pidref_is_set(&s
->control_pid
))
159 unit_unwatch_pidref(UNIT(s
), &s
->control_pid
);
160 pidref_done(&s
->control_pid
);
163 static void swap_done(Unit
*u
) {
168 swap_unset_proc_swaps(s
);
169 swap_set_devnode(s
, NULL
);
171 s
->what
= mfree(s
->what
);
172 s
->parameters_fragment
.what
= mfree(s
->parameters_fragment
.what
);
173 s
->parameters_fragment
.options
= mfree(s
->parameters_fragment
.options
);
175 s
->exec_runtime
= exec_runtime_free(s
->exec_runtime
);
176 exec_command_done_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
177 s
->control_command
= NULL
;
179 swap_unwatch_control_pid(s
);
181 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
184 static int swap_arm_timer(Swap
*s
, bool relative
, usec_t usec
) {
187 return unit_arm_timer(UNIT(s
), &s
->timer_event_source
, relative
, usec
, swap_dispatch_timer
);
190 static SwapParameters
* swap_get_parameters(Swap
*s
) {
193 if (s
->from_proc_swaps
)
194 return &s
->parameters_proc_swaps
;
196 if (s
->from_fragment
)
197 return &s
->parameters_fragment
;
202 static int swap_add_device_dependencies(Swap
*s
) {
203 UnitDependencyMask mask
;
212 p
= swap_get_parameters(s
);
216 mask
= s
->from_proc_swaps
? UNIT_DEPENDENCY_PROC_SWAP
: UNIT_DEPENDENCY_FILE
;
218 if (is_device_path(p
->what
)) {
219 r
= unit_add_node_dependency(UNIT(s
), p
->what
, UNIT_REQUIRES
, mask
);
223 return unit_add_blockdev_dependency(UNIT(s
), p
->what
, mask
);
226 /* File based swap devices need to be ordered after systemd-remount-fs.service, since they might need
227 * a writable file system. */
228 return unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_REMOUNT_FS_SERVICE
, true, mask
);
231 static int swap_add_default_dependencies(Swap
*s
) {
236 if (!UNIT(s
)->default_dependencies
)
239 if (!MANAGER_IS_SYSTEM(UNIT(s
)->manager
))
242 if (detect_container() > 0)
245 /* swap units generated for the swap dev links are missing the
246 * ordering dep against the swap target. */
247 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SWAP_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
251 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_UMOUNT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
254 static int swap_verify(Swap
*s
) {
255 _cleanup_free_
char *e
= NULL
;
258 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
260 r
= unit_name_from_path(s
->what
, ".swap", &e
);
262 return log_unit_error_errno(UNIT(s
), r
, "Failed to generate unit name from path: %m");
264 if (!unit_has_name(UNIT(s
), e
))
265 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Value of What= and unit name do not match, not loading.");
267 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
)
268 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.");
273 static int swap_load_devnode(Swap
*s
) {
274 _cleanup_free_
char *p
= NULL
;
280 if (stat(s
->what
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
283 r
= devname_from_stat_rdev(&st
, &p
);
285 log_unit_full_errno(UNIT(s
), r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
286 "Failed to get device node for swap %s: %m", s
->what
);
290 return swap_set_devnode(s
, p
);
293 static int swap_add_extras(Swap
*s
) {
298 if (UNIT(s
)->fragment_path
)
299 s
->from_fragment
= true;
302 if (s
->parameters_fragment
.what
)
303 s
->what
= strdup(s
->parameters_fragment
.what
);
304 else if (s
->parameters_proc_swaps
.what
)
305 s
->what
= strdup(s
->parameters_proc_swaps
.what
);
307 r
= unit_name_to_path(UNIT(s
)->id
, &s
->what
);
316 path_simplify(s
->what
);
318 if (!UNIT(s
)->description
) {
319 r
= unit_set_description(UNIT(s
), s
->what
);
324 r
= unit_add_mounts_for(UNIT(s
), s
->what
, UNIT_DEPENDENCY_IMPLICIT
, UNIT_MOUNT_REQUIRES
);
328 r
= swap_add_device_dependencies(s
);
332 r
= swap_load_devnode(s
);
336 r
= unit_patch_contexts(UNIT(s
));
340 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
344 r
= unit_set_default_slice(UNIT(s
));
348 r
= swap_add_default_dependencies(s
);
355 static int swap_load(Unit
*u
) {
360 assert(u
->load_state
== UNIT_STUB
);
362 /* Load a .swap file */
363 bool fragment_optional
= s
->from_proc_swaps
;
364 r
= unit_load_fragment_and_dropin(u
, !fragment_optional
);
366 /* Add in some extras, and do so either when we successfully loaded something or when /proc/swaps is
368 if (u
->load_state
== UNIT_LOADED
|| s
->from_proc_swaps
)
369 q
= swap_add_extras(s
);
375 if (u
->load_state
!= UNIT_LOADED
)
378 return swap_verify(s
);
381 static int swap_setup_unit(
384 const char *what_proc_swaps
,
388 _cleanup_free_
char *e
= NULL
;
396 assert(what_proc_swaps
);
398 r
= unit_name_from_path(what
, ".swap", &e
);
400 return log_unit_error_errno(u
, r
, "Failed to generate unit name from path: %m");
402 u
= manager_get_unit(m
, e
);
404 SWAP(u
)->from_proc_swaps
&&
405 !path_equal(SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
))
406 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
407 "Swap %s appeared twice with different device paths %s and %s",
408 e
, SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
);
413 r
= unit_new_for_name(m
, sizeof(Swap
), e
, &u
);
415 log_unit_warning_errno(u
, r
, "Failed to load swap unit: %m");
419 SWAP(u
)->what
= strdup(what
);
420 if (!SWAP(u
)->what
) {
425 unit_add_to_load_queue(u
);
429 p
= &SWAP(u
)->parameters_proc_swaps
;
432 p
->what
= strdup(what_proc_swaps
);
439 /* The unit is definitely around now, mark it as loaded if it was previously referenced but could not be
440 * loaded. After all we can load it now, from the data in /proc/swaps. */
441 if (IN_SET(u
->load_state
, UNIT_NOT_FOUND
, UNIT_BAD_SETTING
, UNIT_ERROR
)) {
442 u
->load_state
= UNIT_LOADED
;
447 SWAP(u
)->is_active
= true;
448 SWAP(u
)->just_activated
= !SWAP(u
)->from_proc_swaps
;
451 SWAP(u
)->from_proc_swaps
= true;
453 p
->priority
= priority
;
454 p
->priority_set
= true;
456 unit_add_to_dbus_queue(u
);
466 static void swap_process_new(Manager
*m
, const char *device
, int prio
, bool set_flags
) {
467 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
469 struct stat st
, st_link
;
474 if (swap_setup_unit(m
, device
, device
, prio
, set_flags
) < 0)
477 /* If this is a block device, then let's add duplicates for
478 * all other names of this block device */
479 if (stat(device
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
482 r
= sd_device_new_from_stat_rdev(&d
, &st
);
484 return (void) log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
485 "Failed to allocate device for swap %s: %m", device
);
487 /* Add the main device node */
488 if (sd_device_get_devname(d
, &dn
) >= 0 && !streq(dn
, device
))
489 (void) swap_setup_unit(m
, dn
, device
, prio
, set_flags
);
491 /* Add additional units for all symlinks */
492 FOREACH_DEVICE_DEVLINK(d
, devlink
) {
494 /* Don't bother with the /dev/block links */
495 if (streq(devlink
, device
))
498 if (path_startswith(devlink
, "/dev/block/"))
501 if (stat(devlink
, &st_link
) >= 0 &&
502 (!S_ISBLK(st_link
.st_mode
) ||
503 st_link
.st_rdev
!= st
.st_rdev
))
506 (void) swap_setup_unit(m
, devlink
, device
, prio
, set_flags
);
510 static void swap_set_state(Swap
*s
, SwapState state
) {
515 if (s
->state
!= state
)
516 bus_unit_send_pending_change_signal(UNIT(s
), false);
518 old_state
= s
->state
;
521 if (!SWAP_STATE_WITH_PROCESS(state
)) {
522 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
523 swap_unwatch_control_pid(s
);
524 s
->control_command
= NULL
;
525 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
528 if (state
!= old_state
)
529 log_unit_debug(UNIT(s
), "Changed %s -> %s", swap_state_to_string(old_state
), swap_state_to_string(state
));
531 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], /* reload_success = */ true);
533 /* If there other units for the same device node have a job
534 queued it might be worth checking again if it is runnable
535 now. This is necessary, since swap_start() refuses
536 operation with EAGAIN if there's already another job for
537 the same device node queued. */
538 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
539 if (UNIT(other
)->job
)
540 job_add_to_run_queue(UNIT(other
)->job
);
543 static int swap_coldplug(Unit
*u
) {
545 SwapState new_state
= SWAP_DEAD
;
549 assert(s
->state
== SWAP_DEAD
);
551 if (s
->deserialized_state
!= s
->state
)
552 new_state
= s
->deserialized_state
;
553 else if (s
->from_proc_swaps
)
554 new_state
= SWAP_ACTIVE
;
556 if (new_state
== s
->state
)
559 if (pidref_is_set(&s
->control_pid
) &&
560 pidref_is_unwaited(&s
->control_pid
) > 0 &&
561 SWAP_STATE_WITH_PROCESS(new_state
)) {
563 r
= unit_watch_pidref(UNIT(s
), &s
->control_pid
, /* exclusive= */ false);
567 r
= swap_arm_timer(s
, /* relative= */ false, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
572 if (!IN_SET(new_state
, SWAP_DEAD
, SWAP_FAILED
))
573 (void) unit_setup_exec_runtime(u
);
575 swap_set_state(s
, new_state
);
579 static void swap_dump(Unit
*u
, FILE *f
, const char *prefix
) {
586 if (s
->from_proc_swaps
)
587 p
= &s
->parameters_proc_swaps
;
588 else if (s
->from_fragment
)
589 p
= &s
->parameters_fragment
;
596 "%sClean Result: %s\n"
598 "%sFrom /proc/swaps: %s\n"
599 "%sFrom fragment: %s\n"
601 prefix
, swap_state_to_string(s
->state
),
602 prefix
, swap_result_to_string(s
->result
),
603 prefix
, swap_result_to_string(s
->clean_result
),
605 prefix
, yes_no(s
->from_proc_swaps
),
606 prefix
, yes_no(s
->from_fragment
),
607 prefix
, yes_no(swap_is_extrinsic(u
)));
610 fprintf(f
, "%sDevice Node: %s\n", prefix
, s
->devnode
);
617 prefix
, strempty(p
->options
));
620 "%sTimeoutSec: %s\n",
621 prefix
, FORMAT_TIMESPAN(s
->timeout_usec
, USEC_PER_SEC
));
623 if (pidref_is_set(&s
->control_pid
))
625 "%sControl PID: "PID_FMT
"\n",
626 prefix
, s
->control_pid
.pid
);
628 exec_context_dump(&s
->exec_context
, f
, prefix
);
629 kill_context_dump(&s
->kill_context
, f
, prefix
);
630 cgroup_context_dump(UNIT(s
), f
, prefix
);
633 static int swap_spawn(Swap
*s
, ExecCommand
*c
, PidRef
*ret_pid
) {
635 _cleanup_(exec_params_shallow_clear
) ExecParameters exec_params
= EXEC_PARAMETERS_INIT(
636 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
);
637 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
645 r
= unit_prepare_exec(UNIT(s
));
649 r
= swap_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
653 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
657 r
= exec_spawn(UNIT(s
),
667 r
= pidref_set_pid(&pidref
, pid
);
671 r
= unit_watch_pidref(UNIT(s
), &pidref
, /* exclusive= */ true);
675 *ret_pid
= TAKE_PIDREF(pidref
);
679 static void swap_enter_dead(Swap
*s
, SwapResult f
) {
682 if (s
->result
== SWAP_SUCCESS
)
685 unit_log_result(UNIT(s
), s
->result
== SWAP_SUCCESS
, swap_result_to_string(s
->result
));
686 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
687 swap_set_state(s
, s
->result
!= SWAP_SUCCESS
? SWAP_FAILED
: SWAP_DEAD
);
689 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
691 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
693 unit_unref_uid_gid(UNIT(s
), true);
696 static void swap_enter_active(Swap
*s
, SwapResult f
) {
699 if (s
->result
== SWAP_SUCCESS
)
702 swap_set_state(s
, SWAP_ACTIVE
);
705 static void swap_enter_dead_or_active(Swap
*s
, SwapResult f
) {
708 if (s
->from_proc_swaps
) {
709 swap_enter_active(s
, f
);
711 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
712 if (UNIT(other
)->job
)
713 swap_enter_dead_or_active(other
, f
);
715 swap_enter_dead(s
, f
);
718 static int state_to_kill_operation(Swap
*s
, SwapState state
) {
719 if (state
== SWAP_DEACTIVATING_SIGTERM
) {
720 if (unit_has_job_type(UNIT(s
), JOB_RESTART
))
723 return KILL_TERMINATE
;
729 static void swap_enter_signal(Swap
*s
, SwapState state
, SwapResult f
) {
734 if (s
->result
== SWAP_SUCCESS
)
737 r
= unit_kill_context(
740 state_to_kill_operation(s
, state
),
741 /* main_pid= */ NULL
,
743 /* main_pid_alien= */ false);
745 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
750 r
= swap_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
752 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
756 swap_set_state(s
, state
);
757 } else if (state
== SWAP_DEACTIVATING_SIGTERM
&& s
->kill_context
.send_sigkill
)
758 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
760 swap_enter_dead_or_active(s
, SWAP_SUCCESS
);
765 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
768 static void swap_enter_activating(Swap
*s
) {
769 _cleanup_free_
char *opts
= NULL
;
774 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
);
776 s
->control_command_id
= SWAP_EXEC_ACTIVATE
;
777 s
->control_command
= s
->exec_command
+ SWAP_EXEC_ACTIVATE
;
779 if (s
->from_fragment
) {
782 r
= fstab_find_pri(s
->parameters_fragment
.options
, &priority
);
784 log_unit_warning_errno(UNIT(s
), r
, "Failed to parse swap priority \"%s\", ignoring: %m", s
->parameters_fragment
.options
);
785 else if (r
> 0 && s
->parameters_fragment
.priority_set
)
786 log_unit_warning(UNIT(s
), "Duplicate swap priority configuration by Priority= and Options= fields.");
788 if (r
<= 0 && s
->parameters_fragment
.priority_set
) {
789 if (s
->parameters_fragment
.options
)
790 r
= asprintf(&opts
, "%s,pri=%i", s
->parameters_fragment
.options
, s
->parameters_fragment
.priority
);
792 r
= asprintf(&opts
, "pri=%i", s
->parameters_fragment
.priority
);
800 r
= exec_command_set(s
->control_command
, "/sbin/swapon", "--fixpgsz", NULL
);
802 log_unit_warning_errno(UNIT(s
), r
, "Failed to initialize swapon command line: %m");
806 if (s
->parameters_fragment
.options
|| opts
) {
807 r
= exec_command_append(s
->control_command
, "-o",
808 opts
?: s
->parameters_fragment
.options
, NULL
);
810 log_unit_warning_errno(UNIT(s
), r
, "Failed to prepare swapon command line: %m");
815 r
= exec_command_append(s
->control_command
, s
->what
, NULL
);
817 log_unit_warning_errno(UNIT(s
), r
, "Failed to prepare swapon command line: %m");
821 swap_unwatch_control_pid(s
);
823 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
825 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'swapon' task: %m");
829 swap_set_state(s
, SWAP_ACTIVATING
);
833 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
836 static void swap_enter_deactivating(Swap
*s
) {
841 s
->control_command_id
= SWAP_EXEC_DEACTIVATE
;
842 s
->control_command
= s
->exec_command
+ SWAP_EXEC_DEACTIVATE
;
844 r
= exec_command_set(s
->control_command
,
849 log_unit_warning_errno(UNIT(s
), r
, "Failed to prepare swapoff command line: %m");
853 swap_unwatch_control_pid(s
);
855 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
857 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'swapoff' task: %m");
861 swap_set_state(s
, SWAP_DEACTIVATING
);
865 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
868 static void swap_cycle_clear(Swap
*s
) {
871 s
->result
= SWAP_SUCCESS
;
872 exec_command_reset_status_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
873 UNIT(s
)->reset_accounting
= true;
876 static int swap_start(Unit
*u
) {
882 /* We cannot fulfill this request right now, try again later please! */
885 SWAP_DEACTIVATING_SIGTERM
,
886 SWAP_DEACTIVATING_SIGKILL
,
891 if (s
->state
== SWAP_ACTIVATING
)
894 assert(IN_SET(s
->state
, SWAP_DEAD
, SWAP_FAILED
));
896 if (detect_container() > 0)
899 /* If there's a job for another swap unit for the same node
900 * running, then let's not dispatch this one for now, and wait
901 * until that other job has finished. */
902 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
903 if (UNIT(other
)->job
&& UNIT(other
)->job
->state
== JOB_RUNNING
)
906 r
= unit_acquire_invocation_id(u
);
911 swap_enter_activating(s
);
915 static int swap_stop(Unit
*u
) {
922 case SWAP_DEACTIVATING
:
923 case SWAP_DEACTIVATING_SIGTERM
:
924 case SWAP_DEACTIVATING_SIGKILL
:
928 case SWAP_ACTIVATING
:
929 case SWAP_ACTIVATING_DONE
:
930 /* There's a control process pending, directly enter kill mode */
931 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_SUCCESS
);
935 if (detect_container() > 0)
938 swap_enter_deactivating(s
);
942 /* If we are currently cleaning, then abort it, brutally. */
943 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
947 assert_not_reached();
951 static int swap_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
958 (void) serialize_item(f
, "state", swap_state_to_string(s
->state
));
959 (void) serialize_item(f
, "result", swap_result_to_string(s
->result
));
960 (void) serialize_pidref(f
, fds
, "control-pid", &s
->control_pid
);
962 if (s
->control_command_id
>= 0)
963 (void) serialize_item(f
, "control-command", swap_exec_command_to_string(s
->control_command_id
));
968 static int swap_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
974 if (streq(key
, "state")) {
977 state
= swap_state_from_string(value
);
979 log_unit_debug(u
, "Failed to parse state value: %s", value
);
981 s
->deserialized_state
= state
;
982 } else if (streq(key
, "result")) {
985 f
= swap_result_from_string(value
);
987 log_unit_debug(u
, "Failed to parse result value: %s", value
);
988 else if (f
!= SWAP_SUCCESS
)
990 } else if (streq(key
, "control-pid")) {
992 pidref_done(&s
->control_pid
);
993 (void) deserialize_pidref(fds
, value
, &s
->control_pid
);
995 } else if (streq(key
, "control-command")) {
998 id
= swap_exec_command_from_string(value
);
1000 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
1002 s
->control_command_id
= id
;
1003 s
->control_command
= s
->exec_command
+ id
;
1006 log_unit_debug(u
, "Unknown serialization key: %s", key
);
1011 static void swap_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
1018 if (pid
!= s
->control_pid
.pid
)
1021 /* Let's scan /proc/swaps before we process SIGCHLD. For the reasoning see the similar code in
1023 (void) swap_process_proc_swaps(u
->manager
);
1025 pidref_done(&s
->control_pid
);
1027 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
1029 else if (code
== CLD_EXITED
)
1030 f
= SWAP_FAILURE_EXIT_CODE
;
1031 else if (code
== CLD_KILLED
)
1032 f
= SWAP_FAILURE_SIGNAL
;
1033 else if (code
== CLD_DUMPED
)
1034 f
= SWAP_FAILURE_CORE_DUMP
;
1036 assert_not_reached();
1038 if (s
->result
== SWAP_SUCCESS
)
1041 if (s
->control_command
) {
1042 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
1044 s
->control_command
= NULL
;
1045 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1048 unit_log_process_exit(
1051 swap_exec_command_to_string(s
->control_command_id
),
1057 case SWAP_ACTIVATING
:
1058 case SWAP_ACTIVATING_DONE
:
1060 if (f
== SWAP_SUCCESS
|| s
->from_proc_swaps
)
1061 swap_enter_active(s
, f
);
1063 swap_enter_dead(s
, f
);
1066 case SWAP_DEACTIVATING
:
1067 case SWAP_DEACTIVATING_SIGKILL
:
1068 case SWAP_DEACTIVATING_SIGTERM
:
1070 swap_enter_dead_or_active(s
, f
);
1074 if (s
->clean_result
== SWAP_SUCCESS
)
1075 s
->clean_result
= f
;
1077 swap_enter_dead(s
, SWAP_SUCCESS
);
1081 assert_not_reached();
1084 /* Notify clients about changed exit status */
1085 unit_add_to_dbus_queue(u
);
1088 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
1089 Swap
*s
= SWAP(userdata
);
1092 assert(s
->timer_event_source
== source
);
1096 case SWAP_ACTIVATING
:
1097 case SWAP_ACTIVATING_DONE
:
1098 log_unit_warning(UNIT(s
), "Activation timed out. Stopping.");
1099 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1102 case SWAP_DEACTIVATING
:
1103 log_unit_warning(UNIT(s
), "Deactivation timed out. Stopping.");
1104 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1107 case SWAP_DEACTIVATING_SIGTERM
:
1108 if (s
->kill_context
.send_sigkill
) {
1109 log_unit_warning(UNIT(s
), "Swap process timed out. Killing.");
1110 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_FAILURE_TIMEOUT
);
1112 log_unit_warning(UNIT(s
), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1113 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1117 case SWAP_DEACTIVATING_SIGKILL
:
1118 log_unit_warning(UNIT(s
), "Swap process still around after SIGKILL. Ignoring.");
1119 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1123 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
1125 if (s
->clean_result
== SWAP_SUCCESS
)
1126 s
->clean_result
= SWAP_FAILURE_TIMEOUT
;
1128 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, 0);
1132 assert_not_reached();
1138 static int swap_load_proc_swaps(Manager
*m
, bool set_flags
) {
1141 rewind(m
->proc_swaps
);
1143 (void) fscanf(m
->proc_swaps
, "%*s %*s %*s %*s %*s\n");
1145 for (unsigned i
= 1;; i
++) {
1146 _cleanup_free_
char *dev
= NULL
, *d
= NULL
;
1149 k
= fscanf(m
->proc_swaps
,
1150 "%ms " /* device/file */
1151 "%*s " /* type of swap */
1152 "%*s " /* swap size */
1154 "%i\n", /* priority */
1160 log_warning("Failed to parse /proc/swaps:%u, skipping.", i
);
1164 ssize_t l
= cunescape(dev
, UNESCAPE_RELAX
, &d
);
1166 return log_error_errno(l
, "Failed to unescape device path: %m");
1168 device_found_node(m
, d
, DEVICE_FOUND_SWAP
, DEVICE_FOUND_SWAP
);
1170 (void) swap_process_new(m
, d
, prio
, set_flags
);
1176 static int swap_process_proc_swaps(Manager
*m
) {
1181 r
= swap_load_proc_swaps(m
, true);
1183 /* Reset flags, just in case, for late calls */
1184 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1185 Swap
*swap
= SWAP(u
);
1189 swap
->is_active
= swap
->just_activated
= false;
1195 manager_dispatch_load_queue(m
);
1197 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1198 Swap
*swap
= SWAP(u
);
1202 if (!swap
->is_active
) {
1204 swap_unset_proc_swaps(swap
);
1206 switch (swap
->state
) {
1209 /* This has just been deactivated */
1210 swap_enter_dead(swap
, SWAP_SUCCESS
);
1215 swap_set_state(swap
, swap
->state
);
1220 device_found_node(m
, swap
->what
, DEVICE_NOT_FOUND
, DEVICE_FOUND_SWAP
);
1222 } else if (swap
->just_activated
) {
1224 /* New swap entry */
1226 switch (swap
->state
) {
1230 (void) unit_acquire_invocation_id(u
);
1231 swap_cycle_clear(swap
);
1232 swap_enter_active(swap
, SWAP_SUCCESS
);
1235 case SWAP_ACTIVATING
:
1236 swap_set_state(swap
, SWAP_ACTIVATING_DONE
);
1240 /* Nothing really changed, but let's
1241 * issue an notification call
1242 * nonetheless, in case somebody is
1243 * waiting for this. */
1244 swap_set_state(swap
, swap
->state
);
1249 /* Reset the flags for later calls */
1250 swap
->is_active
= swap
->just_activated
= false;
1256 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
1257 Manager
*m
= ASSERT_PTR(userdata
);
1259 assert(revents
& EPOLLPRI
);
1261 return swap_process_proc_swaps(m
);
1264 static Unit
*swap_following(Unit
*u
) {
1270 /* If the user configured the swap through /etc/fstab or
1271 * a device unit, follow that. */
1273 if (s
->from_fragment
)
1276 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
1277 if (other
->from_fragment
)
1280 /* Otherwise, make everybody follow the unit that's named after
1281 * the swap device in the kernel */
1283 if (streq_ptr(s
->what
, s
->devnode
))
1286 LIST_FOREACH(same_devnode
, other
, s
->same_devnode_next
)
1287 if (streq_ptr(other
->what
, other
->devnode
))
1290 LIST_FOREACH_BACKWARDS(same_devnode
, other
, s
->same_devnode_prev
) {
1291 if (streq_ptr(other
->what
, other
->devnode
))
1297 /* Fall back to the first on the list */
1301 static int swap_following_set(Unit
*u
, Set
**_set
) {
1303 _cleanup_set_free_ Set
*set
= NULL
;
1309 if (LIST_JUST_US(same_devnode
, s
)) {
1314 set
= set_new(NULL
);
1318 LIST_FOREACH_OTHERS(same_devnode
, other
, s
) {
1319 r
= set_put(set
, other
);
1324 *_set
= TAKE_PTR(set
);
1328 static void swap_shutdown(Manager
*m
) {
1331 m
->swap_event_source
= sd_event_source_disable_unref(m
->swap_event_source
);
1332 m
->proc_swaps
= safe_fclose(m
->proc_swaps
);
1333 m
->swaps_by_devnode
= hashmap_free(m
->swaps_by_devnode
);
1336 static void swap_enumerate(Manager
*m
) {
1341 if (!m
->proc_swaps
) {
1342 m
->proc_swaps
= fopen("/proc/swaps", "re");
1343 if (!m
->proc_swaps
) {
1344 if (errno
== ENOENT
)
1345 log_debug_errno(errno
, "Not swap enabled, skipping enumeration.");
1347 log_warning_errno(errno
, "Failed to open /proc/swaps, ignoring: %m");
1352 r
= sd_event_add_io(m
->event
, &m
->swap_event_source
, fileno(m
->proc_swaps
), EPOLLPRI
, swap_dispatch_io
, m
);
1354 log_error_errno(r
, "Failed to watch /proc/swaps: %m");
1358 /* Dispatch this before we dispatch SIGCHLD, so that
1359 * we always get the events from /proc/swaps before
1360 * the SIGCHLD of /sbin/swapon. */
1361 r
= sd_event_source_set_priority(m
->swap_event_source
, SD_EVENT_PRIORITY_NORMAL
-10);
1363 log_error_errno(r
, "Failed to change /proc/swaps priority: %m");
1367 (void) sd_event_source_set_description(m
->swap_event_source
, "swap-proc");
1370 r
= swap_load_proc_swaps(m
, false);
1380 int swap_process_device_new(Manager
*m
, sd_device
*dev
) {
1381 _cleanup_free_
char *e
= NULL
;
1389 if (sd_device_get_devname(dev
, &dn
) < 0)
1392 r
= unit_name_from_path(dn
, ".swap", &e
);
1394 log_debug_errno(r
, "Cannot convert device name '%s' to unit name, ignoring: %m", dn
);
1398 u
= manager_get_unit(m
, e
);
1400 r
= swap_set_devnode(SWAP(u
), dn
);
1402 FOREACH_DEVICE_DEVLINK(dev
, devlink
) {
1403 _cleanup_free_
char *n
= NULL
;
1406 q
= unit_name_from_path(devlink
, ".swap", &n
);
1407 if (q
== -EINVAL
) /* If the name is not convertible to unit name, we can't manage it */
1412 u
= manager_get_unit(m
, n
);
1414 q
= swap_set_devnode(SWAP(u
), dn
);
1423 int swap_process_device_remove(Manager
*m
, sd_device
*dev
) {
1428 r
= sd_device_get_devname(dev
, &dn
);
1432 while ((s
= hashmap_get(m
->swaps_by_devnode
, dn
))) {
1435 q
= swap_set_devnode(s
, NULL
);
1443 static void swap_reset_failed(Unit
*u
) {
1448 if (s
->state
== SWAP_FAILED
)
1449 swap_set_state(s
, SWAP_DEAD
);
1451 s
->result
= SWAP_SUCCESS
;
1452 s
->clean_result
= SWAP_SUCCESS
;
1455 static int swap_get_timeout(Unit
*u
, usec_t
*timeout
) {
1463 if (!s
->timer_event_source
)
1466 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
1469 if (t
== USEC_INFINITY
)
1476 static bool swap_supported(void) {
1477 static int supported
= -1;
1479 /* If swap support is not available in the kernel, or we are
1480 * running in a container we don't support swap units, and any
1481 * attempts to starting one should fail immediately. */
1485 access("/proc/swaps", F_OK
) >= 0 &&
1486 detect_container() <= 0;
1491 static PidRef
* swap_control_pid(Unit
*u
) {
1492 return &ASSERT_PTR(SWAP(u
))->control_pid
;
1495 static int swap_clean(Unit
*u
, ExecCleanMask mask
) {
1496 _cleanup_strv_free_
char **l
= NULL
;
1503 if (s
->state
!= SWAP_DEAD
)
1506 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
1510 if (strv_isempty(l
))
1513 swap_unwatch_control_pid(s
);
1514 s
->clean_result
= SWAP_SUCCESS
;
1515 s
->control_command
= NULL
;
1516 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1518 r
= swap_arm_timer(s
, /* relative= */ true, s
->exec_context
.timeout_clean_usec
);
1520 log_unit_warning_errno(u
, r
, "Failed to install timer: %m");
1524 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
1526 log_unit_warning_errno(u
, r
, "Failed to spawn cleaning task: %m");
1530 swap_set_state(s
, SWAP_CLEANING
);
1534 s
->clean_result
= SWAP_FAILURE_RESOURCES
;
1535 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1539 static int swap_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
1544 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
1547 static int swap_can_start(Unit
*u
) {
1553 r
= unit_test_start_limit(u
);
1555 swap_enter_dead(s
, SWAP_FAILURE_START_LIMIT_HIT
);
1562 int swap_get_priority(const Swap
*s
) {
1565 if (s
->from_proc_swaps
&& s
->parameters_proc_swaps
.priority_set
)
1566 return s
->parameters_proc_swaps
.priority
;
1568 if (s
->from_fragment
&& s
->parameters_fragment
.priority_set
)
1569 return s
->parameters_fragment
.priority
;
1574 const char* swap_get_options(const Swap
*s
) {
1577 if (s
->from_fragment
)
1578 return s
->parameters_fragment
.options
;
1583 static const char* const swap_exec_command_table
[_SWAP_EXEC_COMMAND_MAX
] = {
1584 [SWAP_EXEC_ACTIVATE
] = "ExecActivate",
1585 [SWAP_EXEC_DEACTIVATE
] = "ExecDeactivate",
1588 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command
, SwapExecCommand
);
1590 static const char* const swap_result_table
[_SWAP_RESULT_MAX
] = {
1591 [SWAP_SUCCESS
] = "success",
1592 [SWAP_FAILURE_RESOURCES
] = "resources",
1593 [SWAP_FAILURE_TIMEOUT
] = "timeout",
1594 [SWAP_FAILURE_EXIT_CODE
] = "exit-code",
1595 [SWAP_FAILURE_SIGNAL
] = "signal",
1596 [SWAP_FAILURE_CORE_DUMP
] = "core-dump",
1597 [SWAP_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
1600 DEFINE_STRING_TABLE_LOOKUP(swap_result
, SwapResult
);
1602 const UnitVTable swap_vtable
= {
1603 .object_size
= sizeof(Swap
),
1604 .exec_context_offset
= offsetof(Swap
, exec_context
),
1605 .cgroup_context_offset
= offsetof(Swap
, cgroup_context
),
1606 .kill_context_offset
= offsetof(Swap
, kill_context
),
1607 .exec_runtime_offset
= offsetof(Swap
, exec_runtime
),
1613 .private_section
= "Swap",
1621 .coldplug
= swap_coldplug
,
1625 .start
= swap_start
,
1628 .clean
= swap_clean
,
1629 .can_clean
= swap_can_clean
,
1631 .get_timeout
= swap_get_timeout
,
1633 .serialize
= swap_serialize
,
1634 .deserialize_item
= swap_deserialize_item
,
1636 .active_state
= swap_active_state
,
1637 .sub_state_to_string
= swap_sub_state_to_string
,
1639 .will_restart
= unit_will_restart_default
,
1641 .may_gc
= swap_may_gc
,
1642 .is_extrinsic
= swap_is_extrinsic
,
1644 .sigchld_event
= swap_sigchld_event
,
1646 .reset_failed
= swap_reset_failed
,
1648 .control_pid
= swap_control_pid
,
1650 .bus_set_property
= bus_swap_set_property
,
1651 .bus_commit_properties
= bus_swap_commit_properties
,
1653 .following
= swap_following
,
1654 .following_set
= swap_following_set
,
1656 .enumerate
= swap_enumerate
,
1657 .shutdown
= swap_shutdown
,
1658 .supported
= swap_supported
,
1660 .status_message_formats
= {
1661 .starting_stopping
= {
1662 [0] = "Activating swap %s...",
1663 [1] = "Deactivating swap %s...",
1665 .finished_start_job
= {
1666 [JOB_DONE
] = "Activated swap %s.",
1667 [JOB_FAILED
] = "Failed to activate swap %s.",
1668 [JOB_TIMEOUT
] = "Timed out activating swap %s.",
1670 .finished_stop_job
= {
1671 [JOB_DONE
] = "Deactivated swap %s.",
1672 [JOB_FAILED
] = "Failed deactivating swap %s.",
1673 [JOB_TIMEOUT
] = "Timed out deactivating swap %s.",
1677 .can_start
= swap_can_start
,
1679 .notify_plymouth
= true,