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
,
42 [SWAP_CLEANING
] = UNIT_MAINTENANCE
,
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
);
47 static int swap_process_proc_swaps(Manager
*m
);
49 static bool SWAP_STATE_WITH_PROCESS(SwapState state
) {
54 SWAP_DEACTIVATING_SIGTERM
,
55 SWAP_DEACTIVATING_SIGKILL
,
59 static void swap_unset_proc_swaps(Swap
*s
) {
62 if (!s
->from_proc_swaps
)
65 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
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
121 u
->ignore_on_isolate
= true;
124 static void swap_unwatch_control_pid(Swap
*s
) {
127 if (s
->control_pid
<= 0)
130 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
134 static void swap_done(Unit
*u
) {
139 swap_unset_proc_swaps(s
);
140 swap_set_devnode(s
, NULL
);
142 s
->what
= mfree(s
->what
);
143 s
->parameters_fragment
.what
= mfree(s
->parameters_fragment
.what
);
144 s
->parameters_fragment
.options
= mfree(s
->parameters_fragment
.options
);
146 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
147 exec_command_done_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
148 s
->control_command
= NULL
;
150 dynamic_creds_unref(&s
->dynamic_creds
);
152 swap_unwatch_control_pid(s
);
154 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
157 static int swap_arm_timer(Swap
*s
, usec_t usec
) {
162 if (s
->timer_event_source
) {
163 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
167 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
170 if (usec
== USEC_INFINITY
)
173 r
= sd_event_add_time(
174 UNIT(s
)->manager
->event
,
175 &s
->timer_event_source
,
178 swap_dispatch_timer
, s
);
182 (void) sd_event_source_set_description(s
->timer_event_source
, "swap-timer");
187 static SwapParameters
* swap_get_parameters(Swap
*s
) {
190 if (s
->from_proc_swaps
)
191 return &s
->parameters_proc_swaps
;
193 if (s
->from_fragment
)
194 return &s
->parameters_fragment
;
199 static int swap_add_device_dependencies(Swap
*s
) {
200 UnitDependencyMask mask
;
209 p
= swap_get_parameters(s
);
213 mask
= s
->from_proc_swaps
? UNIT_DEPENDENCY_PROC_SWAP
: UNIT_DEPENDENCY_FILE
;
215 if (is_device_path(p
->what
)) {
216 r
= unit_add_node_dependency(UNIT(s
), p
->what
, UNIT_REQUIRES
, mask
);
220 return unit_add_blockdev_dependency(UNIT(s
), p
->what
, mask
);
223 /* File based swap devices need to be ordered after systemd-remount-fs.service, since they might need
224 * a writable file system. */
225 return unit_add_dependency_by_name(UNIT(s
), UNIT_AFTER
, SPECIAL_REMOUNT_FS_SERVICE
, true, mask
);
228 static int swap_add_default_dependencies(Swap
*s
) {
233 if (!UNIT(s
)->default_dependencies
)
236 if (!MANAGER_IS_SYSTEM(UNIT(s
)->manager
))
239 if (detect_container() > 0)
242 /* swap units generated for the swap dev links are missing the
243 * ordering dep against the swap target. */
244 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SWAP_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
248 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_UMOUNT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
251 static int swap_verify(Swap
*s
) {
252 _cleanup_free_
char *e
= NULL
;
255 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
257 r
= unit_name_from_path(s
->what
, ".swap", &e
);
259 return log_unit_error_errno(UNIT(s
), r
, "Failed to generate unit name from path: %m");
261 if (!unit_has_name(UNIT(s
), e
)) {
262 log_unit_error(UNIT(s
), "Value of What= and unit name do not match, not loading.");
266 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
267 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.");
274 static int swap_load_devnode(Swap
*s
) {
275 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
282 if (stat(s
->what
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
285 r
= device_new_from_stat_rdev(&d
, &st
);
287 log_unit_full(UNIT(s
), r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
288 "Failed to allocate device for swap %s: %m", s
->what
);
292 if (sd_device_get_devname(d
, &p
) < 0)
295 return swap_set_devnode(s
, p
);
298 static int swap_add_extras(Swap
*s
) {
303 if (UNIT(s
)->fragment_path
)
304 s
->from_fragment
= true;
307 if (s
->parameters_fragment
.what
)
308 s
->what
= strdup(s
->parameters_fragment
.what
);
309 else if (s
->parameters_proc_swaps
.what
)
310 s
->what
= strdup(s
->parameters_proc_swaps
.what
);
312 r
= unit_name_to_path(UNIT(s
)->id
, &s
->what
);
321 path_simplify(s
->what
, false);
323 if (!UNIT(s
)->description
) {
324 r
= unit_set_description(UNIT(s
), s
->what
);
329 r
= unit_require_mounts_for(UNIT(s
), s
->what
, UNIT_DEPENDENCY_IMPLICIT
);
333 r
= swap_add_device_dependencies(s
);
337 r
= swap_load_devnode(s
);
341 r
= unit_patch_contexts(UNIT(s
));
345 r
= unit_add_exec_dependencies(UNIT(s
), &s
->exec_context
);
349 r
= unit_set_default_slice(UNIT(s
));
353 r
= swap_add_default_dependencies(s
);
360 static int swap_load(Unit
*u
) {
365 assert(u
->load_state
== UNIT_STUB
);
367 /* Load a .swap file */
368 bool fragment_optional
= s
->from_proc_swaps
;
369 r
= unit_load_fragment_and_dropin(u
, !fragment_optional
);
371 /* Add in some extras, and do so either when we successfully loaded something or when /proc/swaps is
373 if (u
->load_state
== UNIT_LOADED
|| s
->from_proc_swaps
)
374 q
= swap_add_extras(s
);
380 if (u
->load_state
!= UNIT_LOADED
)
383 return swap_verify(s
);
386 static int swap_setup_unit(
389 const char *what_proc_swaps
,
393 _cleanup_free_
char *e
= NULL
;
401 assert(what_proc_swaps
);
403 r
= unit_name_from_path(what
, ".swap", &e
);
405 return log_unit_error_errno(u
, r
, "Failed to generate unit name from path: %m");
407 u
= manager_get_unit(m
, e
);
409 SWAP(u
)->from_proc_swaps
&&
410 !path_equal(SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
))
411 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
412 "Swap %s appeared twice with different device paths %s and %s",
413 e
, SWAP(u
)->parameters_proc_swaps
.what
, what_proc_swaps
);
418 r
= unit_new_for_name(m
, sizeof(Swap
), e
, &u
);
422 SWAP(u
)->what
= strdup(what
);
423 if (!SWAP(u
)->what
) {
428 unit_add_to_load_queue(u
);
432 p
= &SWAP(u
)->parameters_proc_swaps
;
435 p
->what
= strdup(what_proc_swaps
);
442 /* The unit is definitely around now, mark it as loaded if it was previously referenced but could not be
443 * loaded. After all we can load it now, from the data in /proc/swaps. */
444 if (IN_SET(u
->load_state
, UNIT_NOT_FOUND
, UNIT_BAD_SETTING
, UNIT_ERROR
)) {
445 u
->load_state
= UNIT_LOADED
;
450 SWAP(u
)->is_active
= true;
451 SWAP(u
)->just_activated
= !SWAP(u
)->from_proc_swaps
;
454 SWAP(u
)->from_proc_swaps
= true;
456 p
->priority
= priority
;
457 p
->priority_set
= true;
459 unit_add_to_dbus_queue(u
);
463 log_unit_warning_errno(u
, r
, "Failed to load swap unit: %m");
471 static int swap_process_new(Manager
*m
, const char *device
, int prio
, bool set_flags
) {
472 _cleanup_(sd_device_unrefp
) sd_device
*d
= NULL
;
473 const char *dn
, *devlink
;
474 struct stat st
, st_link
;
479 r
= swap_setup_unit(m
, device
, device
, prio
, set_flags
);
483 /* If this is a block device, then let's add duplicates for
484 * all other names of this block device */
485 if (stat(device
, &st
) < 0 || !S_ISBLK(st
.st_mode
))
488 r
= device_new_from_stat_rdev(&d
, &st
);
490 log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
491 "Failed to allocate device for swap %s: %m", device
);
495 /* Add the main device node */
496 if (sd_device_get_devname(d
, &dn
) >= 0 && !streq(dn
, device
))
497 swap_setup_unit(m
, dn
, device
, prio
, set_flags
);
499 /* Add additional units for all symlinks */
500 FOREACH_DEVICE_DEVLINK(d
, devlink
) {
502 /* Don't bother with the /dev/block links */
503 if (streq(devlink
, device
))
506 if (path_startswith(devlink
, "/dev/block/"))
509 if (stat(devlink
, &st_link
) >= 0 &&
510 (!S_ISBLK(st_link
.st_mode
) ||
511 st_link
.st_rdev
!= st
.st_rdev
))
514 swap_setup_unit(m
, devlink
, device
, prio
, set_flags
);
520 static void swap_set_state(Swap
*s
, SwapState state
) {
526 if (s
->state
!= state
)
527 bus_unit_send_pending_change_signal(UNIT(s
), false);
529 old_state
= s
->state
;
532 if (!SWAP_STATE_WITH_PROCESS(state
)) {
533 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
534 swap_unwatch_control_pid(s
);
535 s
->control_command
= NULL
;
536 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
539 if (state
!= old_state
)
540 log_unit_debug(UNIT(s
), "Changed %s -> %s", swap_state_to_string(old_state
), swap_state_to_string(state
));
542 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
544 /* If there other units for the same device node have a job
545 queued it might be worth checking again if it is runnable
546 now. This is necessary, since swap_start() refuses
547 operation with EAGAIN if there's already another job for
548 the same device node queued. */
549 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
550 if (UNIT(other
)->job
)
551 job_add_to_run_queue(UNIT(other
)->job
);
554 static int swap_coldplug(Unit
*u
) {
556 SwapState new_state
= SWAP_DEAD
;
560 assert(s
->state
== SWAP_DEAD
);
562 if (s
->deserialized_state
!= s
->state
)
563 new_state
= s
->deserialized_state
;
564 else if (s
->from_proc_swaps
)
565 new_state
= SWAP_ACTIVE
;
567 if (new_state
== s
->state
)
570 if (s
->control_pid
> 0 &&
571 pid_is_unwaited(s
->control_pid
) &&
572 SWAP_STATE_WITH_PROCESS(new_state
)) {
574 r
= unit_watch_pid(UNIT(s
), s
->control_pid
, false);
578 r
= swap_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
583 if (!IN_SET(new_state
, SWAP_DEAD
, SWAP_FAILED
)) {
584 (void) unit_setup_dynamic_creds(u
);
585 (void) unit_setup_exec_runtime(u
);
588 swap_set_state(s
, new_state
);
592 static void swap_dump(Unit
*u
, FILE *f
, const char *prefix
) {
593 char buf
[FORMAT_TIMESPAN_MAX
];
600 if (s
->from_proc_swaps
)
601 p
= &s
->parameters_proc_swaps
;
602 else if (s
->from_fragment
)
603 p
= &s
->parameters_fragment
;
610 "%sClean Result: %s\n"
612 "%sFrom /proc/swaps: %s\n"
613 "%sFrom fragment: %s\n",
614 prefix
, swap_state_to_string(s
->state
),
615 prefix
, swap_result_to_string(s
->result
),
616 prefix
, swap_result_to_string(s
->clean_result
),
618 prefix
, yes_no(s
->from_proc_swaps
),
619 prefix
, yes_no(s
->from_fragment
));
622 fprintf(f
, "%sDevice Node: %s\n", prefix
, s
->devnode
);
629 prefix
, strempty(p
->options
));
632 "%sTimeoutSec: %s\n",
633 prefix
, format_timespan(buf
, sizeof(buf
), s
->timeout_usec
, USEC_PER_SEC
));
635 if (s
->control_pid
> 0)
637 "%sControl PID: "PID_FMT
"\n",
638 prefix
, s
->control_pid
);
640 exec_context_dump(&s
->exec_context
, f
, prefix
);
641 kill_context_dump(&s
->kill_context
, f
, prefix
);
642 cgroup_context_dump(UNIT(s
), f
, prefix
);
645 static int swap_spawn(Swap
*s
, ExecCommand
*c
, pid_t
*_pid
) {
647 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
648 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
661 r
= unit_prepare_exec(UNIT(s
));
665 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
669 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
673 r
= exec_spawn(UNIT(s
),
683 r
= unit_watch_pid(UNIT(s
), pid
, true);
692 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
697 static void swap_enter_dead(Swap
*s
, SwapResult f
) {
700 if (s
->result
== SWAP_SUCCESS
)
703 unit_log_result(UNIT(s
), s
->result
== SWAP_SUCCESS
, swap_result_to_string(s
->result
));
704 swap_set_state(s
, s
->result
!= SWAP_SUCCESS
? SWAP_FAILED
: SWAP_DEAD
);
706 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
708 unit_destroy_runtime_directory(UNIT(s
), &s
->exec_context
);
710 unit_unref_uid_gid(UNIT(s
), true);
712 dynamic_creds_destroy(&s
->dynamic_creds
);
715 static void swap_enter_active(Swap
*s
, SwapResult f
) {
718 if (s
->result
== SWAP_SUCCESS
)
721 swap_set_state(s
, SWAP_ACTIVE
);
724 static void swap_enter_dead_or_active(Swap
*s
, SwapResult f
) {
727 if (s
->from_proc_swaps
) {
730 swap_enter_active(s
, f
);
732 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
733 if (UNIT(other
)->job
)
734 swap_enter_dead_or_active(other
, f
);
736 swap_enter_dead(s
, f
);
739 static int state_to_kill_operation(Swap
*s
, SwapState state
) {
740 if (state
== SWAP_DEACTIVATING_SIGTERM
) {
741 if (unit_has_job_type(UNIT(s
), JOB_RESTART
))
744 return KILL_TERMINATE
;
750 static void swap_enter_signal(Swap
*s
, SwapState state
, SwapResult f
) {
755 if (s
->result
== SWAP_SUCCESS
)
758 r
= unit_kill_context(UNIT(s
),
760 state_to_kill_operation(s
, state
),
768 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
772 swap_set_state(s
, state
);
773 } else if (state
== SWAP_DEACTIVATING_SIGTERM
&& s
->kill_context
.send_sigkill
)
774 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
776 swap_enter_dead_or_active(s
, SWAP_SUCCESS
);
781 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
782 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
785 static void swap_enter_activating(Swap
*s
) {
786 _cleanup_free_
char *opts
= NULL
;
791 unit_warn_leftover_processes(UNIT(s
));
793 s
->control_command_id
= SWAP_EXEC_ACTIVATE
;
794 s
->control_command
= s
->exec_command
+ SWAP_EXEC_ACTIVATE
;
796 if (s
->from_fragment
) {
799 r
= fstab_find_pri(s
->parameters_fragment
.options
, &priority
);
801 log_unit_warning_errno(UNIT(s
), r
, "Failed to parse swap priority \"%s\", ignoring: %m", s
->parameters_fragment
.options
);
802 else if (r
> 0 && s
->parameters_fragment
.priority_set
)
803 log_unit_warning(UNIT(s
), "Duplicate swap priority configuration by Priority= and Options= fields.");
805 if (r
<= 0 && s
->parameters_fragment
.priority_set
) {
806 if (s
->parameters_fragment
.options
)
807 r
= asprintf(&opts
, "%s,pri=%i", s
->parameters_fragment
.options
, s
->parameters_fragment
.priority
);
809 r
= asprintf(&opts
, "pri=%i", s
->parameters_fragment
.priority
);
817 r
= exec_command_set(s
->control_command
, "/sbin/swapon", NULL
);
821 if (s
->parameters_fragment
.options
|| opts
) {
822 r
= exec_command_append(s
->control_command
, "-o",
823 opts
?: s
->parameters_fragment
.options
, NULL
);
828 r
= exec_command_append(s
->control_command
, s
->what
, NULL
);
832 swap_unwatch_control_pid(s
);
834 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
838 swap_set_state(s
, SWAP_ACTIVATING
);
842 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapon' task: %m");
843 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
846 static void swap_enter_deactivating(Swap
*s
) {
851 s
->control_command_id
= SWAP_EXEC_DEACTIVATE
;
852 s
->control_command
= s
->exec_command
+ SWAP_EXEC_DEACTIVATE
;
854 r
= exec_command_set(s
->control_command
,
861 swap_unwatch_control_pid(s
);
863 r
= swap_spawn(s
, s
->control_command
, &s
->control_pid
);
867 swap_set_state(s
, SWAP_DEACTIVATING
);
872 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'swapoff' task: %m");
873 swap_enter_dead_or_active(s
, SWAP_FAILURE_RESOURCES
);
876 static void swap_cycle_clear(Swap
*s
) {
879 s
->result
= SWAP_SUCCESS
;
880 exec_command_reset_status_array(s
->exec_command
, _SWAP_EXEC_COMMAND_MAX
);
881 UNIT(s
)->reset_accounting
= true;
884 static int swap_start(Unit
*u
) {
885 Swap
*s
= SWAP(u
), *other
;
890 /* We cannot fulfill this request right now, try again later please! */
893 SWAP_DEACTIVATING_SIGTERM
,
894 SWAP_DEACTIVATING_SIGKILL
,
899 if (s
->state
== SWAP_ACTIVATING
)
902 assert(IN_SET(s
->state
, SWAP_DEAD
, SWAP_FAILED
));
904 if (detect_container() > 0)
907 /* If there's a job for another swap unit for the same node
908 * running, then let's not dispatch this one for now, and wait
909 * until that other job has finished. */
910 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
911 if (UNIT(other
)->job
&& UNIT(other
)->job
->state
== JOB_RUNNING
)
914 r
= unit_test_start_limit(u
);
916 swap_enter_dead(s
, SWAP_FAILURE_START_LIMIT_HIT
);
920 r
= unit_acquire_invocation_id(u
);
925 swap_enter_activating(s
);
929 static int swap_stop(Unit
*u
) {
936 case SWAP_DEACTIVATING
:
937 case SWAP_DEACTIVATING_SIGTERM
:
938 case SWAP_DEACTIVATING_SIGKILL
:
942 case SWAP_ACTIVATING
:
943 case SWAP_ACTIVATING_DONE
:
944 /* There's a control process pending, directly enter kill mode */
945 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_SUCCESS
);
949 if (detect_container() > 0)
952 swap_enter_deactivating(s
);
956 /* If we are currently cleaning, then abort it, brutally. */
957 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_SUCCESS
);
961 assert_not_reached("Unexpected state.");
965 static int swap_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
972 (void) serialize_item(f
, "state", swap_state_to_string(s
->state
));
973 (void) serialize_item(f
, "result", swap_result_to_string(s
->result
));
975 if (s
->control_pid
> 0)
976 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
);
978 if (s
->control_command_id
>= 0)
979 (void) serialize_item(f
, "control-command", swap_exec_command_to_string(s
->control_command_id
));
984 static int swap_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
990 if (streq(key
, "state")) {
993 state
= swap_state_from_string(value
);
995 log_unit_debug(u
, "Failed to parse state value: %s", value
);
997 s
->deserialized_state
= state
;
998 } else if (streq(key
, "result")) {
1001 f
= swap_result_from_string(value
);
1003 log_unit_debug(u
, "Failed to parse result value: %s", value
);
1004 else if (f
!= SWAP_SUCCESS
)
1006 } else if (streq(key
, "control-pid")) {
1009 if (parse_pid(value
, &pid
) < 0)
1010 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
1012 s
->control_pid
= pid
;
1014 } else if (streq(key
, "control-command")) {
1017 id
= swap_exec_command_from_string(value
);
1019 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
1021 s
->control_command_id
= id
;
1022 s
->control_command
= s
->exec_command
+ id
;
1025 log_unit_debug(u
, "Unknown serialization key: %s", key
);
1030 _pure_
static UnitActiveState
swap_active_state(Unit
*u
) {
1033 return state_translation_table
[SWAP(u
)->state
];
1036 _pure_
static const char *swap_sub_state_to_string(Unit
*u
) {
1039 return swap_state_to_string(SWAP(u
)->state
);
1042 _pure_
static bool swap_may_gc(Unit
*u
) {
1047 if (s
->from_proc_swaps
)
1053 static void swap_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
1060 if (pid
!= s
->control_pid
)
1063 /* Let's scan /proc/swaps before we process SIGCHLD. For the reasoning see the similar code in
1065 (void) swap_process_proc_swaps(u
->manager
);
1069 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
1071 else if (code
== CLD_EXITED
)
1072 f
= SWAP_FAILURE_EXIT_CODE
;
1073 else if (code
== CLD_KILLED
)
1074 f
= SWAP_FAILURE_SIGNAL
;
1075 else if (code
== CLD_DUMPED
)
1076 f
= SWAP_FAILURE_CORE_DUMP
;
1078 assert_not_reached("Unknown code");
1080 if (s
->result
== SWAP_SUCCESS
)
1083 if (s
->control_command
) {
1084 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
1086 s
->control_command
= NULL
;
1087 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1090 unit_log_process_exit(
1093 swap_exec_command_to_string(s
->control_command_id
),
1099 case SWAP_ACTIVATING
:
1100 case SWAP_ACTIVATING_DONE
:
1102 if (f
== SWAP_SUCCESS
|| s
->from_proc_swaps
)
1103 swap_enter_active(s
, f
);
1105 swap_enter_dead(s
, f
);
1108 case SWAP_DEACTIVATING
:
1109 case SWAP_DEACTIVATING_SIGKILL
:
1110 case SWAP_DEACTIVATING_SIGTERM
:
1112 swap_enter_dead_or_active(s
, f
);
1116 if (s
->clean_result
== SWAP_SUCCESS
)
1117 s
->clean_result
= f
;
1119 swap_enter_dead(s
, SWAP_SUCCESS
);
1123 assert_not_reached("Uh, control process died at wrong time.");
1126 /* Notify clients about changed exit status */
1127 unit_add_to_dbus_queue(u
);
1130 static int swap_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
1131 Swap
*s
= SWAP(userdata
);
1134 assert(s
->timer_event_source
== source
);
1138 case SWAP_ACTIVATING
:
1139 case SWAP_ACTIVATING_DONE
:
1140 log_unit_warning(UNIT(s
), "Activation timed out. Stopping.");
1141 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1144 case SWAP_DEACTIVATING
:
1145 log_unit_warning(UNIT(s
), "Deactivation timed out. Stopping.");
1146 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGTERM
, SWAP_FAILURE_TIMEOUT
);
1149 case SWAP_DEACTIVATING_SIGTERM
:
1150 if (s
->kill_context
.send_sigkill
) {
1151 log_unit_warning(UNIT(s
), "Swap process timed out. Killing.");
1152 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, SWAP_FAILURE_TIMEOUT
);
1154 log_unit_warning(UNIT(s
), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1155 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1159 case SWAP_DEACTIVATING_SIGKILL
:
1160 log_unit_warning(UNIT(s
), "Swap process still around after SIGKILL. Ignoring.");
1161 swap_enter_dead_or_active(s
, SWAP_FAILURE_TIMEOUT
);
1165 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
1167 if (s
->clean_result
== SWAP_SUCCESS
)
1168 s
->clean_result
= SWAP_FAILURE_TIMEOUT
;
1170 swap_enter_signal(s
, SWAP_DEACTIVATING_SIGKILL
, 0);
1174 assert_not_reached("Timeout at wrong time.");
1180 static int swap_load_proc_swaps(Manager
*m
, bool set_flags
) {
1185 rewind(m
->proc_swaps
);
1187 (void) fscanf(m
->proc_swaps
, "%*s %*s %*s %*s %*s\n");
1190 _cleanup_free_
char *dev
= NULL
, *d
= NULL
;
1193 k
= fscanf(m
->proc_swaps
,
1194 "%ms " /* device/file */
1195 "%*s " /* type of swap */
1196 "%*s " /* swap size */
1198 "%i\n", /* priority */
1204 log_warning("Failed to parse /proc/swaps:%u.", i
);
1208 if (cunescape(dev
, UNESCAPE_RELAX
, &d
) < 0)
1211 device_found_node(m
, d
, DEVICE_FOUND_SWAP
, DEVICE_FOUND_SWAP
);
1213 (void) swap_process_new(m
, d
, prio
, set_flags
);
1219 static int swap_process_proc_swaps(Manager
*m
) {
1225 r
= swap_load_proc_swaps(m
, true);
1227 log_error_errno(r
, "Failed to reread /proc/swaps: %m");
1229 /* Reset flags, just in case, for late calls */
1230 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1231 Swap
*swap
= SWAP(u
);
1233 swap
->is_active
= swap
->just_activated
= false;
1239 manager_dispatch_load_queue(m
);
1241 LIST_FOREACH(units_by_type
, u
, m
->units_by_type
[UNIT_SWAP
]) {
1242 Swap
*swap
= SWAP(u
);
1244 if (!swap
->is_active
) {
1246 swap_unset_proc_swaps(swap
);
1248 switch (swap
->state
) {
1251 /* This has just been deactivated */
1252 swap_enter_dead(swap
, SWAP_SUCCESS
);
1257 swap_set_state(swap
, swap
->state
);
1262 device_found_node(m
, swap
->what
, 0, DEVICE_FOUND_SWAP
);
1264 } else if (swap
->just_activated
) {
1266 /* New swap entry */
1268 switch (swap
->state
) {
1272 (void) unit_acquire_invocation_id(u
);
1273 swap_cycle_clear(swap
);
1274 swap_enter_active(swap
, SWAP_SUCCESS
);
1277 case SWAP_ACTIVATING
:
1278 swap_set_state(swap
, SWAP_ACTIVATING_DONE
);
1282 /* Nothing really changed, but let's
1283 * issue an notification call
1284 * nonetheless, in case somebody is
1285 * waiting for this. */
1286 swap_set_state(swap
, swap
->state
);
1291 /* Reset the flags for later calls */
1292 swap
->is_active
= swap
->just_activated
= false;
1298 static int swap_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
1299 Manager
*m
= userdata
;
1302 assert(revents
& EPOLLPRI
);
1304 return swap_process_proc_swaps(m
);
1307 static Unit
*swap_following(Unit
*u
) {
1309 Swap
*other
, *first
= NULL
;
1313 /* If the user configured the swap through /etc/fstab or
1314 * a device unit, follow that. */
1316 if (s
->from_fragment
)
1319 LIST_FOREACH_OTHERS(same_devnode
, other
, s
)
1320 if (other
->from_fragment
)
1323 /* Otherwise, make everybody follow the unit that's named after
1324 * the swap device in the kernel */
1326 if (streq_ptr(s
->what
, s
->devnode
))
1329 LIST_FOREACH_AFTER(same_devnode
, other
, s
)
1330 if (streq_ptr(other
->what
, other
->devnode
))
1333 LIST_FOREACH_BEFORE(same_devnode
, other
, s
) {
1334 if (streq_ptr(other
->what
, other
->devnode
))
1340 /* Fall back to the first on the list */
1344 static int swap_following_set(Unit
*u
, Set
**_set
) {
1345 Swap
*s
= SWAP(u
), *other
;
1346 _cleanup_set_free_ Set
*set
= NULL
;
1352 if (LIST_JUST_US(same_devnode
, s
)) {
1357 set
= set_new(NULL
);
1361 LIST_FOREACH_OTHERS(same_devnode
, other
, s
) {
1362 r
= set_put(set
, other
);
1367 *_set
= TAKE_PTR(set
);
1371 static void swap_shutdown(Manager
*m
) {
1374 m
->swap_event_source
= sd_event_source_unref(m
->swap_event_source
);
1375 m
->proc_swaps
= safe_fclose(m
->proc_swaps
);
1376 m
->swaps_by_devnode
= hashmap_free(m
->swaps_by_devnode
);
1379 static void swap_enumerate(Manager
*m
) {
1384 if (!m
->proc_swaps
) {
1385 m
->proc_swaps
= fopen("/proc/swaps", "re");
1386 if (!m
->proc_swaps
) {
1387 if (errno
== ENOENT
)
1388 log_debug_errno(errno
, "Not swap enabled, skipping enumeration.");
1390 log_warning_errno(errno
, "Failed to open /proc/swaps, ignoring: %m");
1395 r
= sd_event_add_io(m
->event
, &m
->swap_event_source
, fileno(m
->proc_swaps
), EPOLLPRI
, swap_dispatch_io
, m
);
1397 log_error_errno(r
, "Failed to watch /proc/swaps: %m");
1401 /* Dispatch this before we dispatch SIGCHLD, so that
1402 * we always get the events from /proc/swaps before
1403 * the SIGCHLD of /sbin/swapon. */
1404 r
= sd_event_source_set_priority(m
->swap_event_source
, SD_EVENT_PRIORITY_NORMAL
-10);
1406 log_error_errno(r
, "Failed to change /proc/swaps priority: %m");
1410 (void) sd_event_source_set_description(m
->swap_event_source
, "swap-proc");
1413 r
= swap_load_proc_swaps(m
, false);
1423 int swap_process_device_new(Manager
*m
, sd_device
*dev
) {
1424 _cleanup_free_
char *e
= NULL
;
1425 const char *dn
, *devlink
;
1432 r
= sd_device_get_devname(dev
, &dn
);
1436 r
= unit_name_from_path(dn
, ".swap", &e
);
1440 u
= manager_get_unit(m
, e
);
1442 r
= swap_set_devnode(SWAP(u
), dn
);
1444 FOREACH_DEVICE_DEVLINK(dev
, devlink
) {
1445 _cleanup_free_
char *n
= NULL
;
1448 q
= unit_name_from_path(devlink
, ".swap", &n
);
1452 u
= manager_get_unit(m
, n
);
1454 q
= swap_set_devnode(SWAP(u
), dn
);
1463 int swap_process_device_remove(Manager
*m
, sd_device
*dev
) {
1468 r
= sd_device_get_devname(dev
, &dn
);
1472 while ((s
= hashmap_get(m
->swaps_by_devnode
, dn
))) {
1475 q
= swap_set_devnode(s
, NULL
);
1483 static void swap_reset_failed(Unit
*u
) {
1488 if (s
->state
== SWAP_FAILED
)
1489 swap_set_state(s
, SWAP_DEAD
);
1491 s
->result
= SWAP_SUCCESS
;
1492 s
->clean_result
= SWAP_SUCCESS
;
1495 static int swap_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
1496 return unit_kill_common(u
, who
, signo
, -1, SWAP(u
)->control_pid
, error
);
1499 static int swap_get_timeout(Unit
*u
, usec_t
*timeout
) {
1504 if (!s
->timer_event_source
)
1507 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
1510 if (t
== USEC_INFINITY
)
1517 static bool swap_supported(void) {
1518 static int supported
= -1;
1520 /* If swap support is not available in the kernel, or we are
1521 * running in a container we don't support swap units, and any
1522 * attempts to starting one should fail immediately. */
1526 access("/proc/swaps", F_OK
) >= 0 &&
1527 detect_container() <= 0;
1532 static int swap_control_pid(Unit
*u
) {
1537 return s
->control_pid
;
1540 static int swap_clean(Unit
*u
, ExecCleanMask mask
) {
1541 _cleanup_strv_free_
char **l
= NULL
;
1548 if (s
->state
!= SWAP_DEAD
)
1551 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
1555 if (strv_isempty(l
))
1558 swap_unwatch_control_pid(s
);
1559 s
->clean_result
= SWAP_SUCCESS
;
1560 s
->control_command
= NULL
;
1561 s
->control_command_id
= _SWAP_EXEC_COMMAND_INVALID
;
1563 r
= swap_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->exec_context
.timeout_clean_usec
));
1567 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
1571 swap_set_state(s
, SWAP_CLEANING
);
1576 log_unit_warning_errno(u
, r
, "Failed to initiate cleaning: %m");
1577 s
->clean_result
= SWAP_FAILURE_RESOURCES
;
1578 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1582 static int swap_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
1587 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
1590 static const char* const swap_exec_command_table
[_SWAP_EXEC_COMMAND_MAX
] = {
1591 [SWAP_EXEC_ACTIVATE
] = "ExecActivate",
1592 [SWAP_EXEC_DEACTIVATE
] = "ExecDeactivate",
1595 DEFINE_STRING_TABLE_LOOKUP(swap_exec_command
, SwapExecCommand
);
1597 static const char* const swap_result_table
[_SWAP_RESULT_MAX
] = {
1598 [SWAP_SUCCESS
] = "success",
1599 [SWAP_FAILURE_RESOURCES
] = "resources",
1600 [SWAP_FAILURE_TIMEOUT
] = "timeout",
1601 [SWAP_FAILURE_EXIT_CODE
] = "exit-code",
1602 [SWAP_FAILURE_SIGNAL
] = "signal",
1603 [SWAP_FAILURE_CORE_DUMP
] = "core-dump",
1604 [SWAP_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
1607 DEFINE_STRING_TABLE_LOOKUP(swap_result
, SwapResult
);
1609 const UnitVTable swap_vtable
= {
1610 .object_size
= sizeof(Swap
),
1611 .exec_context_offset
= offsetof(Swap
, exec_context
),
1612 .cgroup_context_offset
= offsetof(Swap
, cgroup_context
),
1613 .kill_context_offset
= offsetof(Swap
, kill_context
),
1614 .exec_runtime_offset
= offsetof(Swap
, exec_runtime
),
1615 .dynamic_creds_offset
= offsetof(Swap
, dynamic_creds
),
1621 .private_section
= "Swap",
1629 .coldplug
= swap_coldplug
,
1633 .start
= swap_start
,
1637 .clean
= swap_clean
,
1638 .can_clean
= swap_can_clean
,
1640 .get_timeout
= swap_get_timeout
,
1642 .serialize
= swap_serialize
,
1643 .deserialize_item
= swap_deserialize_item
,
1645 .active_state
= swap_active_state
,
1646 .sub_state_to_string
= swap_sub_state_to_string
,
1648 .will_restart
= unit_will_restart_default
,
1650 .may_gc
= swap_may_gc
,
1652 .sigchld_event
= swap_sigchld_event
,
1654 .reset_failed
= swap_reset_failed
,
1656 .control_pid
= swap_control_pid
,
1658 .bus_set_property
= bus_swap_set_property
,
1659 .bus_commit_properties
= bus_swap_commit_properties
,
1661 .following
= swap_following
,
1662 .following_set
= swap_following_set
,
1664 .enumerate
= swap_enumerate
,
1665 .shutdown
= swap_shutdown
,
1666 .supported
= swap_supported
,
1668 .status_message_formats
= {
1669 .starting_stopping
= {
1670 [0] = "Activating swap %s...",
1671 [1] = "Deactivating swap %s...",
1673 .finished_start_job
= {
1674 [JOB_DONE
] = "Activated swap %s.",
1675 [JOB_FAILED
] = "Failed to activate swap %s.",
1676 [JOB_TIMEOUT
] = "Timed out activating swap %s.",
1678 .finished_stop_job
= {
1679 [JOB_DONE
] = "Deactivated swap %s.",
1680 [JOB_FAILED
] = "Failed deactivating swap %s.",
1681 [JOB_TIMEOUT
] = "Timed out deactivating swap %s.",