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