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