Debian Codegraph @

src/shutdown/detach-swap.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2010 ProFUSION embedded systems
4 ***/
5
6 #include <sys/swap.h>
7
8 #include "alloc-util.h"
9 #include "detach-swap.h"
10 #include "errno-util.h"
11 #include "libmount-util.h"
12 #include "list.h"
13 #include "log.h"
14
15 static void swap_device_free(SwapDevice **head, SwapDevice *m) {
16 assert(head);
17 assert(m);
18
19 LIST_REMOVE(swap_device, *head, m);
20
21 free(m->path);
22 free(m);
23 }
24
25 void swap_devices_list_free(SwapDevice **head) {
26 assert(head);
27
28 while (*head)
29 swap_device_free(head, *head);
30 }
31
32 int swap_list_get(const char *swaps, SwapDevice **head) {
33 _cleanup_(mnt_free_tablep) struct libmnt_table *t = NULL;
34 _cleanup_(mnt_free_iterp) struct libmnt_iter *i = NULL;
35 int r;
36
37 assert(head);
38
39 r = DLOPEN_LIBMOUNT(LOG_ERR, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED);
40 if (r < 0)
41 return r;
42
43 t = sym_mnt_new_table();
44 i = sym_mnt_new_iter(MNT_ITER_FORWARD);
45 if (!t || !i)
46 return log_oom();
47
48 r = sym_mnt_table_parse_swaps(t, swaps);
49 if (r == -ENOENT) /* no /proc/swaps is fine */
50 return 0;
51 if (r < 0)
52 return log_error_errno(r, "Failed to parse %s: %m", swaps ?: "/proc/swaps");
53
54 for (;;) {
55 struct libmnt_fs *fs;
56 _cleanup_free_ SwapDevice *swap = NULL;
57 const char *source;
58
59 r = sym_mnt_table_next_fs(t, i, &fs);
60 if (r == 1) /* EOF */
61 break;
62 if (r < 0)
63 return log_error_errno(r, "Failed to get next entry from %s: %m", swaps ?: "/proc/swaps");
64
65 source = sym_mnt_fs_get_source(fs);
66 if (!source)
67 continue;
68
69 swap = new0(SwapDevice, 1);
70 if (!swap)
71 return log_oom();
72
73 swap->path = strdup(source);
74 if (!swap->path)
75 return log_oom();
76
77 LIST_PREPEND(swap_device, *head, TAKE_PTR(swap));
78 }
79
80 return 0;
81 }
82
83 static int swap_points_list_off(SwapDevice **head, bool *changed) {
84 int n_failed = 0, r;
85
86 assert(head);
87 assert(changed);
88
89 LIST_FOREACH(swap_device, m, *head) {
90 log_info("Deactivating swap %s.", m->path);
91 r = RET_NERRNO(swapoff(m->path));
92 if (ERRNO_IS_NEG_DEVICE_ABSENT(r))
93 log_debug_errno(r, "Tried to deactivate swap '%s', but swap disappeared by now, ignoring: %m", m->path);
94 else if (r < 0) {
95 log_warning_errno(r, "Could not deactivate swap %s: %m", m->path);
96 n_failed++;
97 continue;
98 } else
99 *changed = true;
100
101 swap_device_free(head, m);
102 }
103
104 return n_failed;
105 }
106
107 int swapoff_all(bool *changed) {
108 _cleanup_(swap_devices_list_free) LIST_HEAD(SwapDevice, swap_list_head);
109 int r;
110
111 assert(changed);
112
113 LIST_HEAD_INIT(swap_list_head);
114
115 r = swap_list_get(NULL, &swap_list_head);
116 if (r < 0)
117 return r;
118
119 return swap_points_list_off(&swap_list_head, changed);
120 }