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
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
);
57 static void swap_unset_proc_swaps(Swap
*s
) {
60 if (!s
->from_proc_swaps
)
63 s
->parameters_proc_swaps
.what
= mfree(s
->parameters_proc_swaps
.what
);
65 s
->from_proc_swaps
= false;
68 static int swap_set_devnode(Swap
*s
, const char *devnode
) {
75 r
= hashmap_ensure_allocated(&UNIT(s
)->manager
->swaps_by_devnode
, &path_hash_ops
);
79 swaps
= UNIT(s
)->manager
->swaps_by_devnode
;
82 first
= hashmap_get(swaps
, s
->devnode
);
84 LIST_REMOVE(same_devnode
, first
, s
);
86 hashmap_replace(swaps
, first
->devnode
, first
);
88 hashmap_remove(swaps
, s
->devnode
);
90 s
->devnode
= mfree(s
->devnode
);
94 s
->devnode
= strdup(devnode
);
98 first
= hashmap_get(swaps
, s
->devnode
);
99 LIST_PREPEND(same_devnode
, first
, s
);
101 return hashmap_replace(swaps
, first
->devnode
, first
);
107 static void swap_init(Unit
*u
) {
111 assert(UNIT(s
)->load_state
== UNIT_STUB
);
113 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
115 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
116 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
118 s
->parameters_proc_swaps
.priority
= s
->parameters_fragment
.priority
= -1;
120 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
122 u
->ignore_on_isolate
= true;
125 static void swap_unwatch_control_pid(Swap
*s
) {
128 if (s
->control_pid
<= 0)
131 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
135 static void swap_done(Unit
*u
) {
140 swap_unset_proc_swaps(s
);
141 swap_set_devnode(s
, NULL
);
143 s
->what
= mfree(s
->what
);
144 s
->parameters_fragment
.what
= mfree(s
->parameters_fragment
.what
);
145 s
->parameters_fragment
.options
= mfree(s
->parameters_fragment
.options
);
147 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
148 exec_command_done_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
149 s
->control_command
= NULL
;
151 dynamic_creds_unref(&s
->dynamic_creds
);
153 swap_unwatch_control_pid(s
);
155 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
158 static int swap_arm_timer(Swap
*s
, usec_t usec
) {
163 if (s
->timer_event_source
) {
164 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
168 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
171 if (usec
== USEC_INFINITY
)
174 r
= sd_event_add_time(
175 UNIT(s
)->manager
->event
,
176 &s
->timer_event_source
,
179 swap_dispatch_timer
, s
);
183 (void) sd_event_source_set_description(s
->timer_event_source
, "swap-timer");
188 static int swap_add_device_dependencies(Swap
*s
) {
194 if (!s
->from_fragment
)
197 if (is_device_path(s
->what
))
198 return unit_add_node_dependency(UNIT(s
), s
->what
, MANAGER_IS_SYSTEM(UNIT(s
)->manager
), UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
200 /* File based swap devices need to be ordered after
201 * systemd-remount-fs.service, since they might need a
202 * writable file system. */
203 return unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_REMOUNT_FS_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
206 static int swap_add_default_dependencies(Swap
*s
) {
211 if (!UNIT(s
)->default_dependencies
)
214 if (!MANAGER_IS_SYSTEM(UNIT(s
)->manager
))
217 if (detect_container() > 0)
220 /* swap units generated for the swap dev links are missing the
221 * ordering dep against the swap target. */
222 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SWAP_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
226 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_UMOUNT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
229 static int swap_verify(Swap
*s
) {
230 _cleanup_free_
char *e
= NULL
;
233 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
236 r
= unit_name_from_path(s
->what
, ".swap", &e
);
238 return log_unit_error_errno(UNIT(s
), r
, "Failed to generate unit name from path: %m");
240 if (!unit_has_name(UNIT(s
), e
)) {
241 log_unit_error(UNIT(s
), "Value of What= and unit name do not match, not loading.");
245 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
246 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.");
253 static int swap_load_devnode(Swap
*s
) {
254 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
261 if (stat(s
->what
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
264 r
= device_new_from_stat_rdev(&d
, &st
);
266 log_unit_full(UNIT(s
), r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
267 "Failed to allocate device for swap %s: %m", s
->what
);
271 if (sd_device_get_devname(d
, &p
) < 0)
274 return swap_set_devnode(s
, p
);
277 static int swap_add_extras(Swap
*s
) {
282 if (UNIT(s
)->fragment_path
)
283 s
->from_fragment
= true;
286 if (s
->parameters_fragment
.what
)
287 s
->what
= strdup(s
->parameters_fragment
.what
);
288 else if (s
->parameters_proc_swaps
.what
)
289 s
->what
= strdup(s
->parameters_proc_swaps
.what
);
291 r
= unit_name_to_path(UNIT(s
)->id
, &s
->what
);
300 path_simplify(s
->what
, false);
302 if (!UNIT(s
)->description
) {
303 r
= unit_set_description(UNIT(s
), s
->what
);
308 r
= unit_require_mounts_for(UNIT(s
), s
->what
, UNIT_DEPENDENCY_IMPLICIT
);
312 r
= swap_add_device_dependencies(s
);
316 r
= swap_load_devnode(s
);
320 r
= unit_patch_contexts(UNIT(s
));
324 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
328 r
= unit_set_default_slice(UNIT(s
));
332 r
= swap_add_default_dependencies(s
);
339 static int swap_load(Unit
*u
) {
344 assert(u
->load_state
== UNIT_STUB
);
346 /* Load a .swap file */
347 if (SWAP(u
)->from_proc_swaps
)
348 r
= unit_load_fragment_and_dropin_optional(u
);
350 r
= unit_load_fragment_and_dropin(u
);
352 /* Add in some extras, and do so either when we successfully loaded something or when /proc/swaps is already
354 if (u
->load_state
== UNIT_LOADED
|| s
->from_proc_swaps
)
355 q
= swap_add_extras(s
);
364 return swap_verify(s
);
367 static int swap_setup_unit(
370 const char *what_proc_swaps
,
374 _cleanup_free_
char *e
= NULL
;
382 assert(what_proc_swaps
);
384 r
= unit_name_from_path(what
, ".swap", &e
);
386 return log_unit_error_errno(u
, r
, "Failed to generate unit name from path: %m");
388 u
= manager_get_unit(m
, e
);
390 SWAP(u
)->from_proc_swaps
&&
391 !path_equal(SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
))
392 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
393 "Swap %s appeared twice with different device paths %s and %s",
394 e
, SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
);
399 r
= unit_new_for_name(m
, sizeof(Swap
), e
, &u
);
403 SWAP(u
)->what
= strdup(what
);
404 if (!SWAP(u
)->what
) {
409 unit_add_to_load_queue(u
);
413 p
= &SWAP(u
)->parameters_proc_swaps
;
416 p
->what
= strdup(what_proc_swaps
);
423 /* The unit is definitely around now, mark it as loaded if it was previously referenced but could not be
424 * loaded. After all we can load it now, from the data in /proc/swaps. */
425 if (IN_SET(u
->load_state
, UNIT_NOT_FOUND
, UNIT_BAD_SETTING
, UNIT_ERROR
)) {
426 u
->load_state
= UNIT_LOADED
;
431 SWAP(u
)->is_active
= true;
432 SWAP(u
)->just_activated
= !SWAP(u
)->from_proc_swaps
;
435 SWAP(u
)->from_proc_swaps
= true;
437 p
->priority
= priority
;
439 unit_add_to_dbus_queue(u
);
443 log_unit_warning_errno(u
, r
, "Failed to load swap unit: %m");
451 static int swap_process_new(Manager
*m
, const char *device
, int prio
, bool set_flags
) {
452 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
453 const char *dn
, *devlink
;
454 struct stat st
, st_link
;
459 r
= swap_setup_unit(m
, device
, device
, prio
, set_flags
);
463 /* If this is a block device, then let's add duplicates for
464 * all other names of this block device */
465 if (stat(device
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
468 r
= device_new_from_stat_rdev(&d
, &st
);
470 log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
471 "Failed to allocate device for swap %s: %m", device
);
475 /* Add the main device node */
476 if (sd_device_get_devname(d
, &dn
) >= 0 && !streq(dn
, device
))
477 swap_setup_unit(m
, dn
, device
, prio
, set_flags
);
479 /* Add additional units for all symlinks */
480 FOREACH_DEVICE_DEVLINK(d
, devlink
) {
482 /* Don't bother with the /dev/block links */
483 if (streq(devlink
, device
))
486 if (path_startswith(devlink
, "/dev/block/"))
489 if (stat(devlink
, &st_link
) >= 0 &&
490 (!S_ISBLK(st_link
.st_mode
) ||
491 st_link
.st_rdev
!= st
.st_rdev
))
494 swap_setup_unit(m
, devlink
, device
, prio
, set_flags
);
500 static void swap_set_state(Swap
*s
, SwapState state
) {
506 if (s
->state
!= state
)
507 bus_unit_send_pending_change_signal(UNIT(s
), false);
509 old_state
= s
->state
;
512 if (!SWAP_STATE_WITH_PROCESS(state
)) {
513 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
514 swap_unwatch_control_pid(s
);
515 s
->control_command
= NULL
;
516 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
519 if (state
!= old_state
)
520 log_unit_debug(UNIT(s
), "Changed %s -> %s", swap_state_to_string(old_state
), swap_state_to_string(state
));
522 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
524 /* If there other units for the same device node have a job
525 queued it might be worth checking again if it is runnable
526 now. This is necessary, since swap_start() refuses
527 operation with EAGAIN if there's already another job for
528 the same device node queued. */
529 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
530 if (UNIT(other
)->job
)
531 job_add_to_run_queue(UNIT(other
)->job
);
534 static int swap_coldplug(Unit
*u
) {
536 SwapState new_state
= SWAP_DEAD
;
540 assert(s
->state
== SWAP_DEAD
);
542 if (s
->deserialized_state
!= s
->state
)
543 new_state
= s
->deserialized_state
;
544 else if (s
->from_proc_swaps
)
545 new_state
= SWAP_ACTIVE
;
547 if (new_state
== s
->state
)
550 if (s
->control_pid
> 0 &&
551 pid_is_unwaited(s
->control_pid
) &&
552 SWAP_STATE_WITH_PROCESS(new_state
)) {
554 r
= unit_watch_pid(UNIT(s
), s
->control_pid
, false);
558 r
= swap_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
563 if (!IN_SET(new_state
, SWAP_DEAD
, SWAP_FAILED
)) {
564 (void) unit_setup_dynamic_creds(u
);
565 (void) unit_setup_exec_runtime(u
);
568 swap_set_state(s
, new_state
);
572 static void swap_dump(Unit
*u
, FILE *f
, const char *prefix
) {
573 char buf
[FORMAT_TIMESPAN_MAX
];
580 if (s
->from_proc_swaps
)
581 p
= &s
->parameters_proc_swaps
;
582 else if (s
->from_fragment
)
583 p
= &s
->parameters_fragment
;
591 "%sFrom /proc/swaps: %s\n"
592 "%sFrom fragment: %s\n",
593 prefix
, swap_state_to_string(s
->state
),
594 prefix
, swap_result_to_string(s
->result
),
596 prefix
, yes_no(s
->from_proc_swaps
),
597 prefix
, yes_no(s
->from_fragment
));
600 fprintf(f
, "%sDevice Node: %s\n", prefix
, s
->devnode
);
607 prefix
, strempty(p
->options
));
610 "%sTimeoutSec: %s\n",
611 prefix
, format_timespan(buf
, sizeof(buf
), s
->timeout_usec
, USEC_PER_SEC
));
613 if (s
->control_pid
> 0)
615 "%sControl PID: "PID_FMT
"\n",
616 prefix
, s
->control_pid
);
618 exec_context_dump(&s
->exec_context
, f
, prefix
);
619 kill_context_dump(&s
->kill_context
, f
, prefix
);
620 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
623 static int swap_spawn(Swap
*s
, ExecCommand
*c
, pid_t
*_pid
) {
625 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
626 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
639 r
= unit_prepare_exec(UNIT(s
));
643 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
647 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
651 r
= exec_spawn(UNIT(s
),
661 r
= unit_watch_pid(UNIT(s
), pid
, true);
670 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
675 static void swap_enter_dead(Swap
*s
, SwapResult f
) {
678 if (s
->result
== SWAP_SUCCESS
)
681 unit_log_result(UNIT(s
), s
->result
== SWAP_SUCCESS
, swap_result_to_string(s
->result
));
682 swap_set_state(s
, s
->result
!= SWAP_SUCCESS
? SWAP_FAILED
: SWAP_DEAD
);
684 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
686 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
688 unit_unref_uid_gid(UNIT(s
), true);
690 dynamic_creds_destroy(&s
->dynamic_creds
);
693 static void swap_enter_active(Swap
*s
, SwapResult f
) {
696 if (s
->result
== SWAP_SUCCESS
)
699 swap_set_state(s
, SWAP_ACTIVE
);
702 static void swap_enter_dead_or_active(Swap
*s
, SwapResult f
) {
705 if (s
->from_proc_swaps
)
706 swap_enter_active(s
, f
);
708 swap_enter_dead(s
, f
);
711 static void swap_enter_signal(Swap
*s
, SwapState state
, SwapResult f
) {
717 if (s
->result
== SWAP_SUCCESS
)
720 if (state
== SWAP_DEACTIVATING_SIGTERM
)
721 kop
= KILL_TERMINATE
;
725 r
= unit_kill_context(UNIT(s
), &s
->kill_context
, kop
, -1, s
->control_pid
, false);
730 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
734 swap_set_state(s
, state
);
735 } else if (state
== SWAP_DEACTIVATING_SIGTERM
&& s
->kill_context
.send_sigkill
)
736 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
738 swap_enter_dead_or_active(s
, SWAP_SUCCESS
);
743 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
744 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
747 static void swap_enter_activating(Swap
*s
) {
748 _cleanup_free_
char *opts
= NULL
;
753 unit_warn_leftover_processes(UNIT(s
));
755 s
->control_command_id
= SWAP_EXEC_ACTIVATE
;
756 s
->control_command
= s
->exec_command
+ SWAP_EXEC_ACTIVATE
;
758 if (s
->from_fragment
) {
761 r
= fstab_find_pri(s
->parameters_fragment
.options
, &priority
);
763 log_warning_errno(r
, "Failed to parse swap priority \"%s\", ignoring: %m", s
->parameters_fragment
.options
);
764 else if (r
== 1 && s
->parameters_fragment
.priority
>= 0)
765 log_warning("Duplicate swap priority configuration by Priority and Options fields.");
767 if (r
<= 0 && s
->parameters_fragment
.priority
>= 0) {
768 if (s
->parameters_fragment
.options
)
769 r
= asprintf(&opts
, "%s,pri=%i", s
->parameters_fragment
.options
, s
->parameters_fragment
.priority
);
771 r
= asprintf(&opts
, "pri=%i", s
->parameters_fragment
.priority
);
777 r
= exec_command_set(s
->control_command
, "/sbin/swapon", NULL
);
781 if (s
->parameters_fragment
.options
|| opts
) {
782 r
= exec_command_append(s
->control_command
, "-o",
783 opts
? : s
->parameters_fragment
.options
, NULL
);
788 r
= exec_command_append(s
->control_command
, s
->what
, NULL
);
792 swap_unwatch_control_pid(s
);
794 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
798 swap_set_state(s
, SWAP_ACTIVATING
);
803 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapon' task: %m");
804 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
807 static void swap_enter_deactivating(Swap
*s
) {
812 s
->control_command_id
= SWAP_EXEC_DEACTIVATE
;
813 s
->control_command
= s
->exec_command
+ SWAP_EXEC_DEACTIVATE
;
815 r
= exec_command_set(s
->control_command
,
822 swap_unwatch_control_pid(s
);
824 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
828 swap_set_state(s
, SWAP_DEACTIVATING
);
833 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapoff' task: %m");
834 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
837 static void swap_cycle_clear(Swap
*s
) {
840 s
->result
= SWAP_SUCCESS
;
841 exec_command_reset_status_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
842 UNIT(s
)->reset_accounting
= true;
845 static int swap_start(Unit
*u
) {
846 Swap
*s
= SWAP(u
), *other
;
851 /* We cannot fulfill this request right now, try again later please! */
854 SWAP_DEACTIVATING_SIGTERM
,
855 SWAP_DEACTIVATING_SIGKILL
))
859 if (s
->state
== SWAP_ACTIVATING
)
862 assert(IN_SET(s
->state
, SWAP_DEAD
, SWAP_FAILED
));
864 if (detect_container() > 0)
867 /* If there's a job for another swap unit for the same node
868 * running, then let's not dispatch this one for now, and wait
869 * until that other job has finished. */
870 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
871 if (UNIT(other
)->job
&& UNIT(other
)->job
->state
== JOB_RUNNING
)
874 r
= unit_test_start_limit(u
);
876 swap_enter_dead(s
, SWAP_FAILURE_START_LIMIT_HIT
);
880 r
= unit_acquire_invocation_id(u
);
885 swap_enter_activating(s
);
889 static int swap_stop(Unit
*u
) {
896 case SWAP_DEACTIVATING
:
897 case SWAP_DEACTIVATING_SIGTERM
:
898 case SWAP_DEACTIVATING_SIGKILL
:
902 case SWAP_ACTIVATING
:
903 case SWAP_ACTIVATING_DONE
:
904 /* There's a control process pending, directly enter kill mode */
905 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_SUCCESS
);
909 if (detect_container() > 0)
912 swap_enter_deactivating(s
);
916 assert_not_reached("Unexpected state.");
920 static int swap_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
927 (void) serialize_item(f
, "state", swap_state_to_string(s
->state
));
928 (void) serialize_item(f
, "result", swap_result_to_string(s
->result
));
930 if (s
->control_pid
> 0)
931 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
);
933 if (s
->control_command_id
>= 0)
934 (void) serialize_item(f
, "control-command", swap_exec_command_to_string(s
->control_command_id
));
939 static int swap_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
945 if (streq(key
, "state")) {
948 state
= swap_state_from_string(value
);
950 log_unit_debug(u
, "Failed to parse state value: %s", value
);
952 s
->deserialized_state
= state
;
953 } else if (streq(key
, "result")) {
956 f
= swap_result_from_string(value
);
958 log_unit_debug(u
, "Failed to parse result value: %s", value
);
959 else if (f
!= SWAP_SUCCESS
)
961 } else if (streq(key
, "control-pid")) {
964 if (parse_pid(value
, &pid
) < 0)
965 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
967 s
->control_pid
= pid
;
969 } else if (streq(key
, "control-command")) {
972 id
= swap_exec_command_from_string(value
);
974 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
976 s
->control_command_id
= id
;
977 s
->control_command
= s
->exec_command
+ id
;
980 log_unit_debug(u
, "Unknown serialization key: %s", key
);
985 _pure_
static UnitActiveState
swap_active_state(Unit
*u
) {
988 return state_translation_table
[SWAP(u
)->state
];
991 _pure_
static const char *swap_sub_state_to_string(Unit
*u
) {
994 return swap_state_to_string(SWAP(u
)->state
);
997 _pure_
static bool swap_may_gc(Unit
*u
) {
1002 if (s
->from_proc_swaps
)
1008 static void swap_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
1015 if (pid
!= s
->control_pid
)
1018 /* Let's scan /proc/swaps before we process SIGCHLD. For the reasoning see the similar code in
1020 (void) swap_process_proc_swaps(u
->manager
);
1024 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
1026 else if (code
== CLD_EXITED
)
1027 f
= SWAP_FAILURE_EXIT_CODE
;
1028 else if (code
== CLD_KILLED
)
1029 f
= SWAP_FAILURE_SIGNAL
;
1030 else if (code
== CLD_DUMPED
)
1031 f
= SWAP_FAILURE_CORE_DUMP
;
1033 assert_not_reached("Unknown code");
1035 if (s
->result
== SWAP_SUCCESS
)
1038 if (s
->control_command
) {
1039 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
1041 s
->control_command
= NULL
;
1042 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1045 unit_log_process_exit(
1046 u
, f
== SWAP_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
,
1048 swap_exec_command_to_string(s
->control_command_id
),
1053 case SWAP_ACTIVATING
:
1054 case SWAP_ACTIVATING_DONE
:
1056 if (f
== SWAP_SUCCESS
|| s
->from_proc_swaps
)
1057 swap_enter_active(s
, f
);
1059 swap_enter_dead(s
, f
);
1062 case SWAP_DEACTIVATING
:
1063 case SWAP_DEACTIVATING_SIGKILL
:
1064 case SWAP_DEACTIVATING_SIGTERM
:
1066 swap_enter_dead_or_active(s
, f
);
1070 assert_not_reached("Uh, control process died at wrong time.");
1073 /* Notify clients about changed exit status */
1074 unit_add_to_dbus_queue(u
);
1077 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
1078 Swap
*s
= SWAP(userdata
);
1081 assert(s
->timer_event_source
== source
);
1085 case SWAP_ACTIVATING
:
1086 case SWAP_ACTIVATING_DONE
:
1087 log_unit_warning(UNIT(s
), "Activation timed out. Stopping.");
1088 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1091 case SWAP_DEACTIVATING
:
1092 log_unit_warning(UNIT(s
), "Deactivation timed out. Stopping.");
1093 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1096 case SWAP_DEACTIVATING_SIGTERM
:
1097 if (s
->kill_context
.send_sigkill
) {
1098 log_unit_warning(UNIT(s
), "Swap process timed out. Killing.");
1099 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_FAILURE_TIMEOUT
);
1101 log_unit_warning(UNIT(s
), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1102 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1106 case SWAP_DEACTIVATING_SIGKILL
:
1107 log_unit_warning(UNIT(s
), "Swap process still around after SIGKILL. Ignoring.");
1108 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1112 assert_not_reached("Timeout at wrong time.");
1118 static int swap_load_proc_swaps(Manager
*m
, bool set_flags
) {
1123 rewind(m
->proc_swaps
);
1125 (void) fscanf(m
->proc_swaps
, "%*s %*s %*s %*s %*s\n");
1128 _cleanup_free_
char *dev
= NULL
, *d
= NULL
;
1131 k
= fscanf(m
->proc_swaps
,
1132 "%ms " /* device/file */
1133 "%*s " /* type of swap */
1134 "%*s " /* swap size */
1136 "%i\n", /* priority */
1142 log_warning("Failed to parse /proc/swaps:%u.", i
);
1146 if (cunescape(dev
, UNESCAPE_RELAX
, &d
) < 0)
1149 device_found_node(m
, d
, DEVICE_FOUND_SWAP
, DEVICE_FOUND_SWAP
);
1151 (void) swap_process_new(m
, d
, prio
, set_flags
);
1157 static int swap_process_proc_swaps(Manager
*m
) {
1163 r
= swap_load_proc_swaps(m
, true);
1165 log_error_errno(r
, "Failed to reread /proc/swaps: %m");
1167 /* Reset flags, just in case, for late calls */
1168 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1169 Swap
*swap
= SWAP(u
);
1171 swap
->is_active
= swap
->just_activated
= false;
1177 manager_dispatch_load_queue(m
);
1179 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1180 Swap
*swap
= SWAP(u
);
1182 if (!swap
->is_active
) {
1184 swap_unset_proc_swaps(swap
);
1186 switch (swap
->state
) {
1189 /* This has just been deactivated */
1190 swap_enter_dead(swap
, SWAP_SUCCESS
);
1195 swap_set_state(swap
, swap
->state
);
1200 device_found_node(m
, swap
->what
, 0, DEVICE_FOUND_SWAP
);
1202 } else if (swap
->just_activated
) {
1204 /* New swap entry */
1206 switch (swap
->state
) {
1210 (void) unit_acquire_invocation_id(u
);
1211 swap_cycle_clear(swap
);
1212 swap_enter_active(swap
, SWAP_SUCCESS
);
1215 case SWAP_ACTIVATING
:
1216 swap_set_state(swap
, SWAP_ACTIVATING_DONE
);
1220 /* Nothing really changed, but let's
1221 * issue an notification call
1222 * nonetheless, in case somebody is
1223 * waiting for this. */
1224 swap_set_state(swap
, swap
->state
);
1229 /* Reset the flags for later calls */
1230 swap
->is_active
= swap
->just_activated
= false;
1236 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
1237 Manager
*m
= userdata
;
1240 assert(revents
& EPOLLPRI
);
1242 return swap_process_proc_swaps(m
);
1245 static Unit
*swap_following(Unit
*u
) {
1247 Swap
*other
, *first
= NULL
;
1251 /* If the user configured the swap through /etc/fstab or
1252 * a device unit, follow that. */
1254 if (s
->from_fragment
)
1257 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
1258 if (other
->from_fragment
)
1261 /* Otherwise, make everybody follow the unit that's named after
1262 * the swap device in the kernel */
1264 if (streq_ptr(s
->what
, s
->devnode
))
1267 LIST_FOREACH_AFTER(same_devnode
, other
, s
)
1268 if (streq_ptr(other
->what
, other
->devnode
))
1271 LIST_FOREACH_BEFORE(same_devnode
, other
, s
) {
1272 if (streq_ptr(other
->what
, other
->devnode
))
1278 /* Fall back to the first on the list */
1282 static int swap_following_set(Unit
*u
, Set
**_set
) {
1283 Swap
*s
= SWAP(u
), *other
;
1284 _cleanup_set_free_ Set
*set
= NULL
;
1290 if (LIST_JUST_US(same_devnode
, s
)) {
1295 set
= set_new(NULL
);
1299 LIST_FOREACH_OTHERS(same_devnode
, other
, s
) {
1300 r
= set_put(set
, other
);
1305 *_set
= TAKE_PTR(set
);
1309 static void swap_shutdown(Manager
*m
) {
1312 m
->swap_event_source
= sd_event_source_unref(m
->swap_event_source
);
1313 m
->proc_swaps
= safe_fclose(m
->proc_swaps
);
1314 m
->swaps_by_devnode
= hashmap_free(m
->swaps_by_devnode
);
1317 static void swap_enumerate(Manager
*m
) {
1322 if (!m
->proc_swaps
) {
1323 m
->proc_swaps
= fopen("/proc/swaps", "re");
1324 if (!m
->proc_swaps
) {
1325 if (errno
== ENOENT
)
1326 log_debug_errno(errno
, "Not swap enabled, skipping enumeration.");
1328 log_warning_errno(errno
, "Failed to open /proc/swaps, ignoring: %m");
1333 r
= sd_event_add_io(m
->event
, &m
->swap_event_source
, fileno(m
->proc_swaps
), EPOLLPRI
, swap_dispatch_io
, m
);
1335 log_error_errno(r
, "Failed to watch /proc/swaps: %m");
1339 /* Dispatch this before we dispatch SIGCHLD, so that
1340 * we always get the events from /proc/swaps before
1341 * the SIGCHLD of /sbin/swapon. */
1342 r
= sd_event_source_set_priority(m
->swap_event_source
, SD_EVENT_PRIORITY_NORMAL
-10);
1344 log_error_errno(r
, "Failed to change /proc/swaps priority: %m");
1348 (void) sd_event_source_set_description(m
->swap_event_source
, "swap-proc");
1351 r
= swap_load_proc_swaps(m
, false);
1361 int swap_process_device_new(Manager
*m
, sd_device
*dev
) {
1362 _cleanup_free_
char *e
= NULL
;
1363 const char *dn
, *devlink
;
1370 r
= sd_device_get_devname(dev
, &dn
);
1374 r
= unit_name_from_path(dn
, ".swap", &e
);
1378 u
= manager_get_unit(m
, e
);
1380 r
= swap_set_devnode(SWAP(u
), dn
);
1382 FOREACH_DEVICE_DEVLINK(dev
, devlink
) {
1383 _cleanup_free_
char *n
= NULL
;
1386 q
= unit_name_from_path(devlink
, ".swap", &n
);
1390 u
= manager_get_unit(m
, n
);
1392 q
= swap_set_devnode(SWAP(u
), dn
);
1401 int swap_process_device_remove(Manager
*m
, sd_device
*dev
) {
1406 r
= sd_device_get_devname(dev
, &dn
);
1410 while ((s
= hashmap_get(m
->swaps_by_devnode
, dn
))) {
1413 q
= swap_set_devnode(s
, NULL
);
1421 static void swap_reset_failed(Unit
*u
) {
1426 if (s
->state
== SWAP_FAILED
)
1427 swap_set_state(s
, SWAP_DEAD
);
1429 s
->result
= SWAP_SUCCESS
;
1432 static int swap_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
1433 return unit_kill_common(u
, who
, signo
, -1, SWAP(u
)->control_pid
, error
);
1436 static int swap_get_timeout(Unit
*u
, usec_t
*timeout
) {
1441 if (!s
->timer_event_source
)
1444 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
1447 if (t
== USEC_INFINITY
)
1454 static bool swap_supported(void) {
1455 static int supported
= -1;
1457 /* If swap support is not available in the kernel, or we are
1458 * running in a container we don't support swap units, and any
1459 * attempts to starting one should fail immediately. */
1463 access("/proc/swaps", F_OK
) >= 0 &&
1464 detect_container() <= 0;
1469 static int swap_control_pid(Unit
*u
) {
1474 return s
->control_pid
;
1477 static const char* const swap_exec_command_table
[_SWAP_EXEC_COMMAND_MAX
] = {
1478 [SWAP_EXEC_ACTIVATE
] = "ExecActivate",
1479 [SWAP_EXEC_DEACTIVATE
] = "ExecDeactivate",
1482 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command
, SwapExecCommand
);
1484 static const char* const swap_result_table
[_SWAP_RESULT_MAX
] = {
1485 [SWAP_SUCCESS
] = "success",
1486 [SWAP_FAILURE_RESOURCES
] = "resources",
1487 [SWAP_FAILURE_TIMEOUT
] = "timeout",
1488 [SWAP_FAILURE_EXIT_CODE
] = "exit-code",
1489 [SWAP_FAILURE_SIGNAL
] = "signal",
1490 [SWAP_FAILURE_CORE_DUMP
] = "core-dump",
1491 [SWAP_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
1494 DEFINE_STRING_TABLE_LOOKUP(swap_result
, SwapResult
);
1496 const UnitVTable swap_vtable
= {
1497 .object_size
= sizeof(Swap
),
1498 .exec_context_offset
= offsetof(Swap
, exec_context
),
1499 .cgroup_context_offset
= offsetof(Swap
, cgroup_context
),
1500 .kill_context_offset
= offsetof(Swap
, kill_context
),
1501 .exec_runtime_offset
= offsetof(Swap
, exec_runtime
),
1502 .dynamic_creds_offset
= offsetof(Swap
, dynamic_creds
),
1508 .private_section
= "Swap",
1514 .coldplug
= swap_coldplug
,
1518 .start
= swap_start
,
1523 .get_timeout
= swap_get_timeout
,
1525 .serialize
= swap_serialize
,
1526 .deserialize_item
= swap_deserialize_item
,
1528 .active_state
= swap_active_state
,
1529 .sub_state_to_string
= swap_sub_state_to_string
,
1531 .may_gc
= swap_may_gc
,
1533 .sigchld_event
= swap_sigchld_event
,
1535 .reset_failed
= swap_reset_failed
,
1537 .control_pid
= swap_control_pid
,
1539 .bus_vtable
= bus_swap_vtable
,
1540 .bus_set_property
= bus_swap_set_property
,
1541 .bus_commit_properties
= bus_swap_commit_properties
,
1543 .following
= swap_following
,
1544 .following_set
= swap_following_set
,
1546 .enumerate
= swap_enumerate
,
1547 .shutdown
= swap_shutdown
,
1548 .supported
= swap_supported
,
1550 .status_message_formats
= {
1551 .starting_stopping
= {
1552 [0] = "Activating swap %s...",
1553 [1] = "Deactivating swap %s...",
1555 .finished_start_job
= {
1556 [JOB_DONE
] = "Activated swap %s.",
1557 [JOB_FAILED
] = "Failed to activate swap %s.",
1558 [JOB_TIMEOUT
] = "Timed out activating swap %s.",
1560 .finished_stop_job
= {
1561 [JOB_DONE
] = "Deactivated swap %s.",
1562 [JOB_FAILED
] = "Failed deactivating swap %s.",
1563 [JOB_TIMEOUT
] = "Timed out deactivating swap %s.",