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