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