]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/swap.c
core/mount: use set_put_strdup_full()
[thirdparty/systemd.git] / src / core / swap.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
07b0b134
ML
2
3#include <errno.h>
07b0b134
ML
4#include <sys/epoll.h>
5#include <sys/stat.h>
4f5dd394 6#include <unistd.h>
07b0b134 7
4366e598 8#include "sd-device.h"
b4bbcaa9 9
b5efdb8a 10#include "alloc-util.h"
07b0b134 11#include "dbus-swap.h"
6fcbec6f 12#include "dbus-unit.h"
4366e598 13#include "device-util.h"
57b7a260 14#include "device.h"
4f5dd394 15#include "escape.h"
9a57c629 16#include "exit-status.h"
3ffd4af2 17#include "fd-util.h"
f97b34a6 18#include "format-util.h"
4f5dd394 19#include "fstab-util.h"
6bedfcbb 20#include "parse-util.h"
9eb977db 21#include "path-util.h"
7b3e062c 22#include "process-util.h"
d68c645b 23#include "serialize.h"
4f5dd394 24#include "special.h"
8b43440b 25#include "string-table.h"
07630cea 26#include "string-util.h"
3ffd4af2 27#include "swap.h"
4f5dd394
LP
28#include "unit-name.h"
29#include "unit.h"
30#include "virt.h"
07b0b134
ML
31
32static const UnitActiveState state_translation_table[_SWAP_STATE_MAX] = {
33 [SWAP_DEAD] = UNIT_INACTIVE,
e04aad61 34 [SWAP_ACTIVATING] = UNIT_ACTIVATING,
5bcb0f2b 35 [SWAP_ACTIVATING_DONE] = UNIT_ACTIVE,
07b0b134 36 [SWAP_ACTIVE] = UNIT_ACTIVE,
e04aad61 37 [SWAP_DEACTIVATING] = UNIT_DEACTIVATING,
e04aad61
LP
38 [SWAP_DEACTIVATING_SIGTERM] = UNIT_DEACTIVATING,
39 [SWAP_DEACTIVATING_SIGKILL] = UNIT_DEACTIVATING,
a8b689b7
YW
40 [SWAP_FAILED] = UNIT_FAILED,
41 [SWAP_CLEANING] = UNIT_MAINTENANCE,
07b0b134
ML
42};
43
718db961
LP
44static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
45static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
bcce581d 46static int swap_process_proc_swaps(Manager *m);
718db961 47
dedf3719
LP
48static bool SWAP_STATE_WITH_PROCESS(SwapState state) {
49 return IN_SET(state,
50 SWAP_ACTIVATING,
51 SWAP_ACTIVATING_DONE,
52 SWAP_DEACTIVATING,
53 SWAP_DEACTIVATING_SIGTERM,
a8b689b7
YW
54 SWAP_DEACTIVATING_SIGKILL,
55 SWAP_CLEANING);
dedf3719
LP
56}
57
39c79477
ZJS
58_pure_ static UnitActiveState swap_active_state(Unit *u) {
59 assert(u);
60
61 return state_translation_table[SWAP(u)->state];
62}
63
64_pure_ static const char *swap_sub_state_to_string(Unit *u) {
65 assert(u);
66
67 return swap_state_to_string(SWAP(u)->state);
68}
69
70_pure_ static bool swap_may_gc(Unit *u) {
71 Swap *s = SWAP(u);
72
73 assert(s);
74
75 if (s->from_proc_swaps)
76 return false;
77
78 return true;
79}
80
81_pure_ static bool swap_is_extrinsic(Unit *u) {
82 assert(SWAP(u));
83
84 return MANAGER_IS_USER(u->manager);
85}
86
e04aad61 87static void swap_unset_proc_swaps(Swap *s) {
9670d583
LP
88 assert(s);
89
90 if (!s->from_proc_swaps)
91 return;
92
a1e58e8e 93 s->parameters_proc_swaps.what = mfree(s->parameters_proc_swaps.what);
9670d583
LP
94 s->from_proc_swaps = false;
95}
96
97static int swap_set_devnode(Swap *s, const char *devnode) {
df326b84 98 Hashmap *swaps;
5bcb0f2b 99 Swap *first;
9670d583 100 int r;
e04aad61
LP
101
102 assert(s);
103
548f6937 104 r = hashmap_ensure_allocated(&UNIT(s)->manager->swaps_by_devnode, &path_hash_ops);
9670d583
LP
105 if (r < 0)
106 return r;
e04aad61 107
9670d583 108 swaps = UNIT(s)->manager->swaps_by_devnode;
e04aad61 109
9670d583
LP
110 if (s->devnode) {
111 first = hashmap_get(swaps, s->devnode);
e04aad61 112
9670d583
LP
113 LIST_REMOVE(same_devnode, first, s);
114 if (first)
115 hashmap_replace(swaps, first->devnode, first);
116 else
117 hashmap_remove(swaps, s->devnode);
5bcb0f2b 118
a1e58e8e 119 s->devnode = mfree(s->devnode);
9670d583
LP
120 }
121
122 if (devnode) {
123 s->devnode = strdup(devnode);
124 if (!s->devnode)
125 return -ENOMEM;
126
127 first = hashmap_get(swaps, s->devnode);
128 LIST_PREPEND(same_devnode, first, s);
129
130 return hashmap_replace(swaps, first->devnode, first);
131 }
132
133 return 0;
e04aad61
LP
134}
135
f6cebb3b 136static void swap_init(Unit *u) {
6e620bec
LP
137 Swap *s = SWAP(u);
138
139 assert(s);
1124fe6f 140 assert(UNIT(s)->load_state == UNIT_STUB);
6e620bec 141
1f19a534 142 s->timeout_usec = u->manager->default_timeout_start_usec;
e04aad61 143
ac155bb8
MS
144 s->exec_context.std_output = u->manager->default_std_output;
145 s->exec_context.std_error = u->manager->default_std_error;
085afe36 146
e1770af8 147 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
c8f4d764 148
5bcb0f2b 149 u->ignore_on_isolate = true;
e04aad61
LP
150}
151
152static void swap_unwatch_control_pid(Swap *s) {
153 assert(s);
154
155 if (s->control_pid <= 0)
156 return;
157
8f03de53 158 unit_unwatch_pid(UNIT(s), TAKE_PID(s->control_pid));
6e620bec
LP
159}
160
4e85aff4
LP
161static void swap_done(Unit *u) {
162 Swap *s = SWAP(u);
07b0b134 163
4e85aff4 164 assert(s);
07b0b134 165
e04aad61 166 swap_unset_proc_swaps(s);
9670d583 167 swap_set_devnode(s, NULL);
e04aad61 168
a1e58e8e
LP
169 s->what = mfree(s->what);
170 s->parameters_fragment.what = mfree(s->parameters_fragment.what);
171 s->parameters_fragment.options = mfree(s->parameters_fragment.options);
86b23b07 172
e8a565cb 173 s->exec_runtime = exec_runtime_unref(s->exec_runtime, false);
e04aad61
LP
174 exec_command_done_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX);
175 s->control_command = NULL;
176
29206d46
LP
177 dynamic_creds_unref(&s->dynamic_creds);
178
e04aad61
LP
179 swap_unwatch_control_pid(s);
180
5dcadb4c 181 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
718db961
LP
182}
183
36c16a7c 184static int swap_arm_timer(Swap *s, usec_t usec) {
718db961
LP
185 int r;
186
187 assert(s);
188
718db961 189 if (s->timer_event_source) {
36c16a7c 190 r = sd_event_source_set_time(s->timer_event_source, usec);
718db961
LP
191 if (r < 0)
192 return r;
193
194 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
195 }
196
36c16a7c
LP
197 if (usec == USEC_INFINITY)
198 return 0;
199
7dfbe2e3 200 r = sd_event_add_time(
6a0f1f6d
LP
201 UNIT(s)->manager->event,
202 &s->timer_event_source,
203 CLOCK_MONOTONIC,
36c16a7c 204 usec, 0,
6a0f1f6d 205 swap_dispatch_timer, s);
7dfbe2e3
TG
206 if (r < 0)
207 return r;
208
209 (void) sd_event_source_set_description(s->timer_event_source, "swap-timer");
210
211 return 0;
07b0b134
ML
212}
213
61f9cf4e
LP
214static SwapParameters* swap_get_parameters(Swap *s) {
215 assert(s);
216
217 if (s->from_proc_swaps)
218 return &s->parameters_proc_swaps;
219
220 if (s->from_fragment)
221 return &s->parameters_fragment;
222
223 return NULL;
224}
225
eef85c4a 226static int swap_add_device_dependencies(Swap *s) {
61f9cf4e
LP
227 UnitDependencyMask mask;
228 SwapParameters *p;
44b0d1fd 229 int r;
61f9cf4e 230
173a8d04
LP
231 assert(s);
232
233 if (!s->what)
234 return 0;
235
61f9cf4e 236 p = swap_get_parameters(s);
d4a3494e 237 if (!p || !p->what)
f10af76d
LP
238 return 0;
239
61f9cf4e
LP
240 mask = s->from_proc_swaps ? UNIT_DEPENDENCY_PROC_SWAP : UNIT_DEPENDENCY_FILE;
241
44b0d1fd
LP
242 if (is_device_path(p->what)) {
243 r = unit_add_node_dependency(UNIT(s), p->what, UNIT_REQUIRES, mask);
244 if (r < 0)
245 return r;
246
247 return unit_add_blockdev_dependency(UNIT(s), p->what, mask);
248 }
9b88bb50 249
61f9cf4e
LP
250 /* File based swap devices need to be ordered after systemd-remount-fs.service, since they might need
251 * a writable file system. */
252 return unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_REMOUNT_FS_SERVICE, true, mask);
173a8d04
LP
253}
254
2edd4434 255static int swap_add_default_dependencies(Swap *s) {
8bf23dc7
FB
256 int r;
257
2edd4434
LP
258 assert(s);
259
4c9ea260
LP
260 if (!UNIT(s)->default_dependencies)
261 return 0;
262
463d0d15 263 if (!MANAGER_IS_SYSTEM(UNIT(s)->manager))
6b1dc2bd 264 return 0;
2edd4434 265
75f86906 266 if (detect_container() > 0)
c0387ebf
LP
267 return 0;
268
8bf23dc7
FB
269 /* swap units generated for the swap dev links are missing the
270 * ordering dep against the swap target. */
35d8c19a 271 r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SWAP_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
8bf23dc7
FB
272 if (r < 0)
273 return r;
274
5a724170 275 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
2edd4434
LP
276}
277
4e85aff4 278static int swap_verify(Swap *s) {
7fd1b19b 279 _cleanup_free_ char *e = NULL;
7410616c 280 int r;
4e85aff4 281
75193d41 282 assert(UNIT(s)->load_state == UNIT_LOADED);
4e85aff4 283
7410616c
LP
284 r = unit_name_from_path(s->what, ".swap", &e);
285 if (r < 0)
f2341e0a 286 return log_unit_error_errno(UNIT(s), r, "Failed to generate unit name from path: %m");
4e85aff4 287
d85ff944
YW
288 if (!unit_has_name(UNIT(s), e))
289 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Value of What= and unit name do not match, not loading.");
4e85aff4 290
d85ff944
YW
291 if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP)
292 return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.");
e04aad61 293
4e85aff4
LP
294 return 0;
295}
296
9670d583 297static int swap_load_devnode(Swap *s) {
4366e598 298 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
9670d583
LP
299 struct stat st;
300 const char *p;
e5ca27b7 301 int r;
9670d583
LP
302
303 assert(s);
304
305 if (stat(s->what, &st) < 0 || !S_ISBLK(st.st_mode))
306 return 0;
307
a1130022 308 r = sd_device_new_from_stat_rdev(&d, &st);
e5ca27b7 309 if (r < 0) {
8ed6f81b
YW
310 log_unit_full_errno(UNIT(s), r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
311 "Failed to allocate device for swap %s: %m", s->what);
9670d583 312 return 0;
e5ca27b7 313 }
9670d583 314
4366e598 315 if (sd_device_get_devname(d, &p) < 0)
9670d583
LP
316 return 0;
317
318 return swap_set_devnode(s, p);
319}
320
15332d73 321static int swap_add_extras(Swap *s) {
07b0b134 322 int r;
07b0b134
ML
323
324 assert(s);
07b0b134 325
15332d73
LP
326 if (UNIT(s)->fragment_path)
327 s->from_fragment = true;
07b0b134 328
15332d73
LP
329 if (!s->what) {
330 if (s->parameters_fragment.what)
331 s->what = strdup(s->parameters_fragment.what);
332 else if (s->parameters_proc_swaps.what)
333 s->what = strdup(s->parameters_proc_swaps.what);
334 else {
335 r = unit_name_to_path(UNIT(s)->id, &s->what);
5bcb0f2b 336 if (r < 0)
4e85aff4 337 return r;
5bcb0f2b 338 }
4e85aff4 339
15332d73
LP
340 if (!s->what)
341 return -ENOMEM;
342 }
07b0b134 343
4ff361cc 344 path_simplify(s->what);
07b0b134 345
15332d73
LP
346 if (!UNIT(s)->description) {
347 r = unit_set_description(UNIT(s), s->what);
9670d583
LP
348 if (r < 0)
349 return r;
15332d73 350 }
9670d583 351
15332d73
LP
352 r = unit_require_mounts_for(UNIT(s), s->what, UNIT_DEPENDENCY_IMPLICIT);
353 if (r < 0)
354 return r;
598459ce 355
15332d73
LP
356 r = swap_add_device_dependencies(s);
357 if (r < 0)
358 return r;
598459ce 359
15332d73
LP
360 r = swap_load_devnode(s);
361 if (r < 0)
362 return r;
a016b922 363
15332d73
LP
364 r = unit_patch_contexts(UNIT(s));
365 if (r < 0)
366 return r;
367
368 r = unit_add_exec_dependencies(UNIT(s), &s->exec_context);
369 if (r < 0)
370 return r;
371
372 r = unit_set_default_slice(UNIT(s));
373 if (r < 0)
374 return r;
375
376 r = swap_add_default_dependencies(s);
377 if (r < 0)
378 return r;
379
380 return 0;
381}
382
383static int swap_load(Unit *u) {
384 Swap *s = SWAP(u);
75193d41 385 int r, q = 0;
15332d73
LP
386
387 assert(s);
388 assert(u->load_state == UNIT_STUB);
389
390 /* Load a .swap file */
c3620770
ZJS
391 bool fragment_optional = s->from_proc_swaps;
392 r = unit_load_fragment_and_dropin(u, !fragment_optional);
15332d73 393
75193d41
ZJS
394 /* Add in some extras, and do so either when we successfully loaded something or when /proc/swaps is
395 * already active. */
06721f39
LP
396 if (u->load_state == UNIT_LOADED || s->from_proc_swaps)
397 q = swap_add_extras(s);
15332d73 398
06721f39
LP
399 if (r < 0)
400 return r;
401 if (q < 0)
402 return q;
75193d41
ZJS
403 if (u->load_state != UNIT_LOADED)
404 return 0;
07b0b134
ML
405
406 return swap_verify(s);
407}
408
628c89cc 409static int swap_setup_unit(
4e85aff4
LP
410 Manager *m,
411 const char *what,
e04aad61 412 const char *what_proc_swaps,
4e85aff4 413 int priority,
e04aad61
LP
414 bool set_flags) {
415
7fd1b19b 416 _cleanup_free_ char *e = NULL;
2c7c6144 417 bool delete = false;
5bcb0f2b 418 Unit *u = NULL;
07b0b134 419 int r;
4e85aff4
LP
420 SwapParameters *p;
421
422 assert(m);
423 assert(what);
6b1dc2bd 424 assert(what_proc_swaps);
07b0b134 425
7410616c
LP
426 r = unit_name_from_path(what, ".swap", &e);
427 if (r < 0)
f2341e0a 428 return log_unit_error_errno(u, r, "Failed to generate unit name from path: %m");
07b0b134 429
e04aad61 430 u = manager_get_unit(m, e);
6b1dc2bd 431 if (u &&
e04aad61 432 SWAP(u)->from_proc_swaps &&
baaa35ad
ZJS
433 !path_equal(SWAP(u)->parameters_proc_swaps.what, what_proc_swaps))
434 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
435 "Swap %s appeared twice with different device paths %s and %s",
436 e, SWAP(u)->parameters_proc_swaps.what, what_proc_swaps);
4e85aff4
LP
437
438 if (!u) {
07b0b134
ML
439 delete = true;
440
a581e45a 441 r = unit_new_for_name(m, sizeof(Swap), e, &u);
7d17cfbc 442 if (r < 0)
e04aad61
LP
443 goto fail;
444
7d17cfbc
MS
445 SWAP(u)->what = strdup(what);
446 if (!SWAP(u)->what) {
628c89cc 447 r = -ENOMEM;
e04aad61
LP
448 goto fail;
449 }
450
451 unit_add_to_load_queue(u);
4e85aff4
LP
452 } else
453 delete = false;
07b0b134 454
6b1dc2bd 455 p = &SWAP(u)->parameters_proc_swaps;
07b0b134 456
6b1dc2bd 457 if (!p->what) {
5bcb0f2b
LP
458 p->what = strdup(what_proc_swaps);
459 if (!p->what) {
460 r = -ENOMEM;
6b1dc2bd
LP
461 goto fail;
462 }
6b1dc2bd 463 }
e04aad61 464
46f94480
LP
465 /* The unit is definitely around now, mark it as loaded if it was previously referenced but could not be
466 * loaded. After all we can load it now, from the data in /proc/swaps. */
467 if (IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_BAD_SETTING, UNIT_ERROR)) {
468 u->load_state = UNIT_LOADED;
469 u->load_error = 0;
470 }
471
6b1dc2bd
LP
472 if (set_flags) {
473 SWAP(u)->is_active = true;
474 SWAP(u)->just_activated = !SWAP(u)->from_proc_swaps;
4e85aff4 475 }
07b0b134 476
6b1dc2bd
LP
477 SWAP(u)->from_proc_swaps = true;
478
4e85aff4 479 p->priority = priority;
7477451b 480 p->priority_set = true;
07b0b134 481
4e85aff4 482 unit_add_to_dbus_queue(u);
07b0b134
ML
483 return 0;
484
485fail:
f2341e0a 486 log_unit_warning_errno(u, r, "Failed to load swap unit: %m");
e04aad61 487
c9d5c9c0 488 if (delete)
07b0b134
ML
489 unit_free(u);
490
4e85aff4 491 return r;
07b0b134
ML
492}
493
6aeb8c89 494static void swap_process_new(Manager *m, const char *device, int prio, bool set_flags) {
4366e598
YW
495 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
496 const char *dn, *devlink;
497 struct stat st, st_link;
5bcb0f2b 498 int r;
e04aad61
LP
499
500 assert(m);
501
6aeb8c89
LP
502 if (swap_setup_unit(m, device, device, prio, set_flags) < 0)
503 return;
e04aad61 504
5bcb0f2b
LP
505 /* If this is a block device, then let's add duplicates for
506 * all other names of this block device */
507 if (stat(device, &st) < 0 || !S_ISBLK(st.st_mode))
6aeb8c89 508 return;
e04aad61 509
a1130022 510 r = sd_device_new_from_stat_rdev(&d, &st);
6aeb8c89
LP
511 if (r < 0)
512 return (void) log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
513 "Failed to allocate device for swap %s: %m", device);
e04aad61 514
5bcb0f2b 515 /* Add the main device node */
4366e598 516 if (sd_device_get_devname(d, &dn) >= 0 && !streq(dn, device))
6aeb8c89 517 (void) swap_setup_unit(m, dn, device, prio, set_flags);
e04aad61 518
5bcb0f2b 519 /* Add additional units for all symlinks */
4366e598 520 FOREACH_DEVICE_DEVLINK(d, devlink) {
e04aad61 521
5bcb0f2b 522 /* Don't bother with the /dev/block links */
4366e598 523 if (streq(devlink, device))
5bcb0f2b 524 continue;
e04aad61 525
4366e598 526 if (path_startswith(devlink, "/dev/block/"))
5bcb0f2b 527 continue;
e04aad61 528
4366e598
YW
529 if (stat(devlink, &st_link) >= 0 &&
530 (!S_ISBLK(st_link.st_mode) ||
531 st_link.st_rdev != st.st_rdev))
532 continue;
e04aad61 533
6aeb8c89 534 (void) swap_setup_unit(m, devlink, device, prio, set_flags);
e04aad61 535 }
e04aad61
LP
536}
537
07b0b134
ML
538static void swap_set_state(Swap *s, SwapState state) {
539 SwapState old_state;
e04aad61 540
07b0b134
ML
541 assert(s);
542
6fcbec6f
LP
543 if (s->state != state)
544 bus_unit_send_pending_change_signal(UNIT(s), false);
545
07b0b134
ML
546 old_state = s->state;
547 s->state = state;
548
dedf3719 549 if (!SWAP_STATE_WITH_PROCESS(state)) {
5dcadb4c 550 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
e04aad61
LP
551 swap_unwatch_control_pid(s);
552 s->control_command = NULL;
553 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
554 }
555
07b0b134 556 if (state != old_state)
f2341e0a 557 log_unit_debug(UNIT(s), "Changed %s -> %s", swap_state_to_string(old_state), swap_state_to_string(state));
07b0b134 558
2ad2e41a 559 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], 0);
37cf8fee
LP
560
561 /* If there other units for the same device node have a job
562 queued it might be worth checking again if it is runnable
563 now. This is necessary, since swap_start() refuses
564 operation with EAGAIN if there's already another job for
565 the same device node queued. */
566 LIST_FOREACH_OTHERS(same_devnode, other, s)
567 if (UNIT(other)->job)
568 job_add_to_run_queue(UNIT(other)->job);
07b0b134
ML
569}
570
be847e82 571static int swap_coldplug(Unit *u) {
07b0b134
ML
572 Swap *s = SWAP(u);
573 SwapState new_state = SWAP_DEAD;
e04aad61 574 int r;
07b0b134
ML
575
576 assert(s);
577 assert(s->state == SWAP_DEAD);
578
579 if (s->deserialized_state != s->state)
580 new_state = s->deserialized_state;
4e85aff4 581 else if (s->from_proc_swaps)
07b0b134
ML
582 new_state = SWAP_ACTIVE;
583
5bcb0f2b
LP
584 if (new_state == s->state)
585 return 0;
e04aad61 586
c386f588
LP
587 if (s->control_pid > 0 &&
588 pid_is_unwaited(s->control_pid) &&
dedf3719 589 SWAP_STATE_WITH_PROCESS(new_state)) {
e04aad61 590
f75f613d 591 r = unit_watch_pid(UNIT(s), s->control_pid, false);
5bcb0f2b
LP
592 if (r < 0)
593 return r;
e04aad61 594
36c16a7c 595 r = swap_arm_timer(s, usec_add(u->state_change_timestamp.monotonic, s->timeout_usec));
5bcb0f2b
LP
596 if (r < 0)
597 return r;
e04aad61 598 }
07b0b134 599
e8a565cb 600 if (!IN_SET(new_state, SWAP_DEAD, SWAP_FAILED)) {
29206d46 601 (void) unit_setup_dynamic_creds(u);
e8a565cb
YW
602 (void) unit_setup_exec_runtime(u);
603 }
29206d46 604
5bcb0f2b 605 swap_set_state(s, new_state);
07b0b134
ML
606 return 0;
607}
608
609static void swap_dump(Unit *u, FILE *f, const char *prefix) {
610 Swap *s = SWAP(u);
4e85aff4 611 SwapParameters *p;
07b0b134
ML
612
613 assert(s);
4e85aff4
LP
614 assert(f);
615
616 if (s->from_proc_swaps)
617 p = &s->parameters_proc_swaps;
618 else if (s->from_fragment)
619 p = &s->parameters_fragment;
b6bfc7bb
LP
620 else
621 p = NULL;
07b0b134
ML
622
623 fprintf(f,
4e85aff4 624 "%sSwap State: %s\n"
e1770af8 625 "%sResult: %s\n"
a8b689b7 626 "%sClean Result: %s\n"
07b0b134 627 "%sWhat: %s\n"
4e85aff4 628 "%sFrom /proc/swaps: %s\n"
39c79477
ZJS
629 "%sFrom fragment: %s\n"
630 "%sExtrinsic: %s\n",
07b0b134 631 prefix, swap_state_to_string(s->state),
e1770af8 632 prefix, swap_result_to_string(s->result),
a8b689b7 633 prefix, swap_result_to_string(s->clean_result),
07b0b134 634 prefix, s->what,
4e85aff4 635 prefix, yes_no(s->from_proc_swaps),
39c79477
ZJS
636 prefix, yes_no(s->from_fragment),
637 prefix, yes_no(swap_is_extrinsic(u)));
e04aad61 638
9670d583
LP
639 if (s->devnode)
640 fprintf(f, "%sDevice Node: %s\n", prefix, s->devnode);
641
b6bfc7bb
LP
642 if (p)
643 fprintf(f,
644 "%sPriority: %i\n"
47cb901e 645 "%sOptions: %s\n",
b6bfc7bb 646 prefix, p->priority,
47cb901e 647 prefix, strempty(p->options));
b6bfc7bb 648
9bd0e1b8
YW
649 fprintf(f,
650 "%sTimeoutSec: %s\n",
5291f26d 651 prefix, FORMAT_TIMESPAN(s->timeout_usec, USEC_PER_SEC));
9bd0e1b8 652
e04aad61
LP
653 if (s->control_pid > 0)
654 fprintf(f,
de0671ee
ZJS
655 "%sControl PID: "PID_FMT"\n",
656 prefix, s->control_pid);
e04aad61
LP
657
658 exec_context_dump(&s->exec_context, f, prefix);
4819ff03 659 kill_context_dump(&s->kill_context, f, prefix);
bc0623df 660 cgroup_context_dump(UNIT(s), f, prefix);
e04aad61
LP
661}
662
663static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) {
3c7416b6 664
b9c04eaf 665 _cleanup_(exec_params_clear) ExecParameters exec_params = {
1703fa41 666 .flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
c39f1ce2
LP
667 .stdin_fd = -1,
668 .stdout_fd = -1,
669 .stderr_fd = -1,
5686391b 670 .exec_fd = -1,
9fa95f85 671 };
3c7416b6
LP
672 pid_t pid;
673 int r;
e04aad61
LP
674
675 assert(s);
676 assert(c);
677 assert(_pid);
678
3c7416b6 679 r = unit_prepare_exec(UNIT(s));
29206d46 680 if (r < 0)
3c7416b6 681 return r;
29206d46 682
36c16a7c 683 r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
646134dc 684 if (r < 0)
e04aad61
LP
685 goto fail;
686
1ad6e8b3
LP
687 r = unit_set_exec_params(UNIT(s), &exec_params);
688 if (r < 0)
689 goto fail;
9fa95f85 690
f2341e0a
LP
691 r = exec_spawn(UNIT(s),
692 c,
646134dc 693 &s->exec_context,
9fa95f85 694 &exec_params,
613b411c 695 s->exec_runtime,
29206d46 696 &s->dynamic_creds,
646134dc
ZJS
697 &pid);
698 if (r < 0)
e04aad61
LP
699 goto fail;
700
f75f613d 701 r = unit_watch_pid(UNIT(s), pid, true);
646134dc 702 if (r < 0)
e04aad61
LP
703 goto fail;
704
705 *_pid = pid;
706
707 return 0;
708
709fail:
5dcadb4c 710 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
3536f49e 711
e04aad61 712 return r;
07b0b134
ML
713}
714
e1770af8 715static void swap_enter_dead(Swap *s, SwapResult f) {
07b0b134
ML
716 assert(s);
717
a0fef983 718 if (s->result == SWAP_SUCCESS)
e1770af8 719 s->result = f;
e04aad61 720
aac99f30 721 unit_log_result(UNIT(s), s->result == SWAP_SUCCESS, swap_result_to_string(s->result));
4c425434 722 unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_stop);
29206d46
LP
723 swap_set_state(s, s->result != SWAP_SUCCESS ? SWAP_FAILED : SWAP_DEAD);
724
e8a565cb 725 s->exec_runtime = exec_runtime_unref(s->exec_runtime, true);
613b411c 726
bb0c0d6f 727 unit_destroy_runtime_data(UNIT(s), &s->exec_context);
e66cf1a3 728
00d9ef85
LP
729 unit_unref_uid_gid(UNIT(s), true);
730
29206d46 731 dynamic_creds_destroy(&s->dynamic_creds);
07b0b134
ML
732}
733
e1770af8 734static void swap_enter_active(Swap *s, SwapResult f) {
e04aad61
LP
735 assert(s);
736
a0fef983 737 if (s->result == SWAP_SUCCESS)
e1770af8 738 s->result = f;
e04aad61
LP
739
740 swap_set_state(s, SWAP_ACTIVE);
741}
742
50864457
LP
743static void swap_enter_dead_or_active(Swap *s, SwapResult f) {
744 assert(s);
745
9c1f969d 746 if (s->from_proc_swaps) {
50864457 747 swap_enter_active(s, f);
9c1f969d
HD
748
749 LIST_FOREACH_OTHERS(same_devnode, other, s)
750 if (UNIT(other)->job)
751 swap_enter_dead_or_active(other, f);
752 } else
50864457
LP
753 swap_enter_dead(s, f);
754}
755
a232ebcc
ZJS
756static int state_to_kill_operation(Swap *s, SwapState state) {
757 if (state == SWAP_DEACTIVATING_SIGTERM) {
758 if (unit_has_job_type(UNIT(s), JOB_RESTART))
759 return KILL_RESTART;
760 else
761 return KILL_TERMINATE;
762 }
763
764 return KILL_KILL;
765}
766
e1770af8 767static void swap_enter_signal(Swap *s, SwapState state, SwapResult f) {
07b0b134
ML
768 int r;
769
770 assert(s);
e04aad61 771
a0fef983 772 if (s->result == SWAP_SUCCESS)
e1770af8 773 s->result = f;
e04aad61 774
a232ebcc
ZJS
775 r = unit_kill_context(UNIT(s),
776 &s->kill_context,
777 state_to_kill_operation(s, state),
778 -1,
779 s->control_pid,
780 false);
cd2086fe
LP
781 if (r < 0)
782 goto fail;
e04aad61 783
cd2086fe 784 if (r > 0) {
36c16a7c 785 r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
646134dc 786 if (r < 0)
e04aad61
LP
787 goto fail;
788
789 swap_set_state(s, state);
50864457 790 } else if (state == SWAP_DEACTIVATING_SIGTERM && s->kill_context.send_sigkill)
ac84d1fb
LP
791 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_SUCCESS);
792 else
50864457 793 swap_enter_dead_or_active(s, SWAP_SUCCESS);
e04aad61
LP
794
795 return;
796
797fail:
f2341e0a 798 log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
50864457 799 swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES);
e04aad61
LP
800}
801
802static void swap_enter_activating(Swap *s) {
bf1d7ba7
KZ
803 _cleanup_free_ char *opts = NULL;
804 int r;
e04aad61
LP
805
806 assert(s);
807
4c425434 808 unit_warn_leftover_processes(UNIT(s), unit_log_leftover_process_start);
a4634b21 809
e04aad61
LP
810 s->control_command_id = SWAP_EXEC_ACTIVATE;
811 s->control_command = s->exec_command + SWAP_EXEC_ACTIVATE;
07b0b134 812
86b23b07 813 if (s->from_fragment) {
7477451b 814 int priority = 0;
47cb901e 815
bf1d7ba7
KZ
816 r = fstab_find_pri(s->parameters_fragment.options, &priority);
817 if (r < 0)
af4454cb
LP
818 log_unit_warning_errno(UNIT(s), r, "Failed to parse swap priority \"%s\", ignoring: %m", s->parameters_fragment.options);
819 else if (r > 0 && s->parameters_fragment.priority_set)
820 log_unit_warning(UNIT(s), "Duplicate swap priority configuration by Priority= and Options= fields.");
bf1d7ba7 821
7477451b 822 if (r <= 0 && s->parameters_fragment.priority_set) {
bf1d7ba7
KZ
823 if (s->parameters_fragment.options)
824 r = asprintf(&opts, "%s,pri=%i", s->parameters_fragment.options, s->parameters_fragment.priority);
825 else
826 r = asprintf(&opts, "pri=%i", s->parameters_fragment.priority);
6fca66a7
LP
827 if (r < 0) {
828 r = -ENOMEM;
bf1d7ba7 829 goto fail;
6fca66a7 830 }
e64d5235 831 }
86b23b07
JS
832 }
833
834 r = exec_command_set(s->control_command, "/sbin/swapon", NULL);
835 if (r < 0)
836 goto fail;
4e85aff4 837
bf1d7ba7
KZ
838 if (s->parameters_fragment.options || opts) {
839 r = exec_command_append(s->control_command, "-o",
af4454cb 840 opts ?: s->parameters_fragment.options, NULL);
86b23b07
JS
841 if (r < 0)
842 goto fail;
843 }
e04aad61 844
86b23b07 845 r = exec_command_append(s->control_command, s->what, NULL);
e04aad61
LP
846 if (r < 0)
847 goto fail;
848
849 swap_unwatch_control_pid(s);
850
646134dc
ZJS
851 r = swap_spawn(s, s->control_command, &s->control_pid);
852 if (r < 0)
e04aad61
LP
853 goto fail;
854
855 swap_set_state(s, SWAP_ACTIVATING);
e04aad61
LP
856 return;
857
858fail:
f2341e0a 859 log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapon' task: %m");
50864457 860 swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES);
e04aad61
LP
861}
862
e1770af8 863static void swap_enter_deactivating(Swap *s) {
e04aad61
LP
864 int r;
865
866 assert(s);
867
e04aad61
LP
868 s->control_command_id = SWAP_EXEC_DEACTIVATE;
869 s->control_command = s->exec_command + SWAP_EXEC_DEACTIVATE;
870
646134dc 871 r = exec_command_set(s->control_command,
e04aad61
LP
872 "/sbin/swapoff",
873 s->what,
646134dc
ZJS
874 NULL);
875 if (r < 0)
e04aad61
LP
876 goto fail;
877
878 swap_unwatch_control_pid(s);
879
646134dc
ZJS
880 r = swap_spawn(s, s->control_command, &s->control_pid);
881 if (r < 0)
e04aad61
LP
882 goto fail;
883
884 swap_set_state(s, SWAP_DEACTIVATING);
885
886 return;
887
888fail:
f2341e0a 889 log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapoff' task: %m");
50864457 890 swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES);
e04aad61
LP
891}
892
31135818
LP
893static void swap_cycle_clear(Swap *s) {
894 assert(s);
895
896 s->result = SWAP_SUCCESS;
897 exec_command_reset_status_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX);
898 UNIT(s)->reset_accounting = true;
899}
900
e04aad61 901static int swap_start(Unit *u) {
03677889 902 Swap *s = SWAP(u);
07299350 903 int r;
e04aad61
LP
904
905 assert(s);
906
50864457 907 /* We cannot fulfill this request right now, try again later please! */
d31ae548
FB
908 if (IN_SET(s->state,
909 SWAP_DEACTIVATING,
910 SWAP_DEACTIVATING_SIGTERM,
a8b689b7
YW
911 SWAP_DEACTIVATING_SIGKILL,
912 SWAP_CLEANING))
e04aad61
LP
913 return -EAGAIN;
914
50864457 915 /* Already on it! */
e04aad61
LP
916 if (s->state == SWAP_ACTIVATING)
917 return 0;
918
d31ae548 919 assert(IN_SET(s->state, SWAP_DEAD, SWAP_FAILED));
e04aad61 920
75f86906 921 if (detect_container() > 0)
a5c3034f
LP
922 return -EPERM;
923
37cf8fee
LP
924 /* If there's a job for another swap unit for the same node
925 * running, then let's not dispatch this one for now, and wait
926 * until that other job has finished. */
927 LIST_FOREACH_OTHERS(same_devnode, other, s)
928 if (UNIT(other)->job && UNIT(other)->job->state == JOB_RUNNING)
929 return -EAGAIN;
930
4b58153d
LP
931 r = unit_acquire_invocation_id(u);
932 if (r < 0)
933 return r;
934
31135818 935 swap_cycle_clear(s);
e04aad61 936 swap_enter_activating(s);
82a2b6bb 937 return 1;
07b0b134
ML
938}
939
940static int swap_stop(Unit *u) {
941 Swap *s = SWAP(u);
07b0b134
ML
942
943 assert(s);
944
50864457
LP
945 switch (s->state) {
946
947 case SWAP_DEACTIVATING:
948 case SWAP_DEACTIVATING_SIGTERM:
949 case SWAP_DEACTIVATING_SIGKILL:
950 /* Already on it */
e04aad61 951 return 0;
07b0b134 952
50864457
LP
953 case SWAP_ACTIVATING:
954 case SWAP_ACTIVATING_DONE:
955 /* There's a control process pending, directly enter kill mode */
956 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_SUCCESS);
957 return 0;
07b0b134 958
50864457
LP
959 case SWAP_ACTIVE:
960 if (detect_container() > 0)
961 return -EPERM;
a5c3034f 962
50864457
LP
963 swap_enter_deactivating(s);
964 return 1;
965
a8b689b7
YW
966 case SWAP_CLEANING:
967 /* If we are currently cleaning, then abort it, brutally. */
968 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_SUCCESS);
969 return 0;
970
50864457 971 default:
04499a70 972 assert_not_reached();
50864457 973 }
07b0b134
ML
974}
975
976static int swap_serialize(Unit *u, FILE *f, FDSet *fds) {
977 Swap *s = SWAP(u);
978
979 assert(s);
980 assert(f);
981 assert(fds);
982
d68c645b
LP
983 (void) serialize_item(f, "state", swap_state_to_string(s->state));
984 (void) serialize_item(f, "result", swap_result_to_string(s->result));
e04aad61
LP
985
986 if (s->control_pid > 0)
d68c645b 987 (void) serialize_item_format(f, "control-pid", PID_FMT, s->control_pid);
e04aad61
LP
988
989 if (s->control_command_id >= 0)
d68c645b 990 (void) serialize_item(f, "control-command", swap_exec_command_to_string(s->control_command_id));
07b0b134
ML
991
992 return 0;
993}
994
995static int swap_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
996 Swap *s = SWAP(u);
997
998 assert(s);
999 assert(fds);
1000
1001 if (streq(key, "state")) {
1002 SwapState state;
1003
646134dc
ZJS
1004 state = swap_state_from_string(value);
1005 if (state < 0)
f2341e0a 1006 log_unit_debug(u, "Failed to parse state value: %s", value);
07b0b134
ML
1007 else
1008 s->deserialized_state = state;
e1770af8
LP
1009 } else if (streq(key, "result")) {
1010 SwapResult f;
1011
1012 f = swap_result_from_string(value);
1013 if (f < 0)
f2341e0a 1014 log_unit_debug(u, "Failed to parse result value: %s", value);
e1770af8
LP
1015 else if (f != SWAP_SUCCESS)
1016 s->result = f;
e04aad61
LP
1017 } else if (streq(key, "control-pid")) {
1018 pid_t pid;
1019
1020 if (parse_pid(value, &pid) < 0)
f2341e0a 1021 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
e04aad61
LP
1022 else
1023 s->control_pid = pid;
1024
1025 } else if (streq(key, "control-command")) {
1026 SwapExecCommand id;
1027
646134dc
ZJS
1028 id = swap_exec_command_from_string(value);
1029 if (id < 0)
f2341e0a 1030 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
e04aad61
LP
1031 else {
1032 s->control_command_id = id;
1033 s->control_command = s->exec_command + id;
1034 }
07b0b134 1035 } else
f2341e0a 1036 log_unit_debug(u, "Unknown serialization key: %s", key);
07b0b134
ML
1037
1038 return 0;
1039}
1040
e04aad61
LP
1041static void swap_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1042 Swap *s = SWAP(u);
e1770af8 1043 SwapResult f;
e04aad61
LP
1044
1045 assert(s);
1046 assert(pid >= 0);
1047
1048 if (pid != s->control_pid)
1049 return;
1050
bcce581d
LP
1051 /* Let's scan /proc/swaps before we process SIGCHLD. For the reasoning see the similar code in
1052 * mount.c */
1053 (void) swap_process_proc_swaps(u->manager);
1054
e04aad61
LP
1055 s->control_pid = 0;
1056
1f0958f6 1057 if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
e1770af8
LP
1058 f = SWAP_SUCCESS;
1059 else if (code == CLD_EXITED)
1060 f = SWAP_FAILURE_EXIT_CODE;
1061 else if (code == CLD_KILLED)
1062 f = SWAP_FAILURE_SIGNAL;
1063 else if (code == CLD_DUMPED)
1064 f = SWAP_FAILURE_CORE_DUMP;
1065 else
04499a70 1066 assert_not_reached();
e1770af8 1067
a0fef983 1068 if (s->result == SWAP_SUCCESS)
e1770af8 1069 s->result = f;
e04aad61
LP
1070
1071 if (s->control_command) {
6ea832a2 1072 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
e1770af8 1073
e04aad61
LP
1074 s->control_command = NULL;
1075 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
1076 }
1077
91bbd9b7 1078 unit_log_process_exit(
5cc2cd1c 1079 u,
91bbd9b7
LP
1080 "Swap process",
1081 swap_exec_command_to_string(s->control_command_id),
5cc2cd1c 1082 f == SWAP_SUCCESS,
91bbd9b7 1083 code, status);
e04aad61
LP
1084
1085 switch (s->state) {
1086
1087 case SWAP_ACTIVATING:
5bcb0f2b 1088 case SWAP_ACTIVATING_DONE:
e04aad61 1089
50864457 1090 if (f == SWAP_SUCCESS || s->from_proc_swaps)
e1770af8 1091 swap_enter_active(s, f);
e04aad61 1092 else
e1770af8 1093 swap_enter_dead(s, f);
e04aad61
LP
1094 break;
1095
1096 case SWAP_DEACTIVATING:
1097 case SWAP_DEACTIVATING_SIGKILL:
1098 case SWAP_DEACTIVATING_SIGTERM:
1099
50864457 1100 swap_enter_dead_or_active(s, f);
e04aad61
LP
1101 break;
1102
a8b689b7
YW
1103 case SWAP_CLEANING:
1104 if (s->clean_result == SWAP_SUCCESS)
1105 s->clean_result = f;
1106
1107 swap_enter_dead(s, SWAP_SUCCESS);
1108 break;
1109
e04aad61 1110 default:
04499a70 1111 assert_not_reached();
e04aad61
LP
1112 }
1113
1114 /* Notify clients about changed exit status */
1115 unit_add_to_dbus_queue(u);
e04aad61
LP
1116}
1117
718db961
LP
1118static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
1119 Swap *s = SWAP(userdata);
e04aad61
LP
1120
1121 assert(s);
718db961 1122 assert(s->timer_event_source == source);
e04aad61
LP
1123
1124 switch (s->state) {
1125
1126 case SWAP_ACTIVATING:
5bcb0f2b 1127 case SWAP_ACTIVATING_DONE:
f2341e0a 1128 log_unit_warning(UNIT(s), "Activation timed out. Stopping.");
50864457 1129 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
e04aad61
LP
1130 break;
1131
1132 case SWAP_DEACTIVATING:
f2341e0a 1133 log_unit_warning(UNIT(s), "Deactivation timed out. Stopping.");
e1770af8 1134 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
e04aad61
LP
1135 break;
1136
e04aad61 1137 case SWAP_DEACTIVATING_SIGTERM:
4819ff03 1138 if (s->kill_context.send_sigkill) {
50864457 1139 log_unit_warning(UNIT(s), "Swap process timed out. Killing.");
e1770af8 1140 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_FAILURE_TIMEOUT);
ba035df2 1141 } else {
50864457
LP
1142 log_unit_warning(UNIT(s), "Swap process timed out. Skipping SIGKILL. Ignoring.");
1143 swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT);
ba035df2 1144 }
e04aad61
LP
1145 break;
1146
e04aad61 1147 case SWAP_DEACTIVATING_SIGKILL:
f2341e0a 1148 log_unit_warning(UNIT(s), "Swap process still around after SIGKILL. Ignoring.");
50864457 1149 swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT);
e04aad61
LP
1150 break;
1151
a8b689b7
YW
1152 case SWAP_CLEANING:
1153 log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
1154
1155 if (s->clean_result == SWAP_SUCCESS)
1156 s->clean_result = SWAP_FAILURE_TIMEOUT;
1157
1158 swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, 0);
1159 break;
1160
e04aad61 1161 default:
04499a70 1162 assert_not_reached();
e04aad61 1163 }
718db961
LP
1164
1165 return 0;
e04aad61
LP
1166}
1167
1168static int swap_load_proc_swaps(Manager *m, bool set_flags) {
e04aad61
LP
1169 assert(m);
1170
07b0b134 1171 rewind(m->proc_swaps);
bab45044 1172
4e85aff4 1173 (void) fscanf(m->proc_swaps, "%*s %*s %*s %*s %*s\n");
07b0b134 1174
fe96c0f8 1175 for (unsigned i = 1;; i++) {
9fb3675e 1176 _cleanup_free_ char *dev = NULL, *d = NULL;
07b0b134
ML
1177 int prio = 0, k;
1178
646134dc
ZJS
1179 k = fscanf(m->proc_swaps,
1180 "%ms " /* device/file */
1181 "%*s " /* type of swap */
1182 "%*s " /* swap size */
1183 "%*s " /* used */
1184 "%i\n", /* priority */
1185 &dev, &prio);
1186 if (k != 2) {
07b0b134 1187 if (k == EOF)
4e85aff4 1188 break;
07b0b134 1189
628c89cc 1190 log_warning("Failed to parse /proc/swaps:%u.", i);
e04aad61 1191 continue;
07b0b134 1192 }
07b0b134 1193
e437538f
ZJS
1194 ssize_t l = cunescape(dev, UNESCAPE_RELAX, &d);
1195 if (l < 0)
1196 return log_error_errno(l, "Failed to unescape device path: %m");
628c89cc 1197
485ae697 1198 device_found_node(m, d, DEVICE_FOUND_SWAP, DEVICE_FOUND_SWAP);
4e85aff4 1199
eb04385d 1200 (void) swap_process_new(m, d, prio, set_flags);
07b0b134
ML
1201 }
1202
eb04385d 1203 return 0;
e04aad61
LP
1204}
1205
bcce581d 1206static int swap_process_proc_swaps(Manager *m) {
4e434314
LP
1207 int r;
1208
1209 assert(m);
4e434314 1210
646134dc
ZJS
1211 r = swap_load_proc_swaps(m, true);
1212 if (r < 0) {
da927ba9 1213 log_error_errno(r, "Failed to reread /proc/swaps: %m");
e04aad61
LP
1214
1215 /* Reset flags, just in case, for late calls */
595ed347
MS
1216 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) {
1217 Swap *swap = SWAP(u);
e04aad61 1218
c73f413d
FS
1219 assert(swap);
1220
e04aad61
LP
1221 swap->is_active = swap->just_activated = false;
1222 }
1223
1224 return 0;
1225 }
1226
1227 manager_dispatch_load_queue(m);
1228
595ed347
MS
1229 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) {
1230 Swap *swap = SWAP(u);
e04aad61 1231
c73f413d
FS
1232 assert(swap);
1233
e04aad61 1234 if (!swap->is_active) {
e04aad61 1235
e04aad61
LP
1236 swap_unset_proc_swaps(swap);
1237
1238 switch (swap->state) {
1239
1240 case SWAP_ACTIVE:
ba6fbb2c 1241 /* This has just been deactivated */
e1770af8 1242 swap_enter_dead(swap, SWAP_SUCCESS);
e04aad61
LP
1243 break;
1244
1245 default:
5bcb0f2b 1246 /* Fire again */
e04aad61
LP
1247 swap_set_state(swap, swap->state);
1248 break;
1249 }
1250
628c89cc 1251 if (swap->what)
b1ba0ce8 1252 device_found_node(m, swap->what, DEVICE_NOT_FOUND, DEVICE_FOUND_SWAP);
628c89cc 1253
e04aad61
LP
1254 } else if (swap->just_activated) {
1255
1256 /* New swap entry */
1257
1258 switch (swap->state) {
1259
1260 case SWAP_DEAD:
1261 case SWAP_FAILED:
31135818
LP
1262 (void) unit_acquire_invocation_id(u);
1263 swap_cycle_clear(swap);
e1770af8 1264 swap_enter_active(swap, SWAP_SUCCESS);
e04aad61
LP
1265 break;
1266
5bcb0f2b
LP
1267 case SWAP_ACTIVATING:
1268 swap_set_state(swap, SWAP_ACTIVATING_DONE);
1269 break;
1270
e04aad61
LP
1271 default:
1272 /* Nothing really changed, but let's
1273 * issue an notification call
1274 * nonetheless, in case somebody is
1275 * waiting for this. */
1276 swap_set_state(swap, swap->state);
1277 break;
1278 }
1279 }
1280
1281 /* Reset the flags for later calls */
1282 swap->is_active = swap->just_activated = false;
1283 }
1284
1285 return 1;
1286}
1287
bcce581d
LP
1288static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1289 Manager *m = userdata;
1290
1291 assert(m);
1292 assert(revents & EPOLLPRI);
1293
1294 return swap_process_proc_swaps(m);
1295}
1296
e04aad61
LP
1297static Unit *swap_following(Unit *u) {
1298 Swap *s = SWAP(u);
03677889 1299 Swap *first = NULL;
e04aad61
LP
1300
1301 assert(s);
1302
cdc89820
ZJS
1303 /* If the user configured the swap through /etc/fstab or
1304 * a device unit, follow that. */
1305
1306 if (s->from_fragment)
e04aad61
LP
1307 return NULL;
1308
caac2704 1309 LIST_FOREACH_OTHERS(same_devnode, other, s)
cdc89820
ZJS
1310 if (other->from_fragment)
1311 return UNIT(other);
1312
b938cb90 1313 /* Otherwise, make everybody follow the unit that's named after
cdc89820
ZJS
1314 * the swap device in the kernel */
1315
1316 if (streq_ptr(s->what, s->devnode))
1317 return NULL;
e04aad61 1318
bd335c96 1319 LIST_FOREACH(same_devnode, other, s->same_devnode_next)
9670d583 1320 if (streq_ptr(other->what, other->devnode))
e04aad61
LP
1321 return UNIT(other);
1322
bd335c96 1323 LIST_FOREACH_BACKWARDS(same_devnode, other, s->same_devnode_prev) {
9670d583 1324 if (streq_ptr(other->what, other->devnode))
e04aad61
LP
1325 return UNIT(other);
1326
1327 first = other;
1328 }
1329
cdc89820 1330 /* Fall back to the first on the list */
e04aad61 1331 return UNIT(first);
07b0b134
ML
1332}
1333
6210e7fc 1334static int swap_following_set(Unit *u, Set **_set) {
03677889 1335 Swap *s = SWAP(u);
af4fa99d 1336 _cleanup_set_free_ Set *set = NULL;
6210e7fc
LP
1337 int r;
1338
1339 assert(s);
1340 assert(_set);
1341
9670d583 1342 if (LIST_JUST_US(same_devnode, s)) {
6210e7fc
LP
1343 *_set = NULL;
1344 return 0;
1345 }
1346
d5099efc 1347 set = set_new(NULL);
5bcb0f2b 1348 if (!set)
6210e7fc
LP
1349 return -ENOMEM;
1350
caac2704 1351 LIST_FOREACH_OTHERS(same_devnode, other, s) {
5bcb0f2b
LP
1352 r = set_put(set, other);
1353 if (r < 0)
95f14a3e 1354 return r;
5bcb0f2b 1355 }
6210e7fc 1356
95f14a3e 1357 *_set = TAKE_PTR(set);
6210e7fc 1358 return 1;
6210e7fc
LP
1359}
1360
07b0b134
ML
1361static void swap_shutdown(Manager *m) {
1362 assert(m);
1363
5dcadb4c 1364 m->swap_event_source = sd_event_source_disable_unref(m->swap_event_source);
74ca738f 1365 m->proc_swaps = safe_fclose(m->proc_swaps);
525d3cc7 1366 m->swaps_by_devnode = hashmap_free(m->swaps_by_devnode);
07b0b134
ML
1367}
1368
ba64af90 1369static void swap_enumerate(Manager *m) {
07b0b134 1370 int r;
9670d583 1371
07b0b134
ML
1372 assert(m);
1373
4e434314 1374 if (!m->proc_swaps) {
646134dc 1375 m->proc_swaps = fopen("/proc/swaps", "re");
ba64af90
LP
1376 if (!m->proc_swaps) {
1377 if (errno == ENOENT)
cb209a04 1378 log_debug_errno(errno, "Not swap enabled, skipping enumeration.");
ba64af90 1379 else
cb209a04 1380 log_warning_errno(errno, "Failed to open /proc/swaps, ignoring: %m");
ba64af90
LP
1381
1382 return;
1383 }
4e434314 1384
151b9b96 1385 r = sd_event_add_io(m->event, &m->swap_event_source, fileno(m->proc_swaps), EPOLLPRI, swap_dispatch_io, m);
ba64af90
LP
1386 if (r < 0) {
1387 log_error_errno(r, "Failed to watch /proc/swaps: %m");
29083707 1388 goto fail;
ba64af90 1389 }
29083707
LP
1390
1391 /* Dispatch this before we dispatch SIGCHLD, so that
1392 * we always get the events from /proc/swaps before
1393 * the SIGCHLD of /sbin/swapon. */
83231637 1394 r = sd_event_source_set_priority(m->swap_event_source, SD_EVENT_PRIORITY_NORMAL-10);
ba64af90
LP
1395 if (r < 0) {
1396 log_error_errno(r, "Failed to change /proc/swaps priority: %m");
718db961 1397 goto fail;
ba64af90 1398 }
7dfbe2e3
TG
1399
1400 (void) sd_event_source_set_description(m->swap_event_source, "swap-proc");
4e434314
LP
1401 }
1402
646134dc
ZJS
1403 r = swap_load_proc_swaps(m, false);
1404 if (r < 0)
718db961
LP
1405 goto fail;
1406
ba64af90 1407 return;
07b0b134 1408
718db961
LP
1409fail:
1410 swap_shutdown(m);
07b0b134
ML
1411}
1412
4366e598 1413int swap_process_device_new(Manager *m, sd_device *dev) {
9670d583 1414 _cleanup_free_ char *e = NULL;
4366e598 1415 const char *dn, *devlink;
cabf58b2 1416 Unit *u;
c53aafb7 1417 int r;
9670d583
LP
1418
1419 assert(m);
1420 assert(dev);
1421
e82c6e8b 1422 if (sd_device_get_devname(dev, &dn) < 0)
9670d583
LP
1423 return 0;
1424
7410616c 1425 r = unit_name_from_path(dn, ".swap", &e);
e82c6e8b
LP
1426 if (r < 0) {
1427 log_debug_errno(r, "Cannot convert device name '%s' to unit name, ignoring: %m", dn);
1428 return 0;
1429 }
9670d583 1430
cabf58b2
FB
1431 u = manager_get_unit(m, e);
1432 if (u)
1433 r = swap_set_devnode(SWAP(u), dn);
9670d583 1434
4366e598 1435 FOREACH_DEVICE_DEVLINK(dev, devlink) {
9670d583 1436 _cleanup_free_ char *n = NULL;
7410616c 1437 int q;
9670d583 1438
4366e598 1439 q = unit_name_from_path(devlink, ".swap", &n);
598a6a84
LP
1440 if (IN_SET(q, -EINVAL, -ENAMETOOLONG)) /* If name too long or otherwise not convertible to
1441 * unit name, we can't manage it */
1442 continue;
7410616c
LP
1443 if (q < 0)
1444 return q;
9670d583 1445
cabf58b2
FB
1446 u = manager_get_unit(m, n);
1447 if (u) {
1448 q = swap_set_devnode(SWAP(u), dn);
9670d583
LP
1449 if (q < 0)
1450 r = q;
1451 }
1452 }
1453
1454 return r;
1455}
1456
4366e598 1457int swap_process_device_remove(Manager *m, sd_device *dev) {
9670d583 1458 const char *dn;
c53aafb7 1459 int r;
9670d583
LP
1460 Swap *s;
1461
4366e598
YW
1462 r = sd_device_get_devname(dev, &dn);
1463 if (r < 0)
9670d583
LP
1464 return 0;
1465
1466 while ((s = hashmap_get(m->swaps_by_devnode, dn))) {
1467 int q;
1468
1469 q = swap_set_devnode(s, NULL);
1470 if (q < 0)
1471 r = q;
1472 }
1473
1474 return r;
1475}
1476
fdf20a31 1477static void swap_reset_failed(Unit *u) {
5632e374
LP
1478 Swap *s = SWAP(u);
1479
1480 assert(s);
1481
fdf20a31 1482 if (s->state == SWAP_FAILED)
5632e374 1483 swap_set_state(s, SWAP_DEAD);
e04aad61 1484
e1770af8 1485 s->result = SWAP_SUCCESS;
a8b689b7 1486 s->clean_result = SWAP_SUCCESS;
5632e374
LP
1487}
1488
718db961 1489static int swap_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
814cc562 1490 return unit_kill_common(u, who, signo, -1, SWAP(u)->control_pid, error);
8a0867d6
LP
1491}
1492
7a7821c8 1493static int swap_get_timeout(Unit *u, usec_t *timeout) {
68db7a3b 1494 Swap *s = SWAP(u);
7a7821c8 1495 usec_t t;
68db7a3b
ZJS
1496 int r;
1497
c73f413d
FS
1498 assert(s);
1499 assert(u);
1500
68db7a3b
ZJS
1501 if (!s->timer_event_source)
1502 return 0;
1503
7a7821c8 1504 r = sd_event_source_get_time(s->timer_event_source, &t);
68db7a3b
ZJS
1505 if (r < 0)
1506 return r;
7a7821c8
LP
1507 if (t == USEC_INFINITY)
1508 return 0;
68db7a3b 1509
7a7821c8 1510 *timeout = t;
68db7a3b
ZJS
1511 return 1;
1512}
1513
1c2e9646 1514static bool swap_supported(void) {
0faacd47
LP
1515 static int supported = -1;
1516
1517 /* If swap support is not available in the kernel, or we are
1518 * running in a container we don't support swap units, and any
1519 * attempts to starting one should fail immediately. */
1520
1521 if (supported < 0)
1522 supported =
1523 access("/proc/swaps", F_OK) >= 0 &&
75f86906 1524 detect_container() <= 0;
0faacd47
LP
1525
1526 return supported;
1527}
1528
291d565a
LP
1529static int swap_control_pid(Unit *u) {
1530 Swap *s = SWAP(u);
1531
1532 assert(s);
1533
1534 return s->control_pid;
1535}
1536
a8b689b7
YW
1537static int swap_clean(Unit *u, ExecCleanMask mask) {
1538 _cleanup_strv_free_ char **l = NULL;
1539 Swap *s = SWAP(u);
1540 int r;
1541
1542 assert(s);
1543 assert(mask != 0);
1544
1545 if (s->state != SWAP_DEAD)
1546 return -EBUSY;
1547
1548 r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
1549 if (r < 0)
1550 return r;
1551
1552 if (strv_isempty(l))
1553 return -EUNATCH;
1554
1555 swap_unwatch_control_pid(s);
1556 s->clean_result = SWAP_SUCCESS;
1557 s->control_command = NULL;
1558 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
1559
1560 r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->exec_context.timeout_clean_usec));
1561 if (r < 0)
1562 goto fail;
1563
1564 r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
1565 if (r < 0)
1566 goto fail;
1567
1568 swap_set_state(s, SWAP_CLEANING);
1569
1570 return 0;
1571
1572fail:
1573 log_unit_warning_errno(u, r, "Failed to initiate cleaning: %m");
1574 s->clean_result = SWAP_FAILURE_RESOURCES;
5dcadb4c 1575 s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
a8b689b7
YW
1576 return r;
1577}
1578
1579static int swap_can_clean(Unit *u, ExecCleanMask *ret) {
1580 Swap *s = SWAP(u);
1581
1582 assert(s);
1583
1584 return exec_context_get_clean_mask(&s->exec_context, ret);
1585}
1586
705578c3 1587static int swap_can_start(Unit *u) {
9727f242
DDM
1588 Swap *s = SWAP(u);
1589 int r;
1590
1591 assert(s);
1592
1593 r = unit_test_start_limit(u);
1594 if (r < 0) {
1595 swap_enter_dead(s, SWAP_FAILURE_START_LIMIT_HIT);
1596 return r;
1597 }
1598
705578c3 1599 return 1;
9727f242
DDM
1600}
1601
e04aad61 1602static const char* const swap_exec_command_table[_SWAP_EXEC_COMMAND_MAX] = {
48d83e33 1603 [SWAP_EXEC_ACTIVATE] = "ExecActivate",
e04aad61
LP
1604 [SWAP_EXEC_DEACTIVATE] = "ExecDeactivate",
1605};
1606
1607DEFINE_STRING_TABLE_LOOKUP(swap_exec_command, SwapExecCommand);
1608
e1770af8 1609static const char* const swap_result_table[_SWAP_RESULT_MAX] = {
48d83e33
ZJS
1610 [SWAP_SUCCESS] = "success",
1611 [SWAP_FAILURE_RESOURCES] = "resources",
1612 [SWAP_FAILURE_TIMEOUT] = "timeout",
1613 [SWAP_FAILURE_EXIT_CODE] = "exit-code",
1614 [SWAP_FAILURE_SIGNAL] = "signal",
1615 [SWAP_FAILURE_CORE_DUMP] = "core-dump",
07299350 1616 [SWAP_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
e1770af8
LP
1617};
1618
1619DEFINE_STRING_TABLE_LOOKUP(swap_result, SwapResult);
1620
07b0b134 1621const UnitVTable swap_vtable = {
7d17cfbc 1622 .object_size = sizeof(Swap),
718db961
LP
1623 .exec_context_offset = offsetof(Swap, exec_context),
1624 .cgroup_context_offset = offsetof(Swap, cgroup_context),
1625 .kill_context_offset = offsetof(Swap, kill_context),
613b411c 1626 .exec_runtime_offset = offsetof(Swap, exec_runtime),
29206d46 1627 .dynamic_creds_offset = offsetof(Swap, dynamic_creds),
3ef63c31 1628
f975e971
LP
1629 .sections =
1630 "Unit\0"
1631 "Swap\0"
1632 "Install\0",
4ad49000 1633 .private_section = "Swap",
71645aca 1634
c80a9a33
LP
1635 .can_fail = true,
1636
4e85aff4 1637 .init = swap_init,
07b0b134 1638 .load = swap_load,
6e620bec 1639 .done = swap_done,
07b0b134
ML
1640
1641 .coldplug = swap_coldplug,
1642
1643 .dump = swap_dump,
1644
1645 .start = swap_start,
1646 .stop = swap_stop,
1647
8a0867d6 1648 .kill = swap_kill,
a8b689b7
YW
1649 .clean = swap_clean,
1650 .can_clean = swap_can_clean,
8a0867d6 1651
68db7a3b
ZJS
1652 .get_timeout = swap_get_timeout,
1653
07b0b134
ML
1654 .serialize = swap_serialize,
1655 .deserialize_item = swap_deserialize_item,
1656
1657 .active_state = swap_active_state,
1658 .sub_state_to_string = swap_sub_state_to_string,
1659
52a12341
YW
1660 .will_restart = unit_will_restart_default,
1661
f2f725e5 1662 .may_gc = swap_may_gc,
39c79477 1663 .is_extrinsic = swap_is_extrinsic,
07b0b134 1664
e04aad61 1665 .sigchld_event = swap_sigchld_event,
e04aad61
LP
1666
1667 .reset_failed = swap_reset_failed,
1668
291d565a
LP
1669 .control_pid = swap_control_pid,
1670
74c964d3
LP
1671 .bus_set_property = bus_swap_set_property,
1672 .bus_commit_properties = bus_swap_commit_properties,
07b0b134 1673
e04aad61 1674 .following = swap_following,
6210e7fc 1675 .following_set = swap_following_set,
5632e374 1676
6e620bec 1677 .enumerate = swap_enumerate,
c6918296 1678 .shutdown = swap_shutdown,
0faacd47 1679 .supported = swap_supported,
c6918296
MS
1680
1681 .status_message_formats = {
1682 .starting_stopping = {
1683 [0] = "Activating swap %s...",
1684 [1] = "Deactivating swap %s...",
1685 },
1686 .finished_start_job = {
1687 [JOB_DONE] = "Activated swap %s.",
1688 [JOB_FAILED] = "Failed to activate swap %s.",
c6918296
MS
1689 [JOB_TIMEOUT] = "Timed out activating swap %s.",
1690 },
1691 .finished_stop_job = {
1692 [JOB_DONE] = "Deactivated swap %s.",
1693 [JOB_FAILED] = "Failed deactivating swap %s.",
1694 [JOB_TIMEOUT] = "Timed out deactivating swap %s.",
1695 },
1696 },
9727f242 1697
705578c3 1698 .can_start = swap_can_start,
07b0b134 1699};