1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include "alloc-util.h"
11 #include "dbus-swap.h"
12 #include "device-private.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"
24 #include "string-table.h"
25 #include "string-util.h"
27 #include "unit-name.h"
31 static const UnitActiveState state_translation_table
[_SWAP_STATE_MAX
] = {
32 [SWAP_DEAD
] = UNIT_INACTIVE
,
33 [SWAP_ACTIVATING
] = UNIT_ACTIVATING
,
34 [SWAP_ACTIVATING_DONE
] = UNIT_ACTIVE
,
35 [SWAP_ACTIVE
] = UNIT_ACTIVE
,
36 [SWAP_DEACTIVATING
] = UNIT_DEACTIVATING
,
37 [SWAP_DEACTIVATING_SIGTERM
] = UNIT_DEACTIVATING
,
38 [SWAP_DEACTIVATING_SIGKILL
] = UNIT_DEACTIVATING
,
39 [SWAP_FAILED
] = UNIT_FAILED
42 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
43 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
45 static bool SWAP_STATE_WITH_PROCESS(SwapState state
) {
50 SWAP_DEACTIVATING_SIGTERM
,
51 SWAP_DEACTIVATING_SIGKILL
);
54 static void swap_unset_proc_swaps(Swap
*s
) {
57 if (!s
->from_proc_swaps
)
60 s
->parameters_proc_swaps
.what
= mfree(s
->parameters_proc_swaps
.what
);
62 s
->from_proc_swaps
= false;
65 static int swap_set_devnode(Swap
*s
, const char *devnode
) {
72 r
= hashmap_ensure_allocated(&UNIT(s
)->manager
->swaps_by_devnode
, &path_hash_ops
);
76 swaps
= UNIT(s
)->manager
->swaps_by_devnode
;
79 first
= hashmap_get(swaps
, s
->devnode
);
81 LIST_REMOVE(same_devnode
, first
, s
);
83 hashmap_replace(swaps
, first
->devnode
, first
);
85 hashmap_remove(swaps
, s
->devnode
);
87 s
->devnode
= mfree(s
->devnode
);
91 s
->devnode
= strdup(devnode
);
95 first
= hashmap_get(swaps
, s
->devnode
);
96 LIST_PREPEND(same_devnode
, first
, s
);
98 return hashmap_replace(swaps
, first
->devnode
, first
);
104 static void swap_init(Unit
*u
) {
108 assert(UNIT(s
)->load_state
== UNIT_STUB
);
110 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
112 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
113 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
115 s
->parameters_proc_swaps
.priority
= s
->parameters_fragment
.priority
= -1;
117 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
119 u
->ignore_on_isolate
= true;
122 static void swap_unwatch_control_pid(Swap
*s
) {
125 if (s
->control_pid
<= 0)
128 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
132 static void swap_done(Unit
*u
) {
137 swap_unset_proc_swaps(s
);
138 swap_set_devnode(s
, NULL
);
140 s
->what
= mfree(s
->what
);
141 s
->parameters_fragment
.what
= mfree(s
->parameters_fragment
.what
);
142 s
->parameters_fragment
.options
= mfree(s
->parameters_fragment
.options
);
144 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
145 exec_command_done_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
146 s
->control_command
= NULL
;
148 dynamic_creds_unref(&s
->dynamic_creds
);
150 swap_unwatch_control_pid(s
);
152 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
155 static int swap_arm_timer(Swap
*s
, usec_t usec
) {
160 if (s
->timer_event_source
) {
161 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
165 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
168 if (usec
== USEC_INFINITY
)
171 r
= sd_event_add_time(
172 UNIT(s
)->manager
->event
,
173 &s
->timer_event_source
,
176 swap_dispatch_timer
, s
);
180 (void) sd_event_source_set_description(s
->timer_event_source
, "swap-timer");
185 static int swap_add_device_dependencies(Swap
*s
) {
191 if (!s
->from_fragment
)
194 if (is_device_path(s
->what
))
195 return unit_add_node_dependency(UNIT(s
), s
->what
, MANAGER_IS_SYSTEM(UNIT(s
)->manager
), UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
197 /* File based swap devices need to be ordered after
198 * systemd-remount-fs.service, since they might need a
199 * writable file system. */
200 return unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_REMOUNT_FS_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
203 static int swap_add_default_dependencies(Swap
*s
) {
208 if (!UNIT(s
)->default_dependencies
)
211 if (!MANAGER_IS_SYSTEM(UNIT(s
)->manager
))
214 if (detect_container() > 0)
217 /* swap units generated for the swap dev links are missing the
218 * ordering dep against the swap target. */
219 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SWAP_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
223 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_UMOUNT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
226 static int swap_verify(Swap
*s
) {
227 _cleanup_free_
char *e
= NULL
;
230 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
233 r
= unit_name_from_path(s
->what
, ".swap", &e
);
235 return log_unit_error_errno(UNIT(s
), r
, "Failed to generate unit name from path: %m");
237 if (!unit_has_name(UNIT(s
), e
)) {
238 log_unit_error(UNIT(s
), "Value of What= and unit name do not match, not loading.");
242 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
243 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.");
250 static int swap_load_devnode(Swap
*s
) {
251 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
258 if (stat(s
->what
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
261 r
= device_new_from_stat_rdev(&d
, &st
);
263 log_unit_full(UNIT(s
), r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
264 "Failed to allocate device for swap %s: %m", s
->what
);
268 if (sd_device_get_devname(d
, &p
) < 0)
271 return swap_set_devnode(s
, p
);
274 static int swap_load(Unit
*u
) {
279 assert(u
->load_state
== UNIT_STUB
);
281 /* Load a .swap file */
282 if (SWAP(u
)->from_proc_swaps
)
283 r
= unit_load_fragment_and_dropin_optional(u
);
285 r
= unit_load_fragment_and_dropin(u
);
289 if (u
->load_state
== UNIT_LOADED
) {
291 if (UNIT(s
)->fragment_path
)
292 s
->from_fragment
= true;
295 if (s
->parameters_fragment
.what
)
296 s
->what
= strdup(s
->parameters_fragment
.what
);
297 else if (s
->parameters_proc_swaps
.what
)
298 s
->what
= strdup(s
->parameters_proc_swaps
.what
);
300 r
= unit_name_to_path(u
->id
, &s
->what
);
309 path_simplify(s
->what
, false);
311 if (!UNIT(s
)->description
) {
312 r
= unit_set_description(u
, s
->what
);
317 r
= unit_require_mounts_for(UNIT(s
), s
->what
, UNIT_DEPENDENCY_IMPLICIT
);
321 r
= swap_add_device_dependencies(s
);
325 r
= swap_load_devnode(s
);
329 r
= unit_patch_contexts(u
);
333 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
337 r
= unit_set_default_slice(u
);
341 r
= swap_add_default_dependencies(s
);
346 return swap_verify(s
);
349 static int swap_setup_unit(
352 const char *what_proc_swaps
,
356 _cleanup_free_
char *e
= NULL
;
364 assert(what_proc_swaps
);
366 r
= unit_name_from_path(what
, ".swap", &e
);
368 return log_unit_error_errno(u
, r
, "Failed to generate unit name from path: %m");
370 u
= manager_get_unit(m
, e
);
373 SWAP(u
)->from_proc_swaps
&&
374 !path_equal(SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
)) {
375 log_error("Swap %s appeared twice with different device paths %s and %s", e
, SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
);
382 r
= unit_new_for_name(m
, sizeof(Swap
), e
, &u
);
386 SWAP(u
)->what
= strdup(what
);
387 if (!SWAP(u
)->what
) {
392 unit_add_to_load_queue(u
);
396 p
= &SWAP(u
)->parameters_proc_swaps
;
399 p
->what
= strdup(what_proc_swaps
);
407 SWAP(u
)->is_active
= true;
408 SWAP(u
)->just_activated
= !SWAP(u
)->from_proc_swaps
;
411 SWAP(u
)->from_proc_swaps
= true;
413 p
->priority
= priority
;
415 unit_add_to_dbus_queue(u
);
419 log_unit_warning_errno(u
, r
, "Failed to load swap unit: %m");
427 static int swap_process_new(Manager
*m
, const char *device
, int prio
, bool set_flags
) {
428 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
429 const char *dn
, *devlink
;
430 struct stat st
, st_link
;
435 r
= swap_setup_unit(m
, device
, device
, prio
, set_flags
);
439 /* If this is a block device, then let's add duplicates for
440 * all other names of this block device */
441 if (stat(device
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
444 r
= device_new_from_stat_rdev(&d
, &st
);
446 log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
447 "Failed to allocate device for swap %s: %m", device
);
451 /* Add the main device node */
452 if (sd_device_get_devname(d
, &dn
) >= 0 && !streq(dn
, device
))
453 swap_setup_unit(m
, dn
, device
, prio
, set_flags
);
455 /* Add additional units for all symlinks */
456 FOREACH_DEVICE_DEVLINK(d
, devlink
) {
458 /* Don't bother with the /dev/block links */
459 if (streq(devlink
, device
))
462 if (path_startswith(devlink
, "/dev/block/"))
465 if (stat(devlink
, &st_link
) >= 0 &&
466 (!S_ISBLK(st_link
.st_mode
) ||
467 st_link
.st_rdev
!= st
.st_rdev
))
470 swap_setup_unit(m
, devlink
, device
, prio
, set_flags
);
476 static void swap_set_state(Swap
*s
, SwapState state
) {
482 old_state
= s
->state
;
485 if (!SWAP_STATE_WITH_PROCESS(state
)) {
486 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
487 swap_unwatch_control_pid(s
);
488 s
->control_command
= NULL
;
489 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
492 if (state
!= old_state
)
493 log_unit_debug(UNIT(s
), "Changed %s -> %s", swap_state_to_string(old_state
), swap_state_to_string(state
));
495 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
497 /* If there other units for the same device node have a job
498 queued it might be worth checking again if it is runnable
499 now. This is necessary, since swap_start() refuses
500 operation with EAGAIN if there's already another job for
501 the same device node queued. */
502 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
503 if (UNIT(other
)->job
)
504 job_add_to_run_queue(UNIT(other
)->job
);
507 static int swap_coldplug(Unit
*u
) {
509 SwapState new_state
= SWAP_DEAD
;
513 assert(s
->state
== SWAP_DEAD
);
515 if (s
->deserialized_state
!= s
->state
)
516 new_state
= s
->deserialized_state
;
517 else if (s
->from_proc_swaps
)
518 new_state
= SWAP_ACTIVE
;
520 if (new_state
== s
->state
)
523 if (s
->control_pid
> 0 &&
524 pid_is_unwaited(s
->control_pid
) &&
525 SWAP_STATE_WITH_PROCESS(new_state
)) {
527 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
531 r
= swap_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
536 if (!IN_SET(new_state
, SWAP_DEAD
, SWAP_FAILED
)) {
537 (void) unit_setup_dynamic_creds(u
);
538 (void) unit_setup_exec_runtime(u
);
541 swap_set_state(s
, new_state
);
545 static void swap_dump(Unit
*u
, FILE *f
, const char *prefix
) {
546 char buf
[FORMAT_TIMESPAN_MAX
];
553 if (s
->from_proc_swaps
)
554 p
= &s
->parameters_proc_swaps
;
555 else if (s
->from_fragment
)
556 p
= &s
->parameters_fragment
;
564 "%sFrom /proc/swaps: %s\n"
565 "%sFrom fragment: %s\n",
566 prefix
, swap_state_to_string(s
->state
),
567 prefix
, swap_result_to_string(s
->result
),
569 prefix
, yes_no(s
->from_proc_swaps
),
570 prefix
, yes_no(s
->from_fragment
));
573 fprintf(f
, "%sDevice Node: %s\n", prefix
, s
->devnode
);
580 prefix
, strempty(p
->options
));
583 "%sTimeoutSec: %s\n",
584 prefix
, format_timespan(buf
, sizeof(buf
), s
->timeout_usec
, USEC_PER_SEC
));
586 if (s
->control_pid
> 0)
588 "%sControl PID: "PID_FMT
"\n",
589 prefix
, s
->control_pid
);
591 exec_context_dump(&s
->exec_context
, f
, prefix
);
592 kill_context_dump(&s
->kill_context
, f
, prefix
);
593 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
596 static int swap_spawn(Swap
*s
, ExecCommand
*c
, pid_t
*_pid
) {
598 ExecParameters exec_params
= {
599 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
612 r
= unit_prepare_exec(UNIT(s
));
616 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
620 unit_set_exec_params(UNIT(s
), &exec_params
);
622 r
= exec_spawn(UNIT(s
),
632 r
= unit_watch_pid(UNIT(s
), pid
);
634 /* FIXME: we need to do something here */
642 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
647 static void swap_enter_dead(Swap
*s
, SwapResult f
) {
650 if (s
->result
== SWAP_SUCCESS
)
653 if (s
->result
!= SWAP_SUCCESS
)
654 log_unit_warning(UNIT(s
), "Failed with result '%s'.", swap_result_to_string(s
->result
));
656 swap_set_state(s
, s
->result
!= SWAP_SUCCESS
? SWAP_FAILED
: SWAP_DEAD
);
658 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
660 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
662 unit_unref_uid_gid(UNIT(s
), true);
664 dynamic_creds_destroy(&s
->dynamic_creds
);
667 static void swap_enter_active(Swap
*s
, SwapResult f
) {
670 if (s
->result
== SWAP_SUCCESS
)
673 swap_set_state(s
, SWAP_ACTIVE
);
676 static void swap_enter_dead_or_active(Swap
*s
, SwapResult f
) {
679 if (s
->from_proc_swaps
)
680 swap_enter_active(s
, f
);
682 swap_enter_dead(s
, f
);
685 static void swap_enter_signal(Swap
*s
, SwapState state
, SwapResult f
) {
691 if (s
->result
== SWAP_SUCCESS
)
694 if (state
== SWAP_DEACTIVATING_SIGTERM
)
695 kop
= KILL_TERMINATE
;
699 r
= unit_kill_context(UNIT(s
), &s
->kill_context
, kop
, -1, s
->control_pid
, false);
704 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
708 swap_set_state(s
, state
);
709 } else if (state
== SWAP_DEACTIVATING_SIGTERM
&& s
->kill_context
.send_sigkill
)
710 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
712 swap_enter_dead_or_active(s
, SWAP_SUCCESS
);
717 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
718 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
721 static void swap_enter_activating(Swap
*s
) {
722 _cleanup_free_
char *opts
= NULL
;
727 unit_warn_leftover_processes(UNIT(s
));
729 s
->control_command_id
= SWAP_EXEC_ACTIVATE
;
730 s
->control_command
= s
->exec_command
+ SWAP_EXEC_ACTIVATE
;
732 if (s
->from_fragment
) {
735 r
= fstab_find_pri(s
->parameters_fragment
.options
, &priority
);
737 log_warning_errno(r
, "Failed to parse swap priority \"%s\", ignoring: %m", s
->parameters_fragment
.options
);
738 else if (r
== 1 && s
->parameters_fragment
.priority
>= 0)
739 log_warning("Duplicate swap priority configuration by Priority and Options fields.");
741 if (r
<= 0 && s
->parameters_fragment
.priority
>= 0) {
742 if (s
->parameters_fragment
.options
)
743 r
= asprintf(&opts
, "%s,pri=%i", s
->parameters_fragment
.options
, s
->parameters_fragment
.priority
);
745 r
= asprintf(&opts
, "pri=%i", s
->parameters_fragment
.priority
);
751 r
= exec_command_set(s
->control_command
, "/sbin/swapon", NULL
);
755 if (s
->parameters_fragment
.options
|| opts
) {
756 r
= exec_command_append(s
->control_command
, "-o",
757 opts
? : s
->parameters_fragment
.options
, NULL
);
762 r
= exec_command_append(s
->control_command
, s
->what
, NULL
);
766 swap_unwatch_control_pid(s
);
768 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
772 swap_set_state(s
, SWAP_ACTIVATING
);
777 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapon' task: %m");
778 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
781 static void swap_enter_deactivating(Swap
*s
) {
786 s
->control_command_id
= SWAP_EXEC_DEACTIVATE
;
787 s
->control_command
= s
->exec_command
+ SWAP_EXEC_DEACTIVATE
;
789 r
= exec_command_set(s
->control_command
,
796 swap_unwatch_control_pid(s
);
798 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
802 swap_set_state(s
, SWAP_DEACTIVATING
);
807 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapoff' task: %m");
808 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
811 static int swap_start(Unit
*u
) {
812 Swap
*s
= SWAP(u
), *other
;
817 /* We cannot fulfill this request right now, try again later please! */
820 SWAP_DEACTIVATING_SIGTERM
,
821 SWAP_DEACTIVATING_SIGKILL
))
825 if (s
->state
== SWAP_ACTIVATING
)
828 assert(IN_SET(s
->state
, SWAP_DEAD
, SWAP_FAILED
));
830 if (detect_container() > 0)
833 /* If there's a job for another swap unit for the same node
834 * running, then let's not dispatch this one for now, and wait
835 * until that other job has finished. */
836 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
837 if (UNIT(other
)->job
&& UNIT(other
)->job
->state
== JOB_RUNNING
)
840 r
= unit_start_limit_test(u
);
842 swap_enter_dead(s
, SWAP_FAILURE_START_LIMIT_HIT
);
846 r
= unit_acquire_invocation_id(u
);
850 s
->result
= SWAP_SUCCESS
;
851 exec_command_reset_status_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
853 u
->reset_accounting
= true;
855 swap_enter_activating(s
);
859 static int swap_stop(Unit
*u
) {
866 case SWAP_DEACTIVATING
:
867 case SWAP_DEACTIVATING_SIGTERM
:
868 case SWAP_DEACTIVATING_SIGKILL
:
872 case SWAP_ACTIVATING
:
873 case SWAP_ACTIVATING_DONE
:
874 /* There's a control process pending, directly enter kill mode */
875 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_SUCCESS
);
879 if (detect_container() > 0)
882 swap_enter_deactivating(s
);
886 assert_not_reached("Unexpected state.");
890 static int swap_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
897 unit_serialize_item(u
, f
, "state", swap_state_to_string(s
->state
));
898 unit_serialize_item(u
, f
, "result", swap_result_to_string(s
->result
));
900 if (s
->control_pid
> 0)
901 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
903 if (s
->control_command_id
>= 0)
904 unit_serialize_item(u
, f
, "control-command", swap_exec_command_to_string(s
->control_command_id
));
909 static int swap_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
915 if (streq(key
, "state")) {
918 state
= swap_state_from_string(value
);
920 log_unit_debug(u
, "Failed to parse state value: %s", value
);
922 s
->deserialized_state
= state
;
923 } else if (streq(key
, "result")) {
926 f
= swap_result_from_string(value
);
928 log_unit_debug(u
, "Failed to parse result value: %s", value
);
929 else if (f
!= SWAP_SUCCESS
)
931 } else if (streq(key
, "control-pid")) {
934 if (parse_pid(value
, &pid
) < 0)
935 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
937 s
->control_pid
= pid
;
939 } else if (streq(key
, "control-command")) {
942 id
= swap_exec_command_from_string(value
);
944 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
946 s
->control_command_id
= id
;
947 s
->control_command
= s
->exec_command
+ id
;
950 log_unit_debug(u
, "Unknown serialization key: %s", key
);
955 _pure_
static UnitActiveState
swap_active_state(Unit
*u
) {
958 return state_translation_table
[SWAP(u
)->state
];
961 _pure_
static const char *swap_sub_state_to_string(Unit
*u
) {
964 return swap_state_to_string(SWAP(u
)->state
);
967 _pure_
static bool swap_may_gc(Unit
*u
) {
972 if (s
->from_proc_swaps
)
978 static void swap_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
985 if (pid
!= s
->control_pid
)
990 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
992 else if (code
== CLD_EXITED
)
993 f
= SWAP_FAILURE_EXIT_CODE
;
994 else if (code
== CLD_KILLED
)
995 f
= SWAP_FAILURE_SIGNAL
;
996 else if (code
== CLD_DUMPED
)
997 f
= SWAP_FAILURE_CORE_DUMP
;
999 assert_not_reached("Unknown code");
1001 if (s
->result
== SWAP_SUCCESS
)
1004 if (s
->control_command
) {
1005 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
1007 s
->control_command
= NULL
;
1008 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1011 log_unit_full(u
, f
== SWAP_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
1012 "Swap process exited, code=%s status=%i", sigchld_code_to_string(code
), status
);
1016 case SWAP_ACTIVATING
:
1017 case SWAP_ACTIVATING_DONE
:
1019 if (f
== SWAP_SUCCESS
|| s
->from_proc_swaps
)
1020 swap_enter_active(s
, f
);
1022 swap_enter_dead(s
, f
);
1025 case SWAP_DEACTIVATING
:
1026 case SWAP_DEACTIVATING_SIGKILL
:
1027 case SWAP_DEACTIVATING_SIGTERM
:
1029 swap_enter_dead_or_active(s
, f
);
1033 assert_not_reached("Uh, control process died at wrong time.");
1036 /* Notify clients about changed exit status */
1037 unit_add_to_dbus_queue(u
);
1040 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
1041 Swap
*s
= SWAP(userdata
);
1044 assert(s
->timer_event_source
== source
);
1048 case SWAP_ACTIVATING
:
1049 case SWAP_ACTIVATING_DONE
:
1050 log_unit_warning(UNIT(s
), "Activation timed out. Stopping.");
1051 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1054 case SWAP_DEACTIVATING
:
1055 log_unit_warning(UNIT(s
), "Deactivation timed out. Stopping.");
1056 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1059 case SWAP_DEACTIVATING_SIGTERM
:
1060 if (s
->kill_context
.send_sigkill
) {
1061 log_unit_warning(UNIT(s
), "Swap process timed out. Killing.");
1062 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_FAILURE_TIMEOUT
);
1064 log_unit_warning(UNIT(s
), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1065 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1069 case SWAP_DEACTIVATING_SIGKILL
:
1070 log_unit_warning(UNIT(s
), "Swap process still around after SIGKILL. Ignoring.");
1071 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1075 assert_not_reached("Timeout at wrong time.");
1081 static int swap_load_proc_swaps(Manager
*m
, bool set_flags
) {
1087 rewind(m
->proc_swaps
);
1089 (void) fscanf(m
->proc_swaps
, "%*s %*s %*s %*s %*s\n");
1092 _cleanup_free_
char *dev
= NULL
, *d
= NULL
;
1095 k
= fscanf(m
->proc_swaps
,
1096 "%ms " /* device/file */
1097 "%*s " /* type of swap */
1098 "%*s " /* swap size */
1100 "%i\n", /* priority */
1106 log_warning("Failed to parse /proc/swaps:%u.", i
);
1110 if (cunescape(dev
, UNESCAPE_RELAX
, &d
) < 0)
1113 device_found_node(m
, d
, DEVICE_FOUND_SWAP
, DEVICE_FOUND_SWAP
);
1115 k
= swap_process_new(m
, d
, prio
, set_flags
);
1123 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
1124 Manager
*m
= userdata
;
1129 assert(revents
& EPOLLPRI
);
1131 r
= swap_load_proc_swaps(m
, true);
1133 log_error_errno(r
, "Failed to reread /proc/swaps: %m");
1135 /* Reset flags, just in case, for late calls */
1136 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1137 Swap
*swap
= SWAP(u
);
1139 swap
->is_active
= swap
->just_activated
= false;
1145 manager_dispatch_load_queue(m
);
1147 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1148 Swap
*swap
= SWAP(u
);
1150 if (!swap
->is_active
) {
1151 /* This has just been deactivated */
1153 swap_unset_proc_swaps(swap
);
1155 switch (swap
->state
) {
1158 swap_enter_dead(swap
, SWAP_SUCCESS
);
1163 swap_set_state(swap
, swap
->state
);
1168 device_found_node(m
, swap
->what
, 0, DEVICE_FOUND_SWAP
);
1170 } else if (swap
->just_activated
) {
1172 /* New swap entry */
1174 switch (swap
->state
) {
1178 (void) unit_acquire_invocation_id(UNIT(swap
));
1179 swap_enter_active(swap
, SWAP_SUCCESS
);
1182 case SWAP_ACTIVATING
:
1183 swap_set_state(swap
, SWAP_ACTIVATING_DONE
);
1187 /* Nothing really changed, but let's
1188 * issue an notification call
1189 * nonetheless, in case somebody is
1190 * waiting for this. */
1191 swap_set_state(swap
, swap
->state
);
1196 /* Reset the flags for later calls */
1197 swap
->is_active
= swap
->just_activated
= false;
1203 static Unit
*swap_following(Unit
*u
) {
1205 Swap
*other
, *first
= NULL
;
1209 /* If the user configured the swap through /etc/fstab or
1210 * a device unit, follow that. */
1212 if (s
->from_fragment
)
1215 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
1216 if (other
->from_fragment
)
1219 /* Otherwise, make everybody follow the unit that's named after
1220 * the swap device in the kernel */
1222 if (streq_ptr(s
->what
, s
->devnode
))
1225 LIST_FOREACH_AFTER(same_devnode
, other
, s
)
1226 if (streq_ptr(other
->what
, other
->devnode
))
1229 LIST_FOREACH_BEFORE(same_devnode
, other
, s
) {
1230 if (streq_ptr(other
->what
, other
->devnode
))
1236 /* Fall back to the first on the list */
1240 static int swap_following_set(Unit
*u
, Set
**_set
) {
1241 Swap
*s
= SWAP(u
), *other
;
1242 _cleanup_set_free_ Set
*set
= NULL
;
1248 if (LIST_JUST_US(same_devnode
, s
)) {
1253 set
= set_new(NULL
);
1257 LIST_FOREACH_OTHERS(same_devnode
, other
, s
) {
1258 r
= set_put(set
, other
);
1263 *_set
= TAKE_PTR(set
);
1267 static void swap_shutdown(Manager
*m
) {
1270 m
->swap_event_source
= sd_event_source_unref(m
->swap_event_source
);
1271 m
->proc_swaps
= safe_fclose(m
->proc_swaps
);
1272 m
->swaps_by_devnode
= hashmap_free(m
->swaps_by_devnode
);
1275 static void swap_enumerate(Manager
*m
) {
1280 if (!m
->proc_swaps
) {
1281 m
->proc_swaps
= fopen("/proc/swaps", "re");
1282 if (!m
->proc_swaps
) {
1283 if (errno
== ENOENT
)
1284 log_debug_errno(errno
, "Not swap enabled, skipping enumeration.");
1286 log_warning_errno(errno
, "Failed to open /proc/swaps, ignoring: %m");
1291 r
= sd_event_add_io(m
->event
, &m
->swap_event_source
, fileno(m
->proc_swaps
), EPOLLPRI
, swap_dispatch_io
, m
);
1293 log_error_errno(r
, "Failed to watch /proc/swaps: %m");
1297 /* Dispatch this before we dispatch SIGCHLD, so that
1298 * we always get the events from /proc/swaps before
1299 * the SIGCHLD of /sbin/swapon. */
1300 r
= sd_event_source_set_priority(m
->swap_event_source
, SD_EVENT_PRIORITY_NORMAL
-10);
1302 log_error_errno(r
, "Failed to change /proc/swaps priority: %m");
1306 (void) sd_event_source_set_description(m
->swap_event_source
, "swap-proc");
1309 r
= swap_load_proc_swaps(m
, false);
1319 int swap_process_device_new(Manager
*m
, sd_device
*dev
) {
1320 _cleanup_free_
char *e
= NULL
;
1321 const char *dn
, *devlink
;
1328 r
= sd_device_get_devname(dev
, &dn
);
1332 r
= unit_name_from_path(dn
, ".swap", &e
);
1336 u
= manager_get_unit(m
, e
);
1338 r
= swap_set_devnode(SWAP(u
), dn
);
1340 FOREACH_DEVICE_DEVLINK(dev
, devlink
) {
1341 _cleanup_free_
char *n
= NULL
;
1344 q
= unit_name_from_path(devlink
, ".swap", &n
);
1348 u
= manager_get_unit(m
, n
);
1350 q
= swap_set_devnode(SWAP(u
), dn
);
1359 int swap_process_device_remove(Manager
*m
, sd_device
*dev
) {
1364 r
= sd_device_get_devname(dev
, &dn
);
1368 while ((s
= hashmap_get(m
->swaps_by_devnode
, dn
))) {
1371 q
= swap_set_devnode(s
, NULL
);
1379 static void swap_reset_failed(Unit
*u
) {
1384 if (s
->state
== SWAP_FAILED
)
1385 swap_set_state(s
, SWAP_DEAD
);
1387 s
->result
= SWAP_SUCCESS
;
1390 static int swap_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
1391 return unit_kill_common(u
, who
, signo
, -1, SWAP(u
)->control_pid
, error
);
1394 static int swap_get_timeout(Unit
*u
, usec_t
*timeout
) {
1399 if (!s
->timer_event_source
)
1402 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
1405 if (t
== USEC_INFINITY
)
1412 static bool swap_supported(void) {
1413 static int supported
= -1;
1415 /* If swap support is not available in the kernel, or we are
1416 * running in a container we don't support swap units, and any
1417 * attempts to starting one should fail immediately. */
1421 access("/proc/swaps", F_OK
) >= 0 &&
1422 detect_container() <= 0;
1427 static int swap_control_pid(Unit
*u
) {
1432 return s
->control_pid
;
1435 static const char* const swap_exec_command_table
[_SWAP_EXEC_COMMAND_MAX
] = {
1436 [SWAP_EXEC_ACTIVATE
] = "ExecActivate",
1437 [SWAP_EXEC_DEACTIVATE
] = "ExecDeactivate",
1440 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command
, SwapExecCommand
);
1442 static const char* const swap_result_table
[_SWAP_RESULT_MAX
] = {
1443 [SWAP_SUCCESS
] = "success",
1444 [SWAP_FAILURE_RESOURCES
] = "resources",
1445 [SWAP_FAILURE_TIMEOUT
] = "timeout",
1446 [SWAP_FAILURE_EXIT_CODE
] = "exit-code",
1447 [SWAP_FAILURE_SIGNAL
] = "signal",
1448 [SWAP_FAILURE_CORE_DUMP
] = "core-dump",
1449 [SWAP_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
1452 DEFINE_STRING_TABLE_LOOKUP(swap_result
, SwapResult
);
1454 const UnitVTable swap_vtable
= {
1455 .object_size
= sizeof(Swap
),
1456 .exec_context_offset
= offsetof(Swap
, exec_context
),
1457 .cgroup_context_offset
= offsetof(Swap
, cgroup_context
),
1458 .kill_context_offset
= offsetof(Swap
, kill_context
),
1459 .exec_runtime_offset
= offsetof(Swap
, exec_runtime
),
1460 .dynamic_creds_offset
= offsetof(Swap
, dynamic_creds
),
1466 .private_section
= "Swap",
1472 .coldplug
= swap_coldplug
,
1476 .start
= swap_start
,
1481 .get_timeout
= swap_get_timeout
,
1483 .serialize
= swap_serialize
,
1484 .deserialize_item
= swap_deserialize_item
,
1486 .active_state
= swap_active_state
,
1487 .sub_state_to_string
= swap_sub_state_to_string
,
1489 .may_gc
= swap_may_gc
,
1491 .sigchld_event
= swap_sigchld_event
,
1493 .reset_failed
= swap_reset_failed
,
1495 .control_pid
= swap_control_pid
,
1497 .bus_vtable
= bus_swap_vtable
,
1498 .bus_set_property
= bus_swap_set_property
,
1499 .bus_commit_properties
= bus_swap_commit_properties
,
1501 .following
= swap_following
,
1502 .following_set
= swap_following_set
,
1504 .enumerate
= swap_enumerate
,
1505 .shutdown
= swap_shutdown
,
1506 .supported
= swap_supported
,
1508 .status_message_formats
= {
1509 .starting_stopping
= {
1510 [0] = "Activating swap %s...",
1511 [1] = "Deactivating swap %s...",
1513 .finished_start_job
= {
1514 [JOB_DONE
] = "Activated swap %s.",
1515 [JOB_FAILED
] = "Failed to activate swap %s.",
1516 [JOB_TIMEOUT
] = "Timed out activating swap %s.",
1518 .finished_stop_job
= {
1519 [JOB_DONE
] = "Deactivated swap %s.",
1520 [JOB_FAILED
] = "Failed deactivating swap %s.",
1521 [JOB_TIMEOUT
] = "Timed out deactivating swap %s.",