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