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
->default_timeout_start_usec
;
144 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
145 s
->exec_context
.std_error
= u
->manager
->default_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_pid(UNIT(s
), s
->control_pid
.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
, usec_t usec
) {
189 if (s
->timer_event_source
) {
190 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
194 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
197 if (usec
== USEC_INFINITY
)
200 r
= sd_event_add_time(
201 UNIT(s
)->manager
->event
,
202 &s
->timer_event_source
,
205 swap_dispatch_timer
, s
);
209 (void) sd_event_source_set_description(s
->timer_event_source
, "swap-timer");
214 static SwapParameters
* swap_get_parameters(Swap
*s
) {
217 if (s
->from_proc_swaps
)
218 return &s
->parameters_proc_swaps
;
220 if (s
->from_fragment
)
221 return &s
->parameters_fragment
;
226 static int swap_add_device_dependencies(Swap
*s
) {
227 UnitDependencyMask mask
;
236 p
= swap_get_parameters(s
);
240 mask
= s
->from_proc_swaps
? UNIT_DEPENDENCY_PROC_SWAP
: UNIT_DEPENDENCY_FILE
;
242 if (is_device_path(p
->what
)) {
243 r
= unit_add_node_dependency(UNIT(s
), p
->what
, UNIT_REQUIRES
, mask
);
247 return unit_add_blockdev_dependency(UNIT(s
), p
->what
, mask
);
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
);
255 static int swap_add_default_dependencies(Swap
*s
) {
260 if (!UNIT(s
)->default_dependencies
)
263 if (!MANAGER_IS_SYSTEM(UNIT(s
)->manager
))
266 if (detect_container() > 0)
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
);
275 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_UMOUNT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
278 static int swap_verify(Swap
*s
) {
279 _cleanup_free_
char *e
= NULL
;
282 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
284 r
= unit_name_from_path(s
->what
, ".swap", &e
);
286 return log_unit_error_errno(UNIT(s
), r
, "Failed to generate unit name from path: %m");
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.");
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.");
297 static int swap_load_devnode(Swap
*s
) {
298 _cleanup_free_
char *p
= NULL
;
304 if (stat(s
->what
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
307 r
= devname_from_stat_rdev(&st
, &p
);
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
);
314 return swap_set_devnode(s
, p
);
317 static int swap_add_extras(Swap
*s
) {
322 if (UNIT(s
)->fragment_path
)
323 s
->from_fragment
= true;
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
);
331 r
= unit_name_to_path(UNIT(s
)->id
, &s
->what
);
340 path_simplify(s
->what
);
342 if (!UNIT(s
)->description
) {
343 r
= unit_set_description(UNIT(s
), s
->what
);
348 r
= unit_require_mounts_for(UNIT(s
), s
->what
, UNIT_DEPENDENCY_IMPLICIT
);
352 r
= swap_add_device_dependencies(s
);
356 r
= swap_load_devnode(s
);
360 r
= unit_patch_contexts(UNIT(s
));
364 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
368 r
= unit_set_default_slice(UNIT(s
));
372 r
= swap_add_default_dependencies(s
);
379 static int swap_load(Unit
*u
) {
384 assert(u
->load_state
== UNIT_STUB
);
386 /* Load a .swap file */
387 bool fragment_optional
= s
->from_proc_swaps
;
388 r
= unit_load_fragment_and_dropin(u
, !fragment_optional
);
390 /* Add in some extras, and do so either when we successfully loaded something or when /proc/swaps is
392 if (u
->load_state
== UNIT_LOADED
|| s
->from_proc_swaps
)
393 q
= swap_add_extras(s
);
399 if (u
->load_state
!= UNIT_LOADED
)
402 return swap_verify(s
);
405 static int swap_setup_unit(
408 const char *what_proc_swaps
,
412 _cleanup_free_
char *e
= NULL
;
420 assert(what_proc_swaps
);
422 r
= unit_name_from_path(what
, ".swap", &e
);
424 return log_unit_error_errno(u
, r
, "Failed to generate unit name from path: %m");
426 u
= manager_get_unit(m
, e
);
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
);
437 r
= unit_new_for_name(m
, sizeof(Swap
), e
, &u
);
441 SWAP(u
)->what
= strdup(what
);
442 if (!SWAP(u
)->what
) {
447 unit_add_to_load_queue(u
);
451 p
= &SWAP(u
)->parameters_proc_swaps
;
454 p
->what
= strdup(what_proc_swaps
);
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
;
469 SWAP(u
)->is_active
= true;
470 SWAP(u
)->just_activated
= !SWAP(u
)->from_proc_swaps
;
473 SWAP(u
)->from_proc_swaps
= true;
475 p
->priority
= priority
;
476 p
->priority_set
= true;
478 unit_add_to_dbus_queue(u
);
482 log_unit_warning_errno(u
, r
, "Failed to load swap unit: %m");
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
;
493 struct stat st
, st_link
;
498 if (swap_setup_unit(m
, device
, device
, prio
, set_flags
) < 0)
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
))
506 r
= sd_device_new_from_stat_rdev(&d
, &st
);
508 return (void) log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
509 "Failed to allocate device for swap %s: %m", device
);
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
);
515 /* Add additional units for all symlinks */
516 FOREACH_DEVICE_DEVLINK(d
, devlink
) {
518 /* Don't bother with the /dev/block links */
519 if (streq(devlink
, device
))
522 if (path_startswith(devlink
, "/dev/block/"))
525 if (stat(devlink
, &st_link
) >= 0 &&
526 (!S_ISBLK(st_link
.st_mode
) ||
527 st_link
.st_rdev
!= st
.st_rdev
))
530 (void) swap_setup_unit(m
, devlink
, device
, prio
, set_flags
);
534 static void swap_set_state(Swap
*s
, SwapState state
) {
539 if (s
->state
!= state
)
540 bus_unit_send_pending_change_signal(UNIT(s
), false);
542 old_state
= s
->state
;
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
;
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
));
555 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], /* reload_success = */ true);
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
);
567 static int swap_coldplug(Unit
*u
) {
569 SwapState new_state
= SWAP_DEAD
;
573 assert(s
->state
== SWAP_DEAD
);
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
;
580 if (new_state
== s
->state
)
583 if (pidref_is_set(&s
->control_pid
) &&
584 pid_is_unwaited(s
->control_pid
.pid
) &&
585 SWAP_STATE_WITH_PROCESS(new_state
)) {
587 r
= unit_watch_pid(UNIT(s
), s
->control_pid
.pid
, /* exclusive= */ false);
591 r
= swap_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
596 if (!IN_SET(new_state
, SWAP_DEAD
, SWAP_FAILED
))
597 (void) unit_setup_exec_runtime(u
);
599 swap_set_state(s
, new_state
);
603 static void swap_dump(Unit
*u
, FILE *f
, const char *prefix
) {
610 if (s
->from_proc_swaps
)
611 p
= &s
->parameters_proc_swaps
;
612 else if (s
->from_fragment
)
613 p
= &s
->parameters_fragment
;
620 "%sClean Result: %s\n"
622 "%sFrom /proc/swaps: %s\n"
623 "%sFrom fragment: %s\n"
625 prefix
, swap_state_to_string(s
->state
),
626 prefix
, swap_result_to_string(s
->result
),
627 prefix
, swap_result_to_string(s
->clean_result
),
629 prefix
, yes_no(s
->from_proc_swaps
),
630 prefix
, yes_no(s
->from_fragment
),
631 prefix
, yes_no(swap_is_extrinsic(u
)));
634 fprintf(f
, "%sDevice Node: %s\n", prefix
, s
->devnode
);
641 prefix
, strempty(p
->options
));
644 "%sTimeoutSec: %s\n",
645 prefix
, FORMAT_TIMESPAN(s
->timeout_usec
, USEC_PER_SEC
));
647 if (pidref_is_set(&s
->control_pid
))
649 "%sControl PID: "PID_FMT
"\n",
650 prefix
, s
->control_pid
.pid
);
652 exec_context_dump(&s
->exec_context
, f
, prefix
);
653 kill_context_dump(&s
->kill_context
, f
, prefix
);
654 cgroup_context_dump(UNIT(s
), f
, prefix
);
657 static int swap_spawn(Swap
*s
, ExecCommand
*c
, PidRef
*ret_pid
) {
659 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
660 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
666 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
674 r
= unit_prepare_exec(UNIT(s
));
678 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
682 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
686 r
= exec_spawn(UNIT(s
),
696 r
= pidref_set_pid(&pidref
, pid
);
700 r
= unit_watch_pid(UNIT(s
), pidref
.pid
, /* exclusive= */ true);
704 *ret_pid
= TAKE_PIDREF(pidref
);
708 static void swap_enter_dead(Swap
*s
, SwapResult f
) {
711 if (s
->result
== SWAP_SUCCESS
)
714 unit_log_result(UNIT(s
), s
->result
== SWAP_SUCCESS
, swap_result_to_string(s
->result
));
715 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
716 swap_set_state(s
, s
->result
!= SWAP_SUCCESS
? SWAP_FAILED
: SWAP_DEAD
);
718 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
720 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
722 unit_unref_uid_gid(UNIT(s
), true);
725 static void swap_enter_active(Swap
*s
, SwapResult f
) {
728 if (s
->result
== SWAP_SUCCESS
)
731 swap_set_state(s
, SWAP_ACTIVE
);
734 static void swap_enter_dead_or_active(Swap
*s
, SwapResult f
) {
737 if (s
->from_proc_swaps
) {
738 swap_enter_active(s
, f
);
740 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
741 if (UNIT(other
)->job
)
742 swap_enter_dead_or_active(other
, f
);
744 swap_enter_dead(s
, f
);
747 static int state_to_kill_operation(Swap
*s
, SwapState state
) {
748 if (state
== SWAP_DEACTIVATING_SIGTERM
) {
749 if (unit_has_job_type(UNIT(s
), JOB_RESTART
))
752 return KILL_TERMINATE
;
758 static void swap_enter_signal(Swap
*s
, SwapState state
, SwapResult f
) {
763 if (s
->result
== SWAP_SUCCESS
)
766 r
= unit_kill_context(UNIT(s
),
768 state_to_kill_operation(s
, state
),
776 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
780 swap_set_state(s
, state
);
781 } else if (state
== SWAP_DEACTIVATING_SIGTERM
&& s
->kill_context
.send_sigkill
)
782 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
784 swap_enter_dead_or_active(s
, SWAP_SUCCESS
);
789 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
790 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
793 static void swap_enter_activating(Swap
*s
) {
794 _cleanup_free_
char *opts
= NULL
;
799 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
);
801 s
->control_command_id
= SWAP_EXEC_ACTIVATE
;
802 s
->control_command
= s
->exec_command
+ SWAP_EXEC_ACTIVATE
;
804 if (s
->from_fragment
) {
807 r
= fstab_find_pri(s
->parameters_fragment
.options
, &priority
);
809 log_unit_warning_errno(UNIT(s
), r
, "Failed to parse swap priority \"%s\", ignoring: %m", s
->parameters_fragment
.options
);
810 else if (r
> 0 && s
->parameters_fragment
.priority_set
)
811 log_unit_warning(UNIT(s
), "Duplicate swap priority configuration by Priority= and Options= fields.");
813 if (r
<= 0 && s
->parameters_fragment
.priority_set
) {
814 if (s
->parameters_fragment
.options
)
815 r
= asprintf(&opts
, "%s,pri=%i", s
->parameters_fragment
.options
, s
->parameters_fragment
.priority
);
817 r
= asprintf(&opts
, "pri=%i", s
->parameters_fragment
.priority
);
825 r
= exec_command_set(s
->control_command
, "/sbin/swapon", "--fixpgsz", NULL
);
829 if (s
->parameters_fragment
.options
|| opts
) {
830 r
= exec_command_append(s
->control_command
, "-o",
831 opts
?: s
->parameters_fragment
.options
, NULL
);
836 r
= exec_command_append(s
->control_command
, s
->what
, NULL
);
840 swap_unwatch_control_pid(s
);
842 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
846 swap_set_state(s
, SWAP_ACTIVATING
);
850 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapon' task: %m");
851 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
854 static void swap_enter_deactivating(Swap
*s
) {
859 s
->control_command_id
= SWAP_EXEC_DEACTIVATE
;
860 s
->control_command
= s
->exec_command
+ SWAP_EXEC_DEACTIVATE
;
862 r
= exec_command_set(s
->control_command
,
869 swap_unwatch_control_pid(s
);
871 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
875 swap_set_state(s
, SWAP_DEACTIVATING
);
880 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapoff' task: %m");
881 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
884 static void swap_cycle_clear(Swap
*s
) {
887 s
->result
= SWAP_SUCCESS
;
888 exec_command_reset_status_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
889 UNIT(s
)->reset_accounting
= true;
892 static int swap_start(Unit
*u
) {
898 /* We cannot fulfill this request right now, try again later please! */
901 SWAP_DEACTIVATING_SIGTERM
,
902 SWAP_DEACTIVATING_SIGKILL
,
907 if (s
->state
== SWAP_ACTIVATING
)
910 assert(IN_SET(s
->state
, SWAP_DEAD
, SWAP_FAILED
));
912 if (detect_container() > 0)
915 /* If there's a job for another swap unit for the same node
916 * running, then let's not dispatch this one for now, and wait
917 * until that other job has finished. */
918 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
919 if (UNIT(other
)->job
&& UNIT(other
)->job
->state
== JOB_RUNNING
)
922 r
= unit_acquire_invocation_id(u
);
927 swap_enter_activating(s
);
931 static int swap_stop(Unit
*u
) {
938 case SWAP_DEACTIVATING
:
939 case SWAP_DEACTIVATING_SIGTERM
:
940 case SWAP_DEACTIVATING_SIGKILL
:
944 case SWAP_ACTIVATING
:
945 case SWAP_ACTIVATING_DONE
:
946 /* There's a control process pending, directly enter kill mode */
947 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_SUCCESS
);
951 if (detect_container() > 0)
954 swap_enter_deactivating(s
);
958 /* If we are currently cleaning, then abort it, brutally. */
959 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
963 assert_not_reached();
967 static int swap_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
974 (void) serialize_item(f
, "state", swap_state_to_string(s
->state
));
975 (void) serialize_item(f
, "result", swap_result_to_string(s
->result
));
977 if (pidref_is_set(&s
->control_pid
))
978 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
.pid
);
980 if (s
->control_command_id
>= 0)
981 (void) serialize_item(f
, "control-command", swap_exec_command_to_string(s
->control_command_id
));
986 static int swap_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
993 if (streq(key
, "state")) {
996 state
= swap_state_from_string(value
);
998 log_unit_debug(u
, "Failed to parse state value: %s", value
);
1000 s
->deserialized_state
= state
;
1001 } else if (streq(key
, "result")) {
1004 f
= swap_result_from_string(value
);
1006 log_unit_debug(u
, "Failed to parse result value: %s", value
);
1007 else if (f
!= SWAP_SUCCESS
)
1009 } else if (streq(key
, "control-pid")) {
1011 pidref_done(&s
->control_pid
);
1012 r
= pidref_set_pidstr(&s
->control_pid
, value
);
1014 log_debug_errno(r
, "Failed to pin control PID '%s', ignoring: %m", value
);
1016 } else if (streq(key
, "control-command")) {
1019 id
= swap_exec_command_from_string(value
);
1021 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
1023 s
->control_command_id
= id
;
1024 s
->control_command
= s
->exec_command
+ id
;
1027 log_unit_debug(u
, "Unknown serialization key: %s", key
);
1032 static void swap_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
1039 if (pid
!= s
->control_pid
.pid
)
1042 /* Let's scan /proc/swaps before we process SIGCHLD. For the reasoning see the similar code in
1044 (void) swap_process_proc_swaps(u
->manager
);
1046 pidref_done(&s
->control_pid
);
1048 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
1050 else if (code
== CLD_EXITED
)
1051 f
= SWAP_FAILURE_EXIT_CODE
;
1052 else if (code
== CLD_KILLED
)
1053 f
= SWAP_FAILURE_SIGNAL
;
1054 else if (code
== CLD_DUMPED
)
1055 f
= SWAP_FAILURE_CORE_DUMP
;
1057 assert_not_reached();
1059 if (s
->result
== SWAP_SUCCESS
)
1062 if (s
->control_command
) {
1063 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
1065 s
->control_command
= NULL
;
1066 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1069 unit_log_process_exit(
1072 swap_exec_command_to_string(s
->control_command_id
),
1078 case SWAP_ACTIVATING
:
1079 case SWAP_ACTIVATING_DONE
:
1081 if (f
== SWAP_SUCCESS
|| s
->from_proc_swaps
)
1082 swap_enter_active(s
, f
);
1084 swap_enter_dead(s
, f
);
1087 case SWAP_DEACTIVATING
:
1088 case SWAP_DEACTIVATING_SIGKILL
:
1089 case SWAP_DEACTIVATING_SIGTERM
:
1091 swap_enter_dead_or_active(s
, f
);
1095 if (s
->clean_result
== SWAP_SUCCESS
)
1096 s
->clean_result
= f
;
1098 swap_enter_dead(s
, SWAP_SUCCESS
);
1102 assert_not_reached();
1105 /* Notify clients about changed exit status */
1106 unit_add_to_dbus_queue(u
);
1109 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
1110 Swap
*s
= SWAP(userdata
);
1113 assert(s
->timer_event_source
== source
);
1117 case SWAP_ACTIVATING
:
1118 case SWAP_ACTIVATING_DONE
:
1119 log_unit_warning(UNIT(s
), "Activation timed out. Stopping.");
1120 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1123 case SWAP_DEACTIVATING
:
1124 log_unit_warning(UNIT(s
), "Deactivation timed out. Stopping.");
1125 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1128 case SWAP_DEACTIVATING_SIGTERM
:
1129 if (s
->kill_context
.send_sigkill
) {
1130 log_unit_warning(UNIT(s
), "Swap process timed out. Killing.");
1131 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_FAILURE_TIMEOUT
);
1133 log_unit_warning(UNIT(s
), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1134 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1138 case SWAP_DEACTIVATING_SIGKILL
:
1139 log_unit_warning(UNIT(s
), "Swap process still around after SIGKILL. Ignoring.");
1140 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1144 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
1146 if (s
->clean_result
== SWAP_SUCCESS
)
1147 s
->clean_result
= SWAP_FAILURE_TIMEOUT
;
1149 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, 0);
1153 assert_not_reached();
1159 static int swap_load_proc_swaps(Manager
*m
, bool set_flags
) {
1162 rewind(m
->proc_swaps
);
1164 (void) fscanf(m
->proc_swaps
, "%*s %*s %*s %*s %*s\n");
1166 for (unsigned i
= 1;; i
++) {
1167 _cleanup_free_
char *dev
= NULL
, *d
= NULL
;
1170 k
= fscanf(m
->proc_swaps
,
1171 "%ms " /* device/file */
1172 "%*s " /* type of swap */
1173 "%*s " /* swap size */
1175 "%i\n", /* priority */
1181 log_warning("Failed to parse /proc/swaps:%u.", i
);
1185 ssize_t l
= cunescape(dev
, UNESCAPE_RELAX
, &d
);
1187 return log_error_errno(l
, "Failed to unescape device path: %m");
1189 device_found_node(m
, d
, DEVICE_FOUND_SWAP
, DEVICE_FOUND_SWAP
);
1191 (void) swap_process_new(m
, d
, prio
, set_flags
);
1197 static int swap_process_proc_swaps(Manager
*m
) {
1202 r
= swap_load_proc_swaps(m
, true);
1204 log_error_errno(r
, "Failed to reread /proc/swaps: %m");
1206 /* Reset flags, just in case, for late calls */
1207 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1208 Swap
*swap
= SWAP(u
);
1212 swap
->is_active
= swap
->just_activated
= false;
1218 manager_dispatch_load_queue(m
);
1220 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1221 Swap
*swap
= SWAP(u
);
1225 if (!swap
->is_active
) {
1227 swap_unset_proc_swaps(swap
);
1229 switch (swap
->state
) {
1232 /* This has just been deactivated */
1233 swap_enter_dead(swap
, SWAP_SUCCESS
);
1238 swap_set_state(swap
, swap
->state
);
1243 device_found_node(m
, swap
->what
, DEVICE_NOT_FOUND
, DEVICE_FOUND_SWAP
);
1245 } else if (swap
->just_activated
) {
1247 /* New swap entry */
1249 switch (swap
->state
) {
1253 (void) unit_acquire_invocation_id(u
);
1254 swap_cycle_clear(swap
);
1255 swap_enter_active(swap
, SWAP_SUCCESS
);
1258 case SWAP_ACTIVATING
:
1259 swap_set_state(swap
, SWAP_ACTIVATING_DONE
);
1263 /* Nothing really changed, but let's
1264 * issue an notification call
1265 * nonetheless, in case somebody is
1266 * waiting for this. */
1267 swap_set_state(swap
, swap
->state
);
1272 /* Reset the flags for later calls */
1273 swap
->is_active
= swap
->just_activated
= false;
1279 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
1280 Manager
*m
= ASSERT_PTR(userdata
);
1282 assert(revents
& EPOLLPRI
);
1284 return swap_process_proc_swaps(m
);
1287 static Unit
*swap_following(Unit
*u
) {
1293 /* If the user configured the swap through /etc/fstab or
1294 * a device unit, follow that. */
1296 if (s
->from_fragment
)
1299 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
1300 if (other
->from_fragment
)
1303 /* Otherwise, make everybody follow the unit that's named after
1304 * the swap device in the kernel */
1306 if (streq_ptr(s
->what
, s
->devnode
))
1309 LIST_FOREACH(same_devnode
, other
, s
->same_devnode_next
)
1310 if (streq_ptr(other
->what
, other
->devnode
))
1313 LIST_FOREACH_BACKWARDS(same_devnode
, other
, s
->same_devnode_prev
) {
1314 if (streq_ptr(other
->what
, other
->devnode
))
1320 /* Fall back to the first on the list */
1324 static int swap_following_set(Unit
*u
, Set
**_set
) {
1326 _cleanup_set_free_ Set
*set
= NULL
;
1332 if (LIST_JUST_US(same_devnode
, s
)) {
1337 set
= set_new(NULL
);
1341 LIST_FOREACH_OTHERS(same_devnode
, other
, s
) {
1342 r
= set_put(set
, other
);
1347 *_set
= TAKE_PTR(set
);
1351 static void swap_shutdown(Manager
*m
) {
1354 m
->swap_event_source
= sd_event_source_disable_unref(m
->swap_event_source
);
1355 m
->proc_swaps
= safe_fclose(m
->proc_swaps
);
1356 m
->swaps_by_devnode
= hashmap_free(m
->swaps_by_devnode
);
1359 static void swap_enumerate(Manager
*m
) {
1364 if (!m
->proc_swaps
) {
1365 m
->proc_swaps
= fopen("/proc/swaps", "re");
1366 if (!m
->proc_swaps
) {
1367 if (errno
== ENOENT
)
1368 log_debug_errno(errno
, "Not swap enabled, skipping enumeration.");
1370 log_warning_errno(errno
, "Failed to open /proc/swaps, ignoring: %m");
1375 r
= sd_event_add_io(m
->event
, &m
->swap_event_source
, fileno(m
->proc_swaps
), EPOLLPRI
, swap_dispatch_io
, m
);
1377 log_error_errno(r
, "Failed to watch /proc/swaps: %m");
1381 /* Dispatch this before we dispatch SIGCHLD, so that
1382 * we always get the events from /proc/swaps before
1383 * the SIGCHLD of /sbin/swapon. */
1384 r
= sd_event_source_set_priority(m
->swap_event_source
, SD_EVENT_PRIORITY_NORMAL
-10);
1386 log_error_errno(r
, "Failed to change /proc/swaps priority: %m");
1390 (void) sd_event_source_set_description(m
->swap_event_source
, "swap-proc");
1393 r
= swap_load_proc_swaps(m
, false);
1403 int swap_process_device_new(Manager
*m
, sd_device
*dev
) {
1404 _cleanup_free_
char *e
= NULL
;
1412 if (sd_device_get_devname(dev
, &dn
) < 0)
1415 r
= unit_name_from_path(dn
, ".swap", &e
);
1417 log_debug_errno(r
, "Cannot convert device name '%s' to unit name, ignoring: %m", dn
);
1421 u
= manager_get_unit(m
, e
);
1423 r
= swap_set_devnode(SWAP(u
), dn
);
1425 FOREACH_DEVICE_DEVLINK(dev
, devlink
) {
1426 _cleanup_free_
char *n
= NULL
;
1429 q
= unit_name_from_path(devlink
, ".swap", &n
);
1430 if (q
== -EINVAL
) /* If the name is not convertible to unit name, we can't manage it */
1435 u
= manager_get_unit(m
, n
);
1437 q
= swap_set_devnode(SWAP(u
), dn
);
1446 int swap_process_device_remove(Manager
*m
, sd_device
*dev
) {
1451 r
= sd_device_get_devname(dev
, &dn
);
1455 while ((s
= hashmap_get(m
->swaps_by_devnode
, dn
))) {
1458 q
= swap_set_devnode(s
, NULL
);
1466 static void swap_reset_failed(Unit
*u
) {
1471 if (s
->state
== SWAP_FAILED
)
1472 swap_set_state(s
, SWAP_DEAD
);
1474 s
->result
= SWAP_SUCCESS
;
1475 s
->clean_result
= SWAP_SUCCESS
;
1478 static int swap_kill(Unit
*u
, KillWho who
, int signo
, int code
, int value
, sd_bus_error
*error
) {
1479 return unit_kill_common(u
, who
, signo
, code
, value
, -1, SWAP(u
)->control_pid
.pid
, error
);
1482 static int swap_get_timeout(Unit
*u
, usec_t
*timeout
) {
1490 if (!s
->timer_event_source
)
1493 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
1496 if (t
== USEC_INFINITY
)
1503 static bool swap_supported(void) {
1504 static int supported
= -1;
1506 /* If swap support is not available in the kernel, or we are
1507 * running in a container we don't support swap units, and any
1508 * attempts to starting one should fail immediately. */
1512 access("/proc/swaps", F_OK
) >= 0 &&
1513 detect_container() <= 0;
1518 static int swap_control_pid(Unit
*u
) {
1523 return s
->control_pid
.pid
;
1526 static int swap_clean(Unit
*u
, ExecCleanMask mask
) {
1527 _cleanup_strv_free_
char **l
= NULL
;
1535 if (s
->state
!= SWAP_DEAD
)
1538 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
1542 if (strv_isempty(l
))
1545 swap_unwatch_control_pid(s
);
1546 s
->clean_result
= SWAP_SUCCESS
;
1547 s
->control_command
= NULL
;
1548 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1550 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->exec_context
.timeout_clean_usec
));
1554 r
= unit_fork_and_watch_rm_rf(u
, l
, &pid
);
1558 r
= pidref_set_pid(&s
->control_pid
, pid
);
1562 swap_set_state(s
, SWAP_CLEANING
);
1566 log_unit_warning_errno(u
, r
, "Failed to initiate cleaning: %m");
1567 s
->clean_result
= SWAP_FAILURE_RESOURCES
;
1568 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1572 static int swap_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
1577 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
1580 static int swap_can_start(Unit
*u
) {
1586 r
= unit_test_start_limit(u
);
1588 swap_enter_dead(s
, SWAP_FAILURE_START_LIMIT_HIT
);
1595 static const char* const swap_exec_command_table
[_SWAP_EXEC_COMMAND_MAX
] = {
1596 [SWAP_EXEC_ACTIVATE
] = "ExecActivate",
1597 [SWAP_EXEC_DEACTIVATE
] = "ExecDeactivate",
1600 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command
, SwapExecCommand
);
1602 static const char* const swap_result_table
[_SWAP_RESULT_MAX
] = {
1603 [SWAP_SUCCESS
] = "success",
1604 [SWAP_FAILURE_RESOURCES
] = "resources",
1605 [SWAP_FAILURE_TIMEOUT
] = "timeout",
1606 [SWAP_FAILURE_EXIT_CODE
] = "exit-code",
1607 [SWAP_FAILURE_SIGNAL
] = "signal",
1608 [SWAP_FAILURE_CORE_DUMP
] = "core-dump",
1609 [SWAP_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
1612 DEFINE_STRING_TABLE_LOOKUP(swap_result
, SwapResult
);
1614 const UnitVTable swap_vtable
= {
1615 .object_size
= sizeof(Swap
),
1616 .exec_context_offset
= offsetof(Swap
, exec_context
),
1617 .cgroup_context_offset
= offsetof(Swap
, cgroup_context
),
1618 .kill_context_offset
= offsetof(Swap
, kill_context
),
1619 .exec_runtime_offset
= offsetof(Swap
, exec_runtime
),
1625 .private_section
= "Swap",
1633 .coldplug
= swap_coldplug
,
1637 .start
= swap_start
,
1641 .clean
= swap_clean
,
1642 .can_clean
= swap_can_clean
,
1644 .get_timeout
= swap_get_timeout
,
1646 .serialize
= swap_serialize
,
1647 .deserialize_item
= swap_deserialize_item
,
1649 .active_state
= swap_active_state
,
1650 .sub_state_to_string
= swap_sub_state_to_string
,
1652 .will_restart
= unit_will_restart_default
,
1654 .may_gc
= swap_may_gc
,
1655 .is_extrinsic
= swap_is_extrinsic
,
1657 .sigchld_event
= swap_sigchld_event
,
1659 .reset_failed
= swap_reset_failed
,
1661 .control_pid
= swap_control_pid
,
1663 .bus_set_property
= bus_swap_set_property
,
1664 .bus_commit_properties
= bus_swap_commit_properties
,
1666 .following
= swap_following
,
1667 .following_set
= swap_following_set
,
1669 .enumerate
= swap_enumerate
,
1670 .shutdown
= swap_shutdown
,
1671 .supported
= swap_supported
,
1673 .status_message_formats
= {
1674 .starting_stopping
= {
1675 [0] = "Activating swap %s...",
1676 [1] = "Deactivating swap %s...",
1678 .finished_start_job
= {
1679 [JOB_DONE
] = "Activated swap %s.",
1680 [JOB_FAILED
] = "Failed to activate swap %s.",
1681 [JOB_TIMEOUT
] = "Timed out activating swap %s.",
1683 .finished_stop_job
= {
1684 [JOB_DONE
] = "Deactivated swap %s.",
1685 [JOB_FAILED
] = "Failed deactivating swap %s.",
1686 [JOB_TIMEOUT
] = "Timed out deactivating swap %s.",
1690 .can_start
= swap_can_start
,
1692 .notify_plymouth
= true,