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"
19 #include "exit-status.h"
21 #include "format-util.h"
22 #include "fstab-util.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "process-util.h"
27 #include "string-table.h"
28 #include "string-util.h"
30 #include "udev-util.h"
31 #include "unit-name.h"
35 static const UnitActiveState state_translation_table
[_SWAP_STATE_MAX
] = {
36 [SWAP_DEAD
] = UNIT_INACTIVE
,
37 [SWAP_ACTIVATING
] = UNIT_ACTIVATING
,
38 [SWAP_ACTIVATING_DONE
] = UNIT_ACTIVE
,
39 [SWAP_ACTIVE
] = UNIT_ACTIVE
,
40 [SWAP_DEACTIVATING
] = UNIT_DEACTIVATING
,
41 [SWAP_DEACTIVATING_SIGTERM
] = UNIT_DEACTIVATING
,
42 [SWAP_DEACTIVATING_SIGKILL
] = UNIT_DEACTIVATING
,
43 [SWAP_FAILED
] = UNIT_FAILED
46 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
47 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
49 static bool SWAP_STATE_WITH_PROCESS(SwapState state
) {
54 SWAP_DEACTIVATING_SIGTERM
,
55 SWAP_DEACTIVATING_SIGKILL
);
58 static void swap_unset_proc_swaps(Swap
*s
) {
61 if (!s
->from_proc_swaps
)
64 s
->parameters_proc_swaps
.what
= mfree(s
->parameters_proc_swaps
.what
);
66 s
->from_proc_swaps
= false;
69 static int swap_set_devnode(Swap
*s
, const char *devnode
) {
76 r
= hashmap_ensure_allocated(&UNIT(s
)->manager
->swaps_by_devnode
, &path_hash_ops
);
80 swaps
= UNIT(s
)->manager
->swaps_by_devnode
;
83 first
= hashmap_get(swaps
, s
->devnode
);
85 LIST_REMOVE(same_devnode
, first
, s
);
87 hashmap_replace(swaps
, first
->devnode
, first
);
89 hashmap_remove(swaps
, s
->devnode
);
91 s
->devnode
= mfree(s
->devnode
);
95 s
->devnode
= strdup(devnode
);
99 first
= hashmap_get(swaps
, s
->devnode
);
100 LIST_PREPEND(same_devnode
, first
, s
);
102 return hashmap_replace(swaps
, first
->devnode
, first
);
108 static void swap_init(Unit
*u
) {
112 assert(UNIT(s
)->load_state
== UNIT_STUB
);
114 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
116 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
117 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
119 s
->parameters_proc_swaps
.priority
= s
->parameters_fragment
.priority
= -1;
121 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
123 u
->ignore_on_isolate
= true;
126 static void swap_unwatch_control_pid(Swap
*s
) {
129 if (s
->control_pid
<= 0)
132 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
136 static void swap_done(Unit
*u
) {
141 swap_unset_proc_swaps(s
);
142 swap_set_devnode(s
, NULL
);
144 s
->what
= mfree(s
->what
);
145 s
->parameters_fragment
.what
= mfree(s
->parameters_fragment
.what
);
146 s
->parameters_fragment
.options
= mfree(s
->parameters_fragment
.options
);
148 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
149 exec_command_done_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
150 s
->control_command
= NULL
;
152 dynamic_creds_unref(&s
->dynamic_creds
);
154 swap_unwatch_control_pid(s
);
156 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
159 static int swap_arm_timer(Swap
*s
, usec_t usec
) {
164 if (s
->timer_event_source
) {
165 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
169 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
172 if (usec
== USEC_INFINITY
)
175 r
= sd_event_add_time(
176 UNIT(s
)->manager
->event
,
177 &s
->timer_event_source
,
180 swap_dispatch_timer
, s
);
184 (void) sd_event_source_set_description(s
->timer_event_source
, "swap-timer");
189 static int swap_add_device_dependencies(Swap
*s
) {
195 if (!s
->from_fragment
)
198 if (is_device_path(s
->what
))
199 return unit_add_node_dependency(UNIT(s
), s
->what
, MANAGER_IS_SYSTEM(UNIT(s
)->manager
), UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
201 /* File based swap devices need to be ordered after
202 * systemd-remount-fs.service, since they might need a
203 * writable file system. */
204 return unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_REMOUNT_FS_SERVICE
, NULL
, true, UNIT_DEPENDENCY_FILE
);
207 static int swap_add_default_dependencies(Swap
*s
) {
212 if (!UNIT(s
)->default_dependencies
)
215 if (!MANAGER_IS_SYSTEM(UNIT(s
)->manager
))
218 if (detect_container() > 0)
221 /* swap units generated for the swap dev links are missing the
222 * ordering dep against the swap target. */
223 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SWAP_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
227 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_UMOUNT_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
230 static int swap_verify(Swap
*s
) {
231 _cleanup_free_
char *e
= NULL
;
234 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
237 r
= unit_name_from_path(s
->what
, ".swap", &e
);
239 return log_unit_error_errno(UNIT(s
), r
, "Failed to generate unit name from path: %m");
241 if (!unit_has_name(UNIT(s
), e
)) {
242 log_unit_error(UNIT(s
), "Value of What= and unit name do not match, not loading.");
246 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
247 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.");
254 static int swap_load_devnode(Swap
*s
) {
255 _cleanup_(udev_device_unrefp
) struct udev_device
*d
= NULL
;
262 if (stat(s
->what
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
265 r
= udev_device_new_from_stat_rdev(UNIT(s
)->manager
->udev
, &st
, &d
);
267 log_unit_full(UNIT(s
), r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
268 "Failed to allocate udev device for swap %s: %m", s
->what
);
272 p
= udev_device_get_devnode(d
);
276 return swap_set_devnode(s
, p
);
279 static int swap_load(Unit
*u
) {
284 assert(u
->load_state
== UNIT_STUB
);
286 /* Load a .swap file */
287 if (SWAP(u
)->from_proc_swaps
)
288 r
= unit_load_fragment_and_dropin_optional(u
);
290 r
= unit_load_fragment_and_dropin(u
);
294 if (u
->load_state
== UNIT_LOADED
) {
296 if (UNIT(s
)->fragment_path
)
297 s
->from_fragment
= true;
300 if (s
->parameters_fragment
.what
)
301 s
->what
= strdup(s
->parameters_fragment
.what
);
302 else if (s
->parameters_proc_swaps
.what
)
303 s
->what
= strdup(s
->parameters_proc_swaps
.what
);
305 r
= unit_name_to_path(u
->id
, &s
->what
);
314 path_simplify(s
->what
, false);
316 if (!UNIT(s
)->description
) {
317 r
= unit_set_description(u
, s
->what
);
322 r
= unit_require_mounts_for(UNIT(s
), s
->what
, UNIT_DEPENDENCY_IMPLICIT
);
326 r
= swap_add_device_dependencies(s
);
330 r
= swap_load_devnode(s
);
334 r
= unit_patch_contexts(u
);
338 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
342 r
= unit_set_default_slice(u
);
346 r
= swap_add_default_dependencies(s
);
351 return swap_verify(s
);
354 static int swap_setup_unit(
357 const char *what_proc_swaps
,
361 _cleanup_free_
char *e
= NULL
;
369 assert(what_proc_swaps
);
371 r
= unit_name_from_path(what
, ".swap", &e
);
373 return log_unit_error_errno(u
, r
, "Failed to generate unit name from path: %m");
375 u
= manager_get_unit(m
, e
);
378 SWAP(u
)->from_proc_swaps
&&
379 !path_equal(SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
)) {
380 log_error("Swap %s appeared twice with different device paths %s and %s", e
, SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
);
387 r
= unit_new_for_name(m
, sizeof(Swap
), e
, &u
);
391 SWAP(u
)->what
= strdup(what
);
392 if (!SWAP(u
)->what
) {
397 unit_add_to_load_queue(u
);
401 p
= &SWAP(u
)->parameters_proc_swaps
;
404 p
->what
= strdup(what_proc_swaps
);
412 SWAP(u
)->is_active
= true;
413 SWAP(u
)->just_activated
= !SWAP(u
)->from_proc_swaps
;
416 SWAP(u
)->from_proc_swaps
= true;
418 p
->priority
= priority
;
420 unit_add_to_dbus_queue(u
);
424 log_unit_warning_errno(u
, r
, "Failed to load swap unit: %m");
432 static int swap_process_new(Manager
*m
, const char *device
, int prio
, bool set_flags
) {
433 _cleanup_(udev_device_unrefp
) struct udev_device
*d
= NULL
;
434 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
441 r
= swap_setup_unit(m
, device
, device
, prio
, set_flags
);
445 /* If this is a block device, then let's add duplicates for
446 * all other names of this block device */
447 if (stat(device
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
450 r
= udev_device_new_from_stat_rdev(m
->udev
, &st
, &d
);
452 log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
453 "Failed to allocate udev device for swap %s: %m", device
);
457 /* Add the main device node */
458 dn
= udev_device_get_devnode(d
);
459 if (dn
&& !streq(dn
, device
))
460 swap_setup_unit(m
, dn
, device
, prio
, set_flags
);
462 /* Add additional units for all symlinks */
463 first
= udev_device_get_devlinks_list_entry(d
);
464 udev_list_entry_foreach(item
, first
) {
467 /* Don't bother with the /dev/block links */
468 p
= udev_list_entry_get_name(item
);
470 if (streq(p
, device
))
473 if (path_startswith(p
, "/dev/block/"))
476 if (stat(p
, &st
) >= 0)
477 if (!S_ISBLK(st
.st_mode
) ||
478 st
.st_rdev
!= udev_device_get_devnum(d
))
481 swap_setup_unit(m
, p
, device
, prio
, set_flags
);
487 static void swap_set_state(Swap
*s
, SwapState state
) {
493 old_state
= s
->state
;
496 if (!SWAP_STATE_WITH_PROCESS(state
)) {
497 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
498 swap_unwatch_control_pid(s
);
499 s
->control_command
= NULL
;
500 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
503 if (state
!= old_state
)
504 log_unit_debug(UNIT(s
), "Changed %s -> %s", swap_state_to_string(old_state
), swap_state_to_string(state
));
506 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
508 /* If there other units for the same device node have a job
509 queued it might be worth checking again if it is runnable
510 now. This is necessary, since swap_start() refuses
511 operation with EAGAIN if there's already another job for
512 the same device node queued. */
513 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
514 if (UNIT(other
)->job
)
515 job_add_to_run_queue(UNIT(other
)->job
);
518 static int swap_coldplug(Unit
*u
) {
520 SwapState new_state
= SWAP_DEAD
;
524 assert(s
->state
== SWAP_DEAD
);
526 if (s
->deserialized_state
!= s
->state
)
527 new_state
= s
->deserialized_state
;
528 else if (s
->from_proc_swaps
)
529 new_state
= SWAP_ACTIVE
;
531 if (new_state
== s
->state
)
534 if (s
->control_pid
> 0 &&
535 pid_is_unwaited(s
->control_pid
) &&
536 SWAP_STATE_WITH_PROCESS(new_state
)) {
538 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
542 r
= swap_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
547 if (!IN_SET(new_state
, SWAP_DEAD
, SWAP_FAILED
)) {
548 (void) unit_setup_dynamic_creds(u
);
549 (void) unit_setup_exec_runtime(u
);
552 swap_set_state(s
, new_state
);
556 static void swap_dump(Unit
*u
, FILE *f
, const char *prefix
) {
557 char buf
[FORMAT_TIMESPAN_MAX
];
564 if (s
->from_proc_swaps
)
565 p
= &s
->parameters_proc_swaps
;
566 else if (s
->from_fragment
)
567 p
= &s
->parameters_fragment
;
575 "%sFrom /proc/swaps: %s\n"
576 "%sFrom fragment: %s\n",
577 prefix
, swap_state_to_string(s
->state
),
578 prefix
, swap_result_to_string(s
->result
),
580 prefix
, yes_no(s
->from_proc_swaps
),
581 prefix
, yes_no(s
->from_fragment
));
584 fprintf(f
, "%sDevice Node: %s\n", prefix
, s
->devnode
);
591 prefix
, strempty(p
->options
));
594 "%sTimeoutSec: %s\n",
595 prefix
, format_timespan(buf
, sizeof(buf
), s
->timeout_usec
, USEC_PER_SEC
));
597 if (s
->control_pid
> 0)
599 "%sControl PID: "PID_FMT
"\n",
600 prefix
, s
->control_pid
);
602 exec_context_dump(&s
->exec_context
, f
, prefix
);
603 kill_context_dump(&s
->kill_context
, f
, prefix
);
604 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
607 static int swap_spawn(Swap
*s
, ExecCommand
*c
, pid_t
*_pid
) {
609 ExecParameters exec_params
= {
610 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
622 r
= unit_prepare_exec(UNIT(s
));
626 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
630 unit_set_exec_params(UNIT(s
), &exec_params
);
632 r
= exec_spawn(UNIT(s
),
642 r
= unit_watch_pid(UNIT(s
), pid
);
644 /* FIXME: we need to do something here */
652 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
657 static void swap_enter_dead(Swap
*s
, SwapResult f
) {
660 if (s
->result
== SWAP_SUCCESS
)
663 if (s
->result
!= SWAP_SUCCESS
)
664 log_unit_warning(UNIT(s
), "Failed with result '%s'.", swap_result_to_string(s
->result
));
666 swap_set_state(s
, s
->result
!= SWAP_SUCCESS
? SWAP_FAILED
: SWAP_DEAD
);
668 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
670 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
672 unit_unref_uid_gid(UNIT(s
), true);
674 dynamic_creds_destroy(&s
->dynamic_creds
);
677 static void swap_enter_active(Swap
*s
, SwapResult f
) {
680 if (s
->result
== SWAP_SUCCESS
)
683 swap_set_state(s
, SWAP_ACTIVE
);
686 static void swap_enter_dead_or_active(Swap
*s
, SwapResult f
) {
689 if (s
->from_proc_swaps
)
690 swap_enter_active(s
, f
);
692 swap_enter_dead(s
, f
);
695 static void swap_enter_signal(Swap
*s
, SwapState state
, SwapResult f
) {
701 if (s
->result
== SWAP_SUCCESS
)
704 if (state
== SWAP_DEACTIVATING_SIGTERM
)
705 kop
= KILL_TERMINATE
;
709 r
= unit_kill_context(UNIT(s
), &s
->kill_context
, kop
, -1, s
->control_pid
, false);
714 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
718 swap_set_state(s
, state
);
719 } else if (state
== SWAP_DEACTIVATING_SIGTERM
&& s
->kill_context
.send_sigkill
)
720 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
722 swap_enter_dead_or_active(s
, SWAP_SUCCESS
);
727 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
728 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
731 static void swap_enter_activating(Swap
*s
) {
732 _cleanup_free_
char *opts
= NULL
;
737 unit_warn_leftover_processes(UNIT(s
));
739 s
->control_command_id
= SWAP_EXEC_ACTIVATE
;
740 s
->control_command
= s
->exec_command
+ SWAP_EXEC_ACTIVATE
;
742 if (s
->from_fragment
) {
745 r
= fstab_find_pri(s
->parameters_fragment
.options
, &priority
);
747 log_warning_errno(r
, "Failed to parse swap priority \"%s\", ignoring: %m", s
->parameters_fragment
.options
);
748 else if (r
== 1 && s
->parameters_fragment
.priority
>= 0)
749 log_warning("Duplicate swap priority configuration by Priority and Options fields.");
751 if (r
<= 0 && s
->parameters_fragment
.priority
>= 0) {
752 if (s
->parameters_fragment
.options
)
753 r
= asprintf(&opts
, "%s,pri=%i", s
->parameters_fragment
.options
, s
->parameters_fragment
.priority
);
755 r
= asprintf(&opts
, "pri=%i", s
->parameters_fragment
.priority
);
761 r
= exec_command_set(s
->control_command
, "/sbin/swapon", NULL
);
765 if (s
->parameters_fragment
.options
|| opts
) {
766 r
= exec_command_append(s
->control_command
, "-o",
767 opts
? : s
->parameters_fragment
.options
, NULL
);
772 r
= exec_command_append(s
->control_command
, s
->what
, NULL
);
776 swap_unwatch_control_pid(s
);
778 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
782 swap_set_state(s
, SWAP_ACTIVATING
);
787 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapon' task: %m");
788 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
791 static void swap_enter_deactivating(Swap
*s
) {
796 s
->control_command_id
= SWAP_EXEC_DEACTIVATE
;
797 s
->control_command
= s
->exec_command
+ SWAP_EXEC_DEACTIVATE
;
799 r
= exec_command_set(s
->control_command
,
806 swap_unwatch_control_pid(s
);
808 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
812 swap_set_state(s
, SWAP_DEACTIVATING
);
817 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapoff' task: %m");
818 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
821 static int swap_start(Unit
*u
) {
822 Swap
*s
= SWAP(u
), *other
;
827 /* We cannot fulfill this request right now, try again later please! */
830 SWAP_DEACTIVATING_SIGTERM
,
831 SWAP_DEACTIVATING_SIGKILL
))
835 if (s
->state
== SWAP_ACTIVATING
)
838 assert(IN_SET(s
->state
, SWAP_DEAD
, SWAP_FAILED
));
840 if (detect_container() > 0)
843 /* If there's a job for another swap unit for the same node
844 * running, then let's not dispatch this one for now, and wait
845 * until that other job has finished. */
846 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
847 if (UNIT(other
)->job
&& UNIT(other
)->job
->state
== JOB_RUNNING
)
850 r
= unit_start_limit_test(u
);
852 swap_enter_dead(s
, SWAP_FAILURE_START_LIMIT_HIT
);
856 r
= unit_acquire_invocation_id(u
);
860 s
->result
= SWAP_SUCCESS
;
862 u
->reset_accounting
= true;
864 swap_enter_activating(s
);
868 static int swap_stop(Unit
*u
) {
875 case SWAP_DEACTIVATING
:
876 case SWAP_DEACTIVATING_SIGTERM
:
877 case SWAP_DEACTIVATING_SIGKILL
:
881 case SWAP_ACTIVATING
:
882 case SWAP_ACTIVATING_DONE
:
883 /* There's a control process pending, directly enter kill mode */
884 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_SUCCESS
);
888 if (detect_container() > 0)
891 swap_enter_deactivating(s
);
895 assert_not_reached("Unexpected state.");
899 static int swap_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
906 unit_serialize_item(u
, f
, "state", swap_state_to_string(s
->state
));
907 unit_serialize_item(u
, f
, "result", swap_result_to_string(s
->result
));
909 if (s
->control_pid
> 0)
910 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
912 if (s
->control_command_id
>= 0)
913 unit_serialize_item(u
, f
, "control-command", swap_exec_command_to_string(s
->control_command_id
));
918 static int swap_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
924 if (streq(key
, "state")) {
927 state
= swap_state_from_string(value
);
929 log_unit_debug(u
, "Failed to parse state value: %s", value
);
931 s
->deserialized_state
= state
;
932 } else if (streq(key
, "result")) {
935 f
= swap_result_from_string(value
);
937 log_unit_debug(u
, "Failed to parse result value: %s", value
);
938 else if (f
!= SWAP_SUCCESS
)
940 } else if (streq(key
, "control-pid")) {
943 if (parse_pid(value
, &pid
) < 0)
944 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
946 s
->control_pid
= pid
;
948 } else if (streq(key
, "control-command")) {
951 id
= swap_exec_command_from_string(value
);
953 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
955 s
->control_command_id
= id
;
956 s
->control_command
= s
->exec_command
+ id
;
959 log_unit_debug(u
, "Unknown serialization key: %s", key
);
964 _pure_
static UnitActiveState
swap_active_state(Unit
*u
) {
967 return state_translation_table
[SWAP(u
)->state
];
970 _pure_
static const char *swap_sub_state_to_string(Unit
*u
) {
973 return swap_state_to_string(SWAP(u
)->state
);
976 _pure_
static bool swap_may_gc(Unit
*u
) {
981 if (s
->from_proc_swaps
)
987 static void swap_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
994 if (pid
!= s
->control_pid
)
999 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
1001 else if (code
== CLD_EXITED
)
1002 f
= SWAP_FAILURE_EXIT_CODE
;
1003 else if (code
== CLD_KILLED
)
1004 f
= SWAP_FAILURE_SIGNAL
;
1005 else if (code
== CLD_DUMPED
)
1006 f
= SWAP_FAILURE_CORE_DUMP
;
1008 assert_not_reached("Unknown code");
1010 if (s
->result
== SWAP_SUCCESS
)
1013 if (s
->control_command
) {
1014 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
1016 s
->control_command
= NULL
;
1017 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1020 log_unit_full(u
, f
== SWAP_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
1021 "Swap process exited, code=%s status=%i", sigchld_code_to_string(code
), status
);
1025 case SWAP_ACTIVATING
:
1026 case SWAP_ACTIVATING_DONE
:
1028 if (f
== SWAP_SUCCESS
|| s
->from_proc_swaps
)
1029 swap_enter_active(s
, f
);
1031 swap_enter_dead(s
, f
);
1034 case SWAP_DEACTIVATING
:
1035 case SWAP_DEACTIVATING_SIGKILL
:
1036 case SWAP_DEACTIVATING_SIGTERM
:
1038 swap_enter_dead_or_active(s
, f
);
1042 assert_not_reached("Uh, control process died at wrong time.");
1045 /* Notify clients about changed exit status */
1046 unit_add_to_dbus_queue(u
);
1049 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
1050 Swap
*s
= SWAP(userdata
);
1053 assert(s
->timer_event_source
== source
);
1057 case SWAP_ACTIVATING
:
1058 case SWAP_ACTIVATING_DONE
:
1059 log_unit_warning(UNIT(s
), "Activation timed out. Stopping.");
1060 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1063 case SWAP_DEACTIVATING
:
1064 log_unit_warning(UNIT(s
), "Deactivation timed out. Stopping.");
1065 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1068 case SWAP_DEACTIVATING_SIGTERM
:
1069 if (s
->kill_context
.send_sigkill
) {
1070 log_unit_warning(UNIT(s
), "Swap process timed out. Killing.");
1071 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_FAILURE_TIMEOUT
);
1073 log_unit_warning(UNIT(s
), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1074 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1078 case SWAP_DEACTIVATING_SIGKILL
:
1079 log_unit_warning(UNIT(s
), "Swap process still around after SIGKILL. Ignoring.");
1080 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1084 assert_not_reached("Timeout at wrong time.");
1090 static int swap_load_proc_swaps(Manager
*m
, bool set_flags
) {
1096 rewind(m
->proc_swaps
);
1098 (void) fscanf(m
->proc_swaps
, "%*s %*s %*s %*s %*s\n");
1101 _cleanup_free_
char *dev
= NULL
, *d
= NULL
;
1104 k
= fscanf(m
->proc_swaps
,
1105 "%ms " /* device/file */
1106 "%*s " /* type of swap */
1107 "%*s " /* swap size */
1109 "%i\n", /* priority */
1115 log_warning("Failed to parse /proc/swaps:%u.", i
);
1119 if (cunescape(dev
, UNESCAPE_RELAX
, &d
) < 0)
1122 device_found_node(m
, d
, DEVICE_FOUND_SWAP
, DEVICE_FOUND_SWAP
);
1124 k
= swap_process_new(m
, d
, prio
, set_flags
);
1132 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
1133 Manager
*m
= userdata
;
1138 assert(revents
& EPOLLPRI
);
1140 r
= swap_load_proc_swaps(m
, true);
1142 log_error_errno(r
, "Failed to reread /proc/swaps: %m");
1144 /* Reset flags, just in case, for late calls */
1145 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1146 Swap
*swap
= SWAP(u
);
1148 swap
->is_active
= swap
->just_activated
= false;
1154 manager_dispatch_load_queue(m
);
1156 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1157 Swap
*swap
= SWAP(u
);
1159 if (!swap
->is_active
) {
1160 /* This has just been deactivated */
1162 swap_unset_proc_swaps(swap
);
1164 switch (swap
->state
) {
1167 swap_enter_dead(swap
, SWAP_SUCCESS
);
1172 swap_set_state(swap
, swap
->state
);
1177 device_found_node(m
, swap
->what
, 0, DEVICE_FOUND_SWAP
);
1179 } else if (swap
->just_activated
) {
1181 /* New swap entry */
1183 switch (swap
->state
) {
1187 (void) unit_acquire_invocation_id(UNIT(swap
));
1188 swap_enter_active(swap
, SWAP_SUCCESS
);
1191 case SWAP_ACTIVATING
:
1192 swap_set_state(swap
, SWAP_ACTIVATING_DONE
);
1196 /* Nothing really changed, but let's
1197 * issue an notification call
1198 * nonetheless, in case somebody is
1199 * waiting for this. */
1200 swap_set_state(swap
, swap
->state
);
1205 /* Reset the flags for later calls */
1206 swap
->is_active
= swap
->just_activated
= false;
1212 static Unit
*swap_following(Unit
*u
) {
1214 Swap
*other
, *first
= NULL
;
1218 /* If the user configured the swap through /etc/fstab or
1219 * a device unit, follow that. */
1221 if (s
->from_fragment
)
1224 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
1225 if (other
->from_fragment
)
1228 /* Otherwise, make everybody follow the unit that's named after
1229 * the swap device in the kernel */
1231 if (streq_ptr(s
->what
, s
->devnode
))
1234 LIST_FOREACH_AFTER(same_devnode
, other
, s
)
1235 if (streq_ptr(other
->what
, other
->devnode
))
1238 LIST_FOREACH_BEFORE(same_devnode
, other
, s
) {
1239 if (streq_ptr(other
->what
, other
->devnode
))
1245 /* Fall back to the first on the list */
1249 static int swap_following_set(Unit
*u
, Set
**_set
) {
1250 Swap
*s
= SWAP(u
), *other
;
1251 _cleanup_set_free_ Set
*set
= NULL
;
1257 if (LIST_JUST_US(same_devnode
, s
)) {
1262 set
= set_new(NULL
);
1266 LIST_FOREACH_OTHERS(same_devnode
, other
, s
) {
1267 r
= set_put(set
, other
);
1272 *_set
= TAKE_PTR(set
);
1276 static void swap_shutdown(Manager
*m
) {
1279 m
->swap_event_source
= sd_event_source_unref(m
->swap_event_source
);
1280 m
->proc_swaps
= safe_fclose(m
->proc_swaps
);
1281 m
->swaps_by_devnode
= hashmap_free(m
->swaps_by_devnode
);
1284 static void swap_enumerate(Manager
*m
) {
1289 if (!m
->proc_swaps
) {
1290 m
->proc_swaps
= fopen("/proc/swaps", "re");
1291 if (!m
->proc_swaps
) {
1292 if (errno
== ENOENT
)
1293 log_debug_errno(errno
, "Not swap enabled, skipping enumeration.");
1295 log_warning_errno(errno
, "Failed to open /proc/swaps, ignoring: %m");
1300 r
= sd_event_add_io(m
->event
, &m
->swap_event_source
, fileno(m
->proc_swaps
), EPOLLPRI
, swap_dispatch_io
, m
);
1302 log_error_errno(r
, "Failed to watch /proc/swaps: %m");
1306 /* Dispatch this before we dispatch SIGCHLD, so that
1307 * we always get the events from /proc/swaps before
1308 * the SIGCHLD of /sbin/swapon. */
1309 r
= sd_event_source_set_priority(m
->swap_event_source
, SD_EVENT_PRIORITY_NORMAL
-10);
1311 log_error_errno(r
, "Failed to change /proc/swaps priority: %m");
1315 (void) sd_event_source_set_description(m
->swap_event_source
, "swap-proc");
1318 r
= swap_load_proc_swaps(m
, false);
1328 int swap_process_device_new(Manager
*m
, struct udev_device
*dev
) {
1329 struct udev_list_entry
*item
= NULL
, *first
= NULL
;
1330 _cleanup_free_
char *e
= NULL
;
1338 dn
= udev_device_get_devnode(dev
);
1342 r
= unit_name_from_path(dn
, ".swap", &e
);
1346 u
= manager_get_unit(m
, e
);
1348 r
= swap_set_devnode(SWAP(u
), dn
);
1350 first
= udev_device_get_devlinks_list_entry(dev
);
1351 udev_list_entry_foreach(item
, first
) {
1352 _cleanup_free_
char *n
= NULL
;
1355 q
= unit_name_from_path(udev_list_entry_get_name(item
), ".swap", &n
);
1359 u
= manager_get_unit(m
, n
);
1361 q
= swap_set_devnode(SWAP(u
), dn
);
1370 int swap_process_device_remove(Manager
*m
, struct udev_device
*dev
) {
1375 dn
= udev_device_get_devnode(dev
);
1379 while ((s
= hashmap_get(m
->swaps_by_devnode
, dn
))) {
1382 q
= swap_set_devnode(s
, NULL
);
1390 static void swap_reset_failed(Unit
*u
) {
1395 if (s
->state
== SWAP_FAILED
)
1396 swap_set_state(s
, SWAP_DEAD
);
1398 s
->result
= SWAP_SUCCESS
;
1401 static int swap_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
1402 return unit_kill_common(u
, who
, signo
, -1, SWAP(u
)->control_pid
, error
);
1405 static int swap_get_timeout(Unit
*u
, usec_t
*timeout
) {
1410 if (!s
->timer_event_source
)
1413 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
1416 if (t
== USEC_INFINITY
)
1423 static bool swap_supported(void) {
1424 static int supported
= -1;
1426 /* If swap support is not available in the kernel, or we are
1427 * running in a container we don't support swap units, and any
1428 * attempts to starting one should fail immediately. */
1432 access("/proc/swaps", F_OK
) >= 0 &&
1433 detect_container() <= 0;
1438 static int swap_control_pid(Unit
*u
) {
1443 return s
->control_pid
;
1446 static const char* const swap_exec_command_table
[_SWAP_EXEC_COMMAND_MAX
] = {
1447 [SWAP_EXEC_ACTIVATE
] = "ExecActivate",
1448 [SWAP_EXEC_DEACTIVATE
] = "ExecDeactivate",
1451 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command
, SwapExecCommand
);
1453 static const char* const swap_result_table
[_SWAP_RESULT_MAX
] = {
1454 [SWAP_SUCCESS
] = "success",
1455 [SWAP_FAILURE_RESOURCES
] = "resources",
1456 [SWAP_FAILURE_TIMEOUT
] = "timeout",
1457 [SWAP_FAILURE_EXIT_CODE
] = "exit-code",
1458 [SWAP_FAILURE_SIGNAL
] = "signal",
1459 [SWAP_FAILURE_CORE_DUMP
] = "core-dump",
1460 [SWAP_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
1463 DEFINE_STRING_TABLE_LOOKUP(swap_result
, SwapResult
);
1465 const UnitVTable swap_vtable
= {
1466 .object_size
= sizeof(Swap
),
1467 .exec_context_offset
= offsetof(Swap
, exec_context
),
1468 .cgroup_context_offset
= offsetof(Swap
, cgroup_context
),
1469 .kill_context_offset
= offsetof(Swap
, kill_context
),
1470 .exec_runtime_offset
= offsetof(Swap
, exec_runtime
),
1471 .dynamic_creds_offset
= offsetof(Swap
, dynamic_creds
),
1477 .private_section
= "Swap",
1483 .coldplug
= swap_coldplug
,
1487 .start
= swap_start
,
1492 .get_timeout
= swap_get_timeout
,
1494 .serialize
= swap_serialize
,
1495 .deserialize_item
= swap_deserialize_item
,
1497 .active_state
= swap_active_state
,
1498 .sub_state_to_string
= swap_sub_state_to_string
,
1500 .may_gc
= swap_may_gc
,
1502 .sigchld_event
= swap_sigchld_event
,
1504 .reset_failed
= swap_reset_failed
,
1506 .control_pid
= swap_control_pid
,
1508 .bus_vtable
= bus_swap_vtable
,
1509 .bus_set_property
= bus_swap_set_property
,
1510 .bus_commit_properties
= bus_swap_commit_properties
,
1512 .following
= swap_following
,
1513 .following_set
= swap_following_set
,
1515 .enumerate
= swap_enumerate
,
1516 .shutdown
= swap_shutdown
,
1517 .supported
= swap_supported
,
1519 .status_message_formats
= {
1520 .starting_stopping
= {
1521 [0] = "Activating swap %s...",
1522 [1] = "Deactivating swap %s...",
1524 .finished_start_job
= {
1525 [JOB_DONE
] = "Activated swap %s.",
1526 [JOB_FAILED
] = "Failed to activate swap %s.",
1527 [JOB_TIMEOUT
] = "Timed out activating swap %s.",
1529 .finished_stop_job
= {
1530 [JOB_DONE
] = "Deactivated swap %s.",
1531 [JOB_FAILED
] = "Failed deactivating swap %s.",
1532 [JOB_TIMEOUT
] = "Timed out deactivating swap %s.",