1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
15 #include "alloc-util.h"
16 #include "dbus-swap.h"
18 #include "exit-status.h"
20 #include "format-util.h"
21 #include "fstab-util.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 #include "process-util.h"
26 #include "string-table.h"
27 #include "string-util.h"
29 #include "udev-util.h"
30 #include "unit-name.h"
34 static const UnitActiveState state_translation_table
[_SWAP_STATE_MAX
] = {
35 [SWAP_DEAD
] = UNIT_INACTIVE
,
36 [SWAP_ACTIVATING
] = UNIT_ACTIVATING
,
37 [SWAP_ACTIVATING_DONE
] = UNIT_ACTIVE
,
38 [SWAP_ACTIVE
] = UNIT_ACTIVE
,
39 [SWAP_DEACTIVATING
] = UNIT_DEACTIVATING
,
40 [SWAP_DEACTIVATING_SIGTERM
] = UNIT_DEACTIVATING
,
41 [SWAP_DEACTIVATING_SIGKILL
] = UNIT_DEACTIVATING
,
42 [SWAP_FAILED
] = UNIT_FAILED
45 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
46 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
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
, NULL
, 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
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
226 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_UMOUNT_TARGET
, NULL
, 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_(udev_device_unrefp
) struct udev_device
*d
= NULL
;
260 if (stat(s
->what
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
263 d
= udev_device_new_from_devnum(UNIT(s
)->manager
->udev
, 'b', st
.st_rdev
);
267 p
= udev_device_get_devnode(d
);
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_kill_slashes(s
->what
);
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_(udev_device_unrefp
) struct udev_device
*d
= NULL
;
429 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
436 r
= swap_setup_unit(m
, device
, device
, prio
, set_flags
);
440 /* If this is a block device, then let's add duplicates for
441 * all other names of this block device */
442 if (stat(device
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
445 d
= udev_device_new_from_devnum(m
->udev
, 'b', st
.st_rdev
);
449 /* Add the main device node */
450 dn
= udev_device_get_devnode(d
);
451 if (dn
&& !streq(dn
, device
))
452 swap_setup_unit(m
, dn
, device
, prio
, set_flags
);
454 /* Add additional units for all symlinks */
455 first
= udev_device_get_devlinks_list_entry(d
);
456 udev_list_entry_foreach(item
, first
) {
459 /* Don't bother with the /dev/block links */
460 p
= udev_list_entry_get_name(item
);
462 if (streq(p
, device
))
465 if (path_startswith(p
, "/dev/block/"))
468 if (stat(p
, &st
) >= 0)
469 if (!S_ISBLK(st
.st_mode
) ||
470 st
.st_rdev
!= udev_device_get_devnum(d
))
473 swap_setup_unit(m
, p
, device
, prio
, set_flags
);
479 static void swap_set_state(Swap
*s
, SwapState state
) {
485 old_state
= s
->state
;
488 if (!SWAP_STATE_WITH_PROCESS(state
)) {
489 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
490 swap_unwatch_control_pid(s
);
491 s
->control_command
= NULL
;
492 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
495 if (state
!= old_state
)
496 log_unit_debug(UNIT(s
), "Changed %s -> %s", swap_state_to_string(old_state
), swap_state_to_string(state
));
498 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], true);
500 /* If there other units for the same device node have a job
501 queued it might be worth checking again if it is runnable
502 now. This is necessary, since swap_start() refuses
503 operation with EAGAIN if there's already another job for
504 the same device node queued. */
505 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
506 if (UNIT(other
)->job
)
507 job_add_to_run_queue(UNIT(other
)->job
);
510 static int swap_coldplug(Unit
*u
) {
512 SwapState new_state
= SWAP_DEAD
;
516 assert(s
->state
== SWAP_DEAD
);
518 if (s
->deserialized_state
!= s
->state
)
519 new_state
= s
->deserialized_state
;
520 else if (s
->from_proc_swaps
)
521 new_state
= SWAP_ACTIVE
;
523 if (new_state
== s
->state
)
526 if (s
->control_pid
> 0 &&
527 pid_is_unwaited(s
->control_pid
) &&
528 SWAP_STATE_WITH_PROCESS(new_state
)) {
530 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
534 r
= swap_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
539 if (!IN_SET(new_state
, SWAP_DEAD
, SWAP_FAILED
)) {
540 (void) unit_setup_dynamic_creds(u
);
541 (void) unit_setup_exec_runtime(u
);
544 swap_set_state(s
, new_state
);
548 static void swap_dump(Unit
*u
, FILE *f
, const char *prefix
) {
549 char buf
[FORMAT_TIMESPAN_MAX
];
556 if (s
->from_proc_swaps
)
557 p
= &s
->parameters_proc_swaps
;
558 else if (s
->from_fragment
)
559 p
= &s
->parameters_fragment
;
567 "%sFrom /proc/swaps: %s\n"
568 "%sFrom fragment: %s\n",
569 prefix
, swap_state_to_string(s
->state
),
570 prefix
, swap_result_to_string(s
->result
),
572 prefix
, yes_no(s
->from_proc_swaps
),
573 prefix
, yes_no(s
->from_fragment
));
576 fprintf(f
, "%sDevice Node: %s\n", prefix
, s
->devnode
);
583 prefix
, strempty(p
->options
));
586 "%sTimeoutSec: %s\n",
587 prefix
, format_timespan(buf
, sizeof(buf
), s
->timeout_usec
, USEC_PER_SEC
));
589 if (s
->control_pid
> 0)
591 "%sControl PID: "PID_FMT
"\n",
592 prefix
, s
->control_pid
);
594 exec_context_dump(&s
->exec_context
, f
, prefix
);
595 kill_context_dump(&s
->kill_context
, f
, prefix
);
596 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
599 static int swap_spawn(Swap
*s
, ExecCommand
*c
, pid_t
*_pid
) {
601 ExecParameters exec_params
= {
602 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
614 r
= unit_prepare_exec(UNIT(s
));
618 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
622 unit_set_exec_params(UNIT(s
), &exec_params
);
624 r
= exec_spawn(UNIT(s
),
634 r
= unit_watch_pid(UNIT(s
), pid
);
636 /* FIXME: we need to do something here */
644 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
649 static void swap_enter_dead(Swap
*s
, SwapResult f
) {
652 if (s
->result
== SWAP_SUCCESS
)
655 if (s
->result
!= SWAP_SUCCESS
)
656 log_unit_warning(UNIT(s
), "Failed with result '%s'.", swap_result_to_string(s
->result
));
658 swap_set_state(s
, s
->result
!= SWAP_SUCCESS
? SWAP_FAILED
: SWAP_DEAD
);
660 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
662 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
664 unit_unref_uid_gid(UNIT(s
), true);
666 dynamic_creds_destroy(&s
->dynamic_creds
);
669 static void swap_enter_active(Swap
*s
, SwapResult f
) {
672 if (s
->result
== SWAP_SUCCESS
)
675 swap_set_state(s
, SWAP_ACTIVE
);
678 static void swap_enter_dead_or_active(Swap
*s
, SwapResult f
) {
681 if (s
->from_proc_swaps
)
682 swap_enter_active(s
, f
);
684 swap_enter_dead(s
, f
);
687 static void swap_enter_signal(Swap
*s
, SwapState state
, SwapResult f
) {
693 if (s
->result
== SWAP_SUCCESS
)
696 if (state
== SWAP_DEACTIVATING_SIGTERM
)
697 kop
= KILL_TERMINATE
;
701 r
= unit_kill_context(UNIT(s
), &s
->kill_context
, kop
, -1, s
->control_pid
, false);
706 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
710 swap_set_state(s
, state
);
711 } else if (state
== SWAP_DEACTIVATING_SIGTERM
&& s
->kill_context
.send_sigkill
)
712 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
714 swap_enter_dead_or_active(s
, SWAP_SUCCESS
);
719 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
720 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
723 static void swap_enter_activating(Swap
*s
) {
724 _cleanup_free_
char *opts
= NULL
;
729 unit_warn_leftover_processes(UNIT(s
));
731 s
->control_command_id
= SWAP_EXEC_ACTIVATE
;
732 s
->control_command
= s
->exec_command
+ SWAP_EXEC_ACTIVATE
;
734 if (s
->from_fragment
) {
737 r
= fstab_find_pri(s
->parameters_fragment
.options
, &priority
);
739 log_warning_errno(r
, "Failed to parse swap priority \"%s\", ignoring: %m", s
->parameters_fragment
.options
);
740 else if (r
== 1 && s
->parameters_fragment
.priority
>= 0)
741 log_warning("Duplicate swap priority configuration by Priority and Options fields.");
743 if (r
<= 0 && s
->parameters_fragment
.priority
>= 0) {
744 if (s
->parameters_fragment
.options
)
745 r
= asprintf(&opts
, "%s,pri=%i", s
->parameters_fragment
.options
, s
->parameters_fragment
.priority
);
747 r
= asprintf(&opts
, "pri=%i", s
->parameters_fragment
.priority
);
753 r
= exec_command_set(s
->control_command
, "/sbin/swapon", NULL
);
757 if (s
->parameters_fragment
.options
|| opts
) {
758 r
= exec_command_append(s
->control_command
, "-o",
759 opts
? : s
->parameters_fragment
.options
, NULL
);
764 r
= exec_command_append(s
->control_command
, s
->what
, NULL
);
768 swap_unwatch_control_pid(s
);
770 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
774 swap_set_state(s
, SWAP_ACTIVATING
);
779 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapon' task: %m");
780 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
783 static void swap_enter_deactivating(Swap
*s
) {
788 s
->control_command_id
= SWAP_EXEC_DEACTIVATE
;
789 s
->control_command
= s
->exec_command
+ SWAP_EXEC_DEACTIVATE
;
791 r
= exec_command_set(s
->control_command
,
798 swap_unwatch_control_pid(s
);
800 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
804 swap_set_state(s
, SWAP_DEACTIVATING
);
809 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapoff' task: %m");
810 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
813 static int swap_start(Unit
*u
) {
814 Swap
*s
= SWAP(u
), *other
;
819 /* We cannot fulfill this request right now, try again later please! */
822 SWAP_DEACTIVATING_SIGTERM
,
823 SWAP_DEACTIVATING_SIGKILL
))
827 if (s
->state
== SWAP_ACTIVATING
)
830 assert(IN_SET(s
->state
, SWAP_DEAD
, SWAP_FAILED
));
832 if (detect_container() > 0)
835 /* If there's a job for another swap unit for the same node
836 * running, then let's not dispatch this one for now, and wait
837 * until that other job has finished. */
838 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
839 if (UNIT(other
)->job
&& UNIT(other
)->job
->state
== JOB_RUNNING
)
842 r
= unit_start_limit_test(u
);
844 swap_enter_dead(s
, SWAP_FAILURE_START_LIMIT_HIT
);
848 r
= unit_acquire_invocation_id(u
);
852 s
->result
= SWAP_SUCCESS
;
854 u
->reset_accounting
= true;
856 swap_enter_activating(s
);
860 static int swap_stop(Unit
*u
) {
867 case SWAP_DEACTIVATING
:
868 case SWAP_DEACTIVATING_SIGTERM
:
869 case SWAP_DEACTIVATING_SIGKILL
:
873 case SWAP_ACTIVATING
:
874 case SWAP_ACTIVATING_DONE
:
875 /* There's a control process pending, directly enter kill mode */
876 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_SUCCESS
);
880 if (detect_container() > 0)
883 swap_enter_deactivating(s
);
887 assert_not_reached("Unexpected state.");
891 static int swap_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
898 unit_serialize_item(u
, f
, "state", swap_state_to_string(s
->state
));
899 unit_serialize_item(u
, f
, "result", swap_result_to_string(s
->result
));
901 if (s
->control_pid
> 0)
902 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
904 if (s
->control_command_id
>= 0)
905 unit_serialize_item(u
, f
, "control-command", swap_exec_command_to_string(s
->control_command_id
));
910 static int swap_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
916 if (streq(key
, "state")) {
919 state
= swap_state_from_string(value
);
921 log_unit_debug(u
, "Failed to parse state value: %s", value
);
923 s
->deserialized_state
= state
;
924 } else if (streq(key
, "result")) {
927 f
= swap_result_from_string(value
);
929 log_unit_debug(u
, "Failed to parse result value: %s", value
);
930 else if (f
!= SWAP_SUCCESS
)
932 } else if (streq(key
, "control-pid")) {
935 if (parse_pid(value
, &pid
) < 0)
936 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
938 s
->control_pid
= pid
;
940 } else if (streq(key
, "control-command")) {
943 id
= swap_exec_command_from_string(value
);
945 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
947 s
->control_command_id
= id
;
948 s
->control_command
= s
->exec_command
+ id
;
951 log_unit_debug(u
, "Unknown serialization key: %s", key
);
956 _pure_
static UnitActiveState
swap_active_state(Unit
*u
) {
959 return state_translation_table
[SWAP(u
)->state
];
962 _pure_
static const char *swap_sub_state_to_string(Unit
*u
) {
965 return swap_state_to_string(SWAP(u
)->state
);
968 _pure_
static bool swap_may_gc(Unit
*u
) {
973 if (s
->from_proc_swaps
)
979 static void swap_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
986 if (pid
!= s
->control_pid
)
991 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
993 else if (code
== CLD_EXITED
)
994 f
= SWAP_FAILURE_EXIT_CODE
;
995 else if (code
== CLD_KILLED
)
996 f
= SWAP_FAILURE_SIGNAL
;
997 else if (code
== CLD_DUMPED
)
998 f
= SWAP_FAILURE_CORE_DUMP
;
1000 assert_not_reached("Unknown code");
1002 if (s
->result
== SWAP_SUCCESS
)
1005 if (s
->control_command
) {
1006 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
1008 s
->control_command
= NULL
;
1009 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1012 log_unit_full(u
, f
== SWAP_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
1013 "Swap process exited, code=%s status=%i", sigchld_code_to_string(code
), status
);
1017 case SWAP_ACTIVATING
:
1018 case SWAP_ACTIVATING_DONE
:
1020 if (f
== SWAP_SUCCESS
|| s
->from_proc_swaps
)
1021 swap_enter_active(s
, f
);
1023 swap_enter_dead(s
, f
);
1026 case SWAP_DEACTIVATING
:
1027 case SWAP_DEACTIVATING_SIGKILL
:
1028 case SWAP_DEACTIVATING_SIGTERM
:
1030 swap_enter_dead_or_active(s
, f
);
1034 assert_not_reached("Uh, control process died at wrong time.");
1037 /* Notify clients about changed exit status */
1038 unit_add_to_dbus_queue(u
);
1041 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
1042 Swap
*s
= SWAP(userdata
);
1045 assert(s
->timer_event_source
== source
);
1049 case SWAP_ACTIVATING
:
1050 case SWAP_ACTIVATING_DONE
:
1051 log_unit_warning(UNIT(s
), "Activation timed out. Stopping.");
1052 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1055 case SWAP_DEACTIVATING
:
1056 log_unit_warning(UNIT(s
), "Deactivation timed out. Stopping.");
1057 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1060 case SWAP_DEACTIVATING_SIGTERM
:
1061 if (s
->kill_context
.send_sigkill
) {
1062 log_unit_warning(UNIT(s
), "Swap process timed out. Killing.");
1063 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_FAILURE_TIMEOUT
);
1065 log_unit_warning(UNIT(s
), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1066 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1070 case SWAP_DEACTIVATING_SIGKILL
:
1071 log_unit_warning(UNIT(s
), "Swap process still around after SIGKILL. Ignoring.");
1072 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1076 assert_not_reached("Timeout at wrong time.");
1082 static int swap_load_proc_swaps(Manager
*m
, bool set_flags
) {
1088 rewind(m
->proc_swaps
);
1090 (void) fscanf(m
->proc_swaps
, "%*s %*s %*s %*s %*s\n");
1093 _cleanup_free_
char *dev
= NULL
, *d
= NULL
;
1096 k
= fscanf(m
->proc_swaps
,
1097 "%ms " /* device/file */
1098 "%*s " /* type of swap */
1099 "%*s " /* swap size */
1101 "%i\n", /* priority */
1107 log_warning("Failed to parse /proc/swaps:%u.", i
);
1111 if (cunescape(dev
, UNESCAPE_RELAX
, &d
) < 0)
1114 device_found_node(m
, d
, true, DEVICE_FOUND_SWAP
, set_flags
);
1116 k
= swap_process_new(m
, d
, prio
, set_flags
);
1124 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
1125 Manager
*m
= userdata
;
1130 assert(revents
& EPOLLPRI
);
1132 r
= swap_load_proc_swaps(m
, true);
1134 log_error_errno(r
, "Failed to reread /proc/swaps: %m");
1136 /* Reset flags, just in case, for late calls */
1137 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1138 Swap
*swap
= SWAP(u
);
1140 swap
->is_active
= swap
->just_activated
= false;
1146 manager_dispatch_load_queue(m
);
1148 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1149 Swap
*swap
= SWAP(u
);
1151 if (!swap
->is_active
) {
1152 /* This has just been deactivated */
1154 swap_unset_proc_swaps(swap
);
1156 switch (swap
->state
) {
1159 swap_enter_dead(swap
, SWAP_SUCCESS
);
1164 swap_set_state(swap
, swap
->state
);
1169 device_found_node(m
, swap
->what
, false, DEVICE_FOUND_SWAP
, true);
1171 } else if (swap
->just_activated
) {
1173 /* New swap entry */
1175 switch (swap
->state
) {
1179 (void) unit_acquire_invocation_id(UNIT(swap
));
1180 swap_enter_active(swap
, SWAP_SUCCESS
);
1183 case SWAP_ACTIVATING
:
1184 swap_set_state(swap
, SWAP_ACTIVATING_DONE
);
1188 /* Nothing really changed, but let's
1189 * issue an notification call
1190 * nonetheless, in case somebody is
1191 * waiting for this. */
1192 swap_set_state(swap
, swap
->state
);
1197 /* Reset the flags for later calls */
1198 swap
->is_active
= swap
->just_activated
= false;
1204 static Unit
*swap_following(Unit
*u
) {
1206 Swap
*other
, *first
= NULL
;
1210 /* If the user configured the swap through /etc/fstab or
1211 * a device unit, follow that. */
1213 if (s
->from_fragment
)
1216 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
1217 if (other
->from_fragment
)
1220 /* Otherwise, make everybody follow the unit that's named after
1221 * the swap device in the kernel */
1223 if (streq_ptr(s
->what
, s
->devnode
))
1226 LIST_FOREACH_AFTER(same_devnode
, other
, s
)
1227 if (streq_ptr(other
->what
, other
->devnode
))
1230 LIST_FOREACH_BEFORE(same_devnode
, other
, s
) {
1231 if (streq_ptr(other
->what
, other
->devnode
))
1237 /* Fall back to the first on the list */
1241 static int swap_following_set(Unit
*u
, Set
**_set
) {
1242 Swap
*s
= SWAP(u
), *other
;
1243 _cleanup_(set_freep
) Set
*set
= NULL
;
1249 if (LIST_JUST_US(same_devnode
, s
)) {
1254 set
= set_new(NULL
);
1258 LIST_FOREACH_OTHERS(same_devnode
, other
, s
) {
1259 r
= set_put(set
, other
);
1264 *_set
= TAKE_PTR(set
);
1268 static void swap_shutdown(Manager
*m
) {
1271 m
->swap_event_source
= sd_event_source_unref(m
->swap_event_source
);
1273 m
->proc_swaps
= safe_fclose(m
->proc_swaps
);
1275 m
->swaps_by_devnode
= hashmap_free(m
->swaps_by_devnode
);
1278 static void swap_enumerate(Manager
*m
) {
1283 if (!m
->proc_swaps
) {
1284 m
->proc_swaps
= fopen("/proc/swaps", "re");
1285 if (!m
->proc_swaps
) {
1286 if (errno
== ENOENT
)
1287 log_debug("Not swap enabled, skipping enumeration");
1289 log_error_errno(errno
, "Failed to open /proc/swaps: %m");
1294 r
= sd_event_add_io(m
->event
, &m
->swap_event_source
, fileno(m
->proc_swaps
), EPOLLPRI
, swap_dispatch_io
, m
);
1296 log_error_errno(r
, "Failed to watch /proc/swaps: %m");
1300 /* Dispatch this before we dispatch SIGCHLD, so that
1301 * we always get the events from /proc/swaps before
1302 * the SIGCHLD of /sbin/swapon. */
1303 r
= sd_event_source_set_priority(m
->swap_event_source
, SD_EVENT_PRIORITY_NORMAL
-10);
1305 log_error_errno(r
, "Failed to change /proc/swaps priority: %m");
1309 (void) sd_event_source_set_description(m
->swap_event_source
, "swap-proc");
1312 r
= swap_load_proc_swaps(m
, false);
1322 int swap_process_device_new(Manager
*m
, struct udev_device
*dev
) {
1323 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
1324 _cleanup_free_
char *e
= NULL
;
1332 dn
= udev_device_get_devnode(dev
);
1336 r
= unit_name_from_path(dn
, ".swap", &e
);
1340 u
= manager_get_unit(m
, e
);
1342 r
= swap_set_devnode(SWAP(u
), dn
);
1344 first
= udev_device_get_devlinks_list_entry(dev
);
1345 udev_list_entry_foreach(item
, first
) {
1346 _cleanup_free_
char *n
= NULL
;
1349 q
= unit_name_from_path(udev_list_entry_get_name(item
), ".swap", &n
);
1353 u
= manager_get_unit(m
, n
);
1355 q
= swap_set_devnode(SWAP(u
), dn
);
1364 int swap_process_device_remove(Manager
*m
, struct udev_device
*dev
) {
1369 dn
= udev_device_get_devnode(dev
);
1373 while ((s
= hashmap_get(m
->swaps_by_devnode
, dn
))) {
1376 q
= swap_set_devnode(s
, NULL
);
1384 static void swap_reset_failed(Unit
*u
) {
1389 if (s
->state
== SWAP_FAILED
)
1390 swap_set_state(s
, SWAP_DEAD
);
1392 s
->result
= SWAP_SUCCESS
;
1395 static int swap_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
1396 return unit_kill_common(u
, who
, signo
, -1, SWAP(u
)->control_pid
, error
);
1399 static int swap_get_timeout(Unit
*u
, usec_t
*timeout
) {
1404 if (!s
->timer_event_source
)
1407 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
1410 if (t
== USEC_INFINITY
)
1417 static bool swap_supported(void) {
1418 static int supported
= -1;
1420 /* If swap support is not available in the kernel, or we are
1421 * running in a container we don't support swap units, and any
1422 * attempts to starting one should fail immediately. */
1426 access("/proc/swaps", F_OK
) >= 0 &&
1427 detect_container() <= 0;
1432 static int swap_control_pid(Unit
*u
) {
1437 return s
->control_pid
;
1440 static const char* const swap_exec_command_table
[_SWAP_EXEC_COMMAND_MAX
] = {
1441 [SWAP_EXEC_ACTIVATE
] = "ExecActivate",
1442 [SWAP_EXEC_DEACTIVATE
] = "ExecDeactivate",
1445 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command
, SwapExecCommand
);
1447 static const char* const swap_result_table
[_SWAP_RESULT_MAX
] = {
1448 [SWAP_SUCCESS
] = "success",
1449 [SWAP_FAILURE_RESOURCES
] = "resources",
1450 [SWAP_FAILURE_TIMEOUT
] = "timeout",
1451 [SWAP_FAILURE_EXIT_CODE
] = "exit-code",
1452 [SWAP_FAILURE_SIGNAL
] = "signal",
1453 [SWAP_FAILURE_CORE_DUMP
] = "core-dump",
1454 [SWAP_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
1457 DEFINE_STRING_TABLE_LOOKUP(swap_result
, SwapResult
);
1459 const UnitVTable swap_vtable
= {
1460 .object_size
= sizeof(Swap
),
1461 .exec_context_offset
= offsetof(Swap
, exec_context
),
1462 .cgroup_context_offset
= offsetof(Swap
, cgroup_context
),
1463 .kill_context_offset
= offsetof(Swap
, kill_context
),
1464 .exec_runtime_offset
= offsetof(Swap
, exec_runtime
),
1465 .dynamic_creds_offset
= offsetof(Swap
, dynamic_creds
),
1471 .private_section
= "Swap",
1477 .coldplug
= swap_coldplug
,
1481 .start
= swap_start
,
1486 .get_timeout
= swap_get_timeout
,
1488 .serialize
= swap_serialize
,
1489 .deserialize_item
= swap_deserialize_item
,
1491 .active_state
= swap_active_state
,
1492 .sub_state_to_string
= swap_sub_state_to_string
,
1494 .may_gc
= swap_may_gc
,
1496 .sigchld_event
= swap_sigchld_event
,
1498 .reset_failed
= swap_reset_failed
,
1500 .control_pid
= swap_control_pid
,
1502 .bus_vtable
= bus_swap_vtable
,
1503 .bus_set_property
= bus_swap_set_property
,
1504 .bus_commit_properties
= bus_swap_commit_properties
,
1506 .following
= swap_following
,
1507 .following_set
= swap_following_set
,
1509 .enumerate
= swap_enumerate
,
1510 .shutdown
= swap_shutdown
,
1511 .supported
= swap_supported
,
1513 .status_message_formats
= {
1514 .starting_stopping
= {
1515 [0] = "Activating swap %s...",
1516 [1] = "Deactivating swap %s...",
1518 .finished_start_job
= {
1519 [JOB_DONE
] = "Activated swap %s.",
1520 [JOB_FAILED
] = "Failed to activate swap %s.",
1521 [JOB_TIMEOUT
] = "Timed out activating swap %s.",
1523 .finished_stop_job
= {
1524 [JOB_DONE
] = "Deactivated swap %s.",
1525 [JOB_FAILED
] = "Failed deactivating swap %s.",
1526 [JOB_TIMEOUT
] = "Timed out deactivating swap %s.",