Debian Codegraph @

src/core/cgroup.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <sys/stat.h>
5 #include <unistd.h>
6
7 #include "sd-bus.h"
8 #include "sd-messages.h"
9
10 #include "af-list.h"
11 #include "alloc-util.h"
12 #include "blockdev-util.h"
13 #include "bpf-bind-iface.h"
14 #include "bpf-devices.h"
15 #include "bpf-firewall.h"
16 #include "bpf-foreign.h"
17 #include "bpf-program.h"
18 #include "bpf-restrict-ifaces.h"
19 #include "bpf-socket-bind.h"
20 #include "btrfs-util.h"
21 #include "bus-error.h"
22 #include "bus-locator.h"
23 #include "cgroup.h"
24 #include "cgroup-setup.h"
25 #include "cgroup-util.h"
26 #include "devnum-util.h"
27 #include "errno-util.h"
28 #include "extract-word.h"
29 #include "fd-util.h"
30 #include "fdset.h"
31 #include "fileio.h"
32 #include "in-addr-prefix-util.h"
33 #include "inotify-util.h"
34 #include "ip-protocol-list.h"
35 #include "limits-util.h"
36 #include "manager.h"
37 #include "mountpoint-util.h"
38 #include "netlink-internal.h"
39 #include "nulstr-util.h"
40 #include "parse-util.h"
41 #include "path-util.h"
42 #include "percent-util.h"
43 #include "pidref.h"
44 #include "process-util.h"
45 #include "procfs-util.h"
46 #include "serialize.h"
47 #include "set.h"
48 #include "special.h"
49 #include "stdio-util.h"
50 #include "string-table.h"
51 #include "string-util.h"
52 #include "strv.h"
53 #include "virt.h"
54
55 #if BPF_FRAMEWORK
56 #include "bpf-link.h"
57 #include "bpf-restrict-fs.h"
58 #endif
59
60 #define CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC (100 * USEC_PER_MSEC)
61
62 /* Returns the log level to use when cgroup attribute writes fail. When an attribute is missing or we have access
63 * problems we downgrade to LOG_DEBUG. This is supposed to be nice to container managers and kernels which want to mask
64 * out specific attributes from us. */
65 #define LOG_LEVEL_CGROUP_WRITE(r) ((ABS(r) == ENOENT || ERRNO_IS_FS_WRITE_REFUSED(r)) ? LOG_DEBUG : LOG_WARNING)
66
67 static void unit_remove_from_cgroup_empty_queue(Unit *u);
68
69 uint64_t cgroup_tasks_max_resolve(const CGroupTasksMax *tasks_max) {
70 if (tasks_max->scale == 0)
71 return tasks_max->value;
72
73 return system_tasks_max_scale(tasks_max->value, tasks_max->scale);
74 }
75
76 bool manager_owns_host_root_cgroup(Manager *m) {
77 assert(m);
78
79 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
80 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
81 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
82 * we run in any kind of container virtualization. */
83
84 if (MANAGER_IS_USER(m))
85 return false;
86
87 if (detect_container() > 0)
88 return false;
89
90 return empty_or_root(m->cgroup_root);
91 }
92
93 bool unit_has_host_root_cgroup(const Unit *u) {
94 assert(u);
95 assert(u->manager);
96
97 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
98 * the manager manages the root cgroup. */
99
100 if (!manager_owns_host_root_cgroup(u->manager))
101 return false;
102
103 return unit_has_name(u, SPECIAL_ROOT_SLICE);
104 }
105
106 bool unit_has_startup_cgroup_constraints(Unit *u) {
107 assert(u);
108
109 /* Returns true if this unit has any directives which apply during
110 * startup/shutdown phases. */
111
112 CGroupContext *c;
113
114 c = unit_get_cgroup_context(u);
115 if (!c)
116 return false;
117
118 return c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
119 c->startup_cpuset_cpus.set ||
120 c->startup_cpuset_mems.set ||
121 c->startup_memory_high_set ||
122 c->startup_memory_max_set ||
123 c->startup_memory_swap_max_set||
124 c->startup_memory_zswap_max_set ||
125 c->startup_memory_low_set;
126 }
127
128 static int set_attribute_and_warn(Unit *u, const char *attribute, const char *value) {
129 int r;
130
131 assert(u);
132 assert(attribute);
133 assert(value);
134
135 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
136 if (!crt || !crt->cgroup_path)
137 return -EOWNERDEAD;
138
139 r = cg_set_attribute(crt->cgroup_path, attribute, value);
140 if (r < 0)
141 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to set '%s' attribute on '%s' to '%.*s': %m",
142 attribute, empty_to_root(crt->cgroup_path), (int) strcspn(value, NEWLINE), value);
143
144 return r;
145 }
146
147 void cgroup_context_init(CGroupContext *c) {
148 assert(c);
149
150 /* Initialize everything to the kernel defaults. When initializing a bool member to 'true', make
151 * sure to serialize in execute-serialize.c using serialize_bool() instead of
152 * serialize_bool_elide(), as sd-executor will initialize here to 'true', but serialize_bool_elide()
153 * skips serialization if the value is 'false' (as that's the common default), so if the value at
154 * runtime is zero it would be lost after deserialization. Same when initializing uint64_t and other
155 * values, update/add a conditional serialization check. This is to minimize the amount of
156 * serialized data that is sent to the sd-executor, so that there is less work to do on the default
157 * cases. */
158
159 *c = (CGroupContext) {
160 .cpu_weight = CGROUP_WEIGHT_INVALID,
161 .startup_cpu_weight = CGROUP_WEIGHT_INVALID,
162 .cpu_quota_per_sec_usec = USEC_INFINITY,
163 .cpu_quota_period_usec = USEC_INFINITY,
164
165 .memory_high = CGROUP_LIMIT_MAX,
166 .startup_memory_high = CGROUP_LIMIT_MAX,
167 .memory_max = CGROUP_LIMIT_MAX,
168 .startup_memory_max = CGROUP_LIMIT_MAX,
169 .memory_swap_max = CGROUP_LIMIT_MAX,
170 .startup_memory_swap_max = CGROUP_LIMIT_MAX,
171 .memory_zswap_max = CGROUP_LIMIT_MAX,
172 .startup_memory_zswap_max = CGROUP_LIMIT_MAX,
173
174 .memory_zswap_writeback = true,
175
176 .io_weight = CGROUP_WEIGHT_INVALID,
177 .startup_io_weight = CGROUP_WEIGHT_INVALID,
178
179 .tasks_max = CGROUP_TASKS_MAX_UNSET,
180
181 .cpuset_partition = _CPUSET_PARTITION_INVALID,
182
183 .moom_swap = MANAGED_OOM_AUTO,
184 .moom_mem_pressure = MANAGED_OOM_AUTO,
185 .moom_preference = MANAGED_OOM_PREFERENCE_NONE,
186 /* The default duration value in oomd.conf will be used when
187 * moom_mem_pressure_duration_usec is set to infinity. */
188 .moom_mem_pressure_duration_usec = USEC_INFINITY,
189
190 .pressure = {
191 [PRESSURE_MEMORY] = { .watch = _CGROUP_PRESSURE_WATCH_INVALID, .threshold_usec = USEC_INFINITY },
192 [PRESSURE_CPU] = { .watch = _CGROUP_PRESSURE_WATCH_INVALID, .threshold_usec = USEC_INFINITY },
193 [PRESSURE_IO] = { .watch = _CGROUP_PRESSURE_WATCH_INVALID, .threshold_usec = USEC_INFINITY },
194 },
195 };
196 }
197
198 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
199 assert(c);
200 assert(a);
201
202 LIST_REMOVE(device_allow, c->device_allow, a);
203 free(a->path);
204 free(a);
205 }
206
207 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
208 assert(c);
209 assert(w);
210
211 LIST_REMOVE(device_weights, c->io_device_weights, w);
212 free(w->path);
213 free(w);
214 }
215
216 void cgroup_context_free_io_device_latency(CGroupContext *c, CGroupIODeviceLatency *l) {
217 assert(c);
218 assert(l);
219
220 LIST_REMOVE(device_latencies, c->io_device_latencies, l);
221 free(l->path);
222 free(l);
223 }
224
225 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
226 assert(c);
227 assert(l);
228
229 LIST_REMOVE(device_limits, c->io_device_limits, l);
230 free(l->path);
231 free(l);
232 }
233
234 void cgroup_context_remove_bpf_foreign_program(CGroupContext *c, CGroupBPFForeignProgram *p) {
235 assert(c);
236 assert(p);
237
238 LIST_REMOVE(programs, c->bpf_foreign_programs, p);
239 free(p->bpffs_path);
240 free(p);
241 }
242
243 void cgroup_context_remove_socket_bind(CGroupSocketBindItem **head) {
244 assert(head);
245
246 LIST_CLEAR(socket_bind_items, *head, free);
247 }
248
249 void cgroup_context_done(CGroupContext *c) {
250 assert(c);
251
252 while (c->io_device_weights)
253 cgroup_context_free_io_device_weight(c, c->io_device_weights);
254
255 while (c->io_device_latencies)
256 cgroup_context_free_io_device_latency(c, c->io_device_latencies);
257
258 while (c->io_device_limits)
259 cgroup_context_free_io_device_limit(c, c->io_device_limits);
260
261 while (c->device_allow)
262 cgroup_context_free_device_allow(c, c->device_allow);
263
264 cgroup_context_remove_socket_bind(&c->socket_bind_allow);
265 cgroup_context_remove_socket_bind(&c->socket_bind_deny);
266
267 c->ip_address_allow = set_free(c->ip_address_allow);
268 c->ip_address_deny = set_free(c->ip_address_deny);
269
270 c->ip_filters_ingress = strv_free(c->ip_filters_ingress);
271 c->ip_filters_egress = strv_free(c->ip_filters_egress);
272
273 while (c->bpf_foreign_programs)
274 cgroup_context_remove_bpf_foreign_program(c, c->bpf_foreign_programs);
275
276 c->restrict_network_interfaces = set_free(c->restrict_network_interfaces);
277
278 c->bind_network_interface = mfree(c->bind_network_interface);
279
280 cpu_set_done(&c->cpuset_cpus);
281 cpu_set_done(&c->startup_cpuset_cpus);
282 cpu_set_done(&c->cpuset_mems);
283 cpu_set_done(&c->startup_cpuset_mems);
284
285 c->delegate_subgroup = mfree(c->delegate_subgroup);
286
287 c->moom_rules = strv_free(c->moom_rules);
288
289 nft_set_context_clear(&c->nft_set_context);
290 }
291
292 static int unit_get_kernel_memory_limit(Unit *u, const char *file, uint64_t *ret) {
293 assert(u);
294
295 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
296 if (!crt || !crt->cgroup_path)
297 return -EOWNERDEAD;
298
299 return cg_get_attribute_as_uint64(crt->cgroup_path, file, ret);
300 }
301
302 static int unit_compare_memory_limit(Unit *u, const char *property_name, uint64_t *ret_unit_value, uint64_t *ret_kernel_value) {
303 CGroupContext *c;
304 CGroupMask m;
305 const char *file;
306 uint64_t unit_value;
307 int r;
308
309 /* Compare kernel memcg configuration against our internal systemd state.
310 *
311 * Returns:
312 *
313 * <0: On error.
314 * 0: If the kernel memory setting doesn't match our configuration.
315 * >0: If the kernel memory setting matches our configuration.
316 *
317 * The following values are only guaranteed to be populated on return >=0:
318 *
319 * - ret_unit_value will contain our internal expected value for the unit, page-aligned.
320 * - ret_kernel_value will contain the actual value presented by the kernel. */
321
322 assert(u);
323 assert(ret_unit_value);
324 assert(ret_kernel_value);
325
326 /* The root slice doesn't have any controller files, so we can't compare anything. */
327 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
328 return -ENODATA;
329
330 /* It's possible to have MemoryFoo set without systemd wanting to have the memory controller enabled,
331 * for example, in the case of DisableControllers= or cgroup_disable on the kernel command line. To
332 * avoid specious errors in these scenarios, check that we even expect the memory controller to be
333 * enabled at all. */
334 m = unit_get_target_mask(u);
335 if (!FLAGS_SET(m, CGROUP_MASK_MEMORY))
336 return -ENODATA;
337
338 assert_se(c = unit_get_cgroup_context(u));
339
340 bool startup = u->manager && IN_SET(manager_state(u->manager), MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING);
341
342 if (streq(property_name, "MemoryLow")) {
343 unit_value = c->memory_low;
344 file = "memory.low";
345 } else if (startup && streq(property_name, "StartupMemoryLow")) {
346 unit_value = c->startup_memory_low;
347 file = "memory.low";
348 } else if (streq(property_name, "MemoryMin")) {
349 unit_value = c->memory_min;
350 file = "memory.min";
351 } else if (streq(property_name, "MemoryHigh")) {
352 unit_value = c->memory_high;
353 file = "memory.high";
354 } else if (startup && streq(property_name, "StartupMemoryHigh")) {
355 unit_value = c->startup_memory_high;
356 file = "memory.high";
357 } else if (streq(property_name, "MemoryMax")) {
358 unit_value = c->memory_max;
359 file = "memory.max";
360 } else if (startup && streq(property_name, "StartupMemoryMax")) {
361 unit_value = c->startup_memory_max;
362 file = "memory.max";
363 } else if (streq(property_name, "MemorySwapMax")) {
364 unit_value = c->memory_swap_max;
365 file = "memory.swap.max";
366 } else if (startup && streq(property_name, "StartupMemorySwapMax")) {
367 unit_value = c->startup_memory_swap_max;
368 file = "memory.swap.max";
369 } else if (streq(property_name, "MemoryZSwapMax")) {
370 unit_value = c->memory_zswap_max;
371 file = "memory.zswap.max";
372 } else if (startup && streq(property_name, "StartupMemoryZSwapMax")) {
373 unit_value = c->startup_memory_zswap_max;
374 file = "memory.zswap.max";
375 } else
376 return -EINVAL;
377
378 r = unit_get_kernel_memory_limit(u, file, ret_kernel_value);
379 if (r < 0)
380 return log_unit_debug_errno(u, r, "Failed to parse %s: %m", file);
381
382 /* It's intended (soon) in a future kernel to not expose cgroup memory limits rounded to page
383 * boundaries, but instead separate the user-exposed limit, which is whatever userspace told us, from
384 * our internal page-counting. To support those future kernels, just check the value itself first
385 * without any page-alignment. */
386 if (*ret_kernel_value == unit_value) {
387 *ret_unit_value = unit_value;
388 return 1;
389 }
390
391 /* The current kernel behaviour, by comparison, is that even if you write a particular number of
392 * bytes into a cgroup memory file, it always returns that number page-aligned down (since the kernel
393 * internally stores cgroup limits in pages). As such, so long as it aligns properly, everything is
394 * cricket. */
395 if (unit_value != CGROUP_LIMIT_MAX)
396 unit_value = PAGE_ALIGN_DOWN(unit_value);
397
398 *ret_unit_value = unit_value;
399
400 return *ret_kernel_value == *ret_unit_value;
401 }
402
403 #define FORMAT_CGROUP_DIFF_MAX 128
404
405 static char *format_cgroup_memory_limit_comparison(Unit *u, const char *property_name, char *buf, size_t l) {
406 uint64_t kval, sval;
407 int r;
408
409 assert(u);
410 assert(property_name);
411 assert(buf);
412 assert(l > 0);
413
414 r = unit_compare_memory_limit(u, property_name, &sval, &kval);
415
416 /* memory.swap.max is special in that it relies on CONFIG_MEMCG_SWAP (and the default swapaccount=1).
417 * In the absence of reliably being able to detect whether memcg swap support is available or not,
418 * only complain if the error is not ENOENT. This is similarly the case for memory.zswap.max relying
419 * on CONFIG_ZSWAP. */
420 if (r > 0 || IN_SET(r, -ENODATA, -EOWNERDEAD) ||
421 (r == -ENOENT && STR_IN_SET(property_name,
422 "MemorySwapMax",
423 "StartupMemorySwapMax",
424 "MemoryZSwapMax",
425 "StartupMemoryZSwapMax")))
426 buf[0] = 0;
427 else if (r < 0) {
428 errno = -r;
429 (void) snprintf(buf, l, " (error getting kernel value: %m)");
430 } else
431 (void) snprintf(buf, l, " (different value in kernel: %" PRIu64 ")", kval);
432
433 return buf;
434 }
435
436 const char* cgroup_device_permissions_to_string(CGroupDevicePermissions p) {
437 static const char *table[_CGROUP_DEVICE_PERMISSIONS_MAX] = {
438 /* Lets simply define a table with every possible combination. As long as those are just 8 we
439 * can get away with it. If this ever grows to more we need to revisit this logic though. */
440 [0] = "",
441 [CGROUP_DEVICE_READ] = "r",
442 [CGROUP_DEVICE_WRITE] = "w",
443 [CGROUP_DEVICE_MKNOD] = "m",
444 [CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE] = "rw",
445 [CGROUP_DEVICE_READ|CGROUP_DEVICE_MKNOD] = "rm",
446 [CGROUP_DEVICE_WRITE|CGROUP_DEVICE_MKNOD] = "wm",
447 [CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE|CGROUP_DEVICE_MKNOD] = "rwm",
448 };
449
450 if (p < 0 || p >= _CGROUP_DEVICE_PERMISSIONS_MAX)
451 return NULL;
452
453 return table[p];
454 }
455
456 CGroupDevicePermissions cgroup_device_permissions_from_string(const char *s) {
457 CGroupDevicePermissions p = 0;
458
459 if (!s)
460 return _CGROUP_DEVICE_PERMISSIONS_INVALID;
461
462 for (const char *c = s; *c; c++) {
463 if (*c == 'r')
464 p |= CGROUP_DEVICE_READ;
465 else if (*c == 'w')
466 p |= CGROUP_DEVICE_WRITE;
467 else if (*c == 'm')
468 p |= CGROUP_DEVICE_MKNOD;
469 else
470 return _CGROUP_DEVICE_PERMISSIONS_INVALID;
471 }
472
473 return p;
474 }
475
476 void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
477 _cleanup_free_ char *disable_controllers_str = NULL, *delegate_controllers_str = NULL, *cpuset_cpus = NULL, *cpuset_mems = NULL, *startup_cpuset_cpus = NULL, *startup_cpuset_mems = NULL;
478 CGroupContext *c;
479 struct in_addr_prefix *iaai;
480 char cda[FORMAT_CGROUP_DIFF_MAX], cdb[FORMAT_CGROUP_DIFF_MAX], cdc[FORMAT_CGROUP_DIFF_MAX], cdd[FORMAT_CGROUP_DIFF_MAX],
481 cde[FORMAT_CGROUP_DIFF_MAX], cdf[FORMAT_CGROUP_DIFF_MAX], cdg[FORMAT_CGROUP_DIFF_MAX], cdh[FORMAT_CGROUP_DIFF_MAX],
482 cdi[FORMAT_CGROUP_DIFF_MAX], cdj[FORMAT_CGROUP_DIFF_MAX], cdk[FORMAT_CGROUP_DIFF_MAX];
483
484 assert(u);
485 assert(f);
486
487 assert_se(c = unit_get_cgroup_context(u));
488
489 prefix = strempty(prefix);
490
491 (void) cg_mask_to_string(c->disable_controllers, &disable_controllers_str);
492 (void) cg_mask_to_string(c->delegate_controllers, &delegate_controllers_str);
493
494 /* "Delegate=" means "yes, but no controllers". Show this as "(none)". */
495 const char *delegate_str = delegate_controllers_str ?: c->delegate ? "(none)" : "no";
496
497 cpuset_cpus = cpu_set_to_range_string(&c->cpuset_cpus);
498 startup_cpuset_cpus = cpu_set_to_range_string(&c->startup_cpuset_cpus);
499 cpuset_mems = cpu_set_to_range_string(&c->cpuset_mems);
500 startup_cpuset_mems = cpu_set_to_range_string(&c->startup_cpuset_mems);
501
502 fprintf(f,
503 "%sIOAccounting: %s\n"
504 "%sMemoryAccounting: %s\n"
505 "%sTasksAccounting: %s\n"
506 "%sIPAccounting: %s\n"
507 "%sCPUWeight: %" PRIu64 "\n"
508 "%sStartupCPUWeight: %" PRIu64 "\n"
509 "%sCPUQuotaPerSecSec: %s\n"
510 "%sCPUQuotaPeriodSec: %s\n"
511 "%sAllowedCPUs: %s\n"
512 "%sStartupAllowedCPUs: %s\n"
513 "%sAllowedMemoryNodes: %s\n"
514 "%sStartupAllowedMemoryNodes: %s\n"
515 "%sCPUSetPartition: %s\n"
516 "%sIOWeight: %" PRIu64 "\n"
517 "%sStartupIOWeight: %" PRIu64 "\n"
518 "%sMemoryMin: %" PRIu64 "%s\n"
519 "%sMemoryLow: %" PRIu64 "%s\n"
520 "%sStartupMemoryLow: %" PRIu64 "%s\n"
521 "%sMemoryHigh: %" PRIu64 "%s\n"
522 "%sStartupMemoryHigh: %" PRIu64 "%s\n"
523 "%sMemoryMax: %" PRIu64 "%s\n"
524 "%sStartupMemoryMax: %" PRIu64 "%s\n"
525 "%sMemorySwapMax: %" PRIu64 "%s\n"
526 "%sStartupMemorySwapMax: %" PRIu64 "%s\n"
527 "%sMemoryZSwapMax: %" PRIu64 "%s\n"
528 "%sStartupMemoryZSwapMax: %" PRIu64 "%s\n"
529 "%sMemoryZSwapWriteback: %s\n"
530 "%sTasksMax: %" PRIu64 "\n"
531 "%sDevicePolicy: %s\n"
532 "%sDisableControllers: %s\n"
533 "%sDelegate: %s\n"
534 "%sManagedOOMSwap: %s\n"
535 "%sManagedOOMMemoryPressure: %s\n"
536 "%sManagedOOMMemoryPressureLimit: " PERMYRIAD_AS_PERCENT_FORMAT_STR "\n"
537 "%sManagedOOMPreference: %s\n"
538 "%sMemoryPressureWatch: %s\n"
539 "%sCPUPressureWatch: %s\n"
540 "%sIOPressureWatch: %s\n"
541 "%sCoredumpReceive: %s\n",
542 prefix, yes_no(c->io_accounting),
543 prefix, yes_no(c->memory_accounting),
544 prefix, yes_no(c->tasks_accounting),
545 prefix, yes_no(c->ip_accounting),
546 prefix, c->cpu_weight,
547 prefix, c->startup_cpu_weight,
548 prefix, FORMAT_TIMESPAN(c->cpu_quota_per_sec_usec, 1),
549 prefix, FORMAT_TIMESPAN(c->cpu_quota_period_usec, 1),
550 prefix, strempty(cpuset_cpus),
551 prefix, strempty(startup_cpuset_cpus),
552 prefix, strempty(cpuset_mems),
553 prefix, strempty(startup_cpuset_mems),
554 prefix, strna(cpuset_partition_to_string(c->cpuset_partition)),
555 prefix, c->io_weight,
556 prefix, c->startup_io_weight,
557 prefix, c->memory_min, format_cgroup_memory_limit_comparison(u, "MemoryMin", cda, sizeof(cda)),
558 prefix, c->memory_low, format_cgroup_memory_limit_comparison(u, "MemoryLow", cdb, sizeof(cdb)),
559 prefix, c->startup_memory_low, format_cgroup_memory_limit_comparison(u, "StartupMemoryLow", cdc, sizeof(cdc)),
560 prefix, c->memory_high, format_cgroup_memory_limit_comparison(u, "MemoryHigh", cdd, sizeof(cdd)),
561 prefix, c->startup_memory_high, format_cgroup_memory_limit_comparison(u, "StartupMemoryHigh", cde, sizeof(cde)),
562 prefix, c->memory_max, format_cgroup_memory_limit_comparison(u, "MemoryMax", cdf, sizeof(cdf)),
563 prefix, c->startup_memory_max, format_cgroup_memory_limit_comparison(u, "StartupMemoryMax", cdg, sizeof(cdg)),
564 prefix, c->memory_swap_max, format_cgroup_memory_limit_comparison(u, "MemorySwapMax", cdh, sizeof(cdh)),
565 prefix, c->startup_memory_swap_max, format_cgroup_memory_limit_comparison(u, "StartupMemorySwapMax", cdi, sizeof(cdi)),
566 prefix, c->memory_zswap_max, format_cgroup_memory_limit_comparison(u, "MemoryZSwapMax", cdj, sizeof(cdj)),
567 prefix, c->startup_memory_zswap_max, format_cgroup_memory_limit_comparison(u, "StartupMemoryZSwapMax", cdk, sizeof(cdk)),
568 prefix, yes_no(c->memory_zswap_writeback),
569 prefix, cgroup_tasks_max_resolve(&c->tasks_max),
570 prefix, cgroup_device_policy_to_string(c->device_policy),
571 prefix, strempty(disable_controllers_str),
572 prefix, delegate_str,
573 prefix, managed_oom_mode_to_string(c->moom_swap),
574 prefix, managed_oom_mode_to_string(c->moom_mem_pressure),
575 prefix, PERMYRIAD_AS_PERCENT_FORMAT_VAL(UINT32_SCALE_TO_PERMYRIAD(c->moom_mem_pressure_limit)),
576 prefix, managed_oom_preference_to_string(c->moom_preference),
577 prefix, cgroup_pressure_watch_to_string(c->pressure[PRESSURE_MEMORY].watch),
578 prefix, cgroup_pressure_watch_to_string(c->pressure[PRESSURE_CPU].watch),
579 prefix, cgroup_pressure_watch_to_string(c->pressure[PRESSURE_IO].watch),
580 prefix, yes_no(c->coredump_receive));
581
582 if (c->delegate_subgroup)
583 fprintf(f, "%sDelegateSubgroup: %s\n",
584 prefix, c->delegate_subgroup);
585
586 if (c->bind_network_interface)
587 fprintf(f, "%sBindNetworkInterface: %s\n",
588 prefix, c->bind_network_interface);
589
590 if (c->pressure[PRESSURE_MEMORY].threshold_usec != USEC_INFINITY)
591 fprintf(f, "%sMemoryPressureThresholdSec: %s\n",
592 prefix, FORMAT_TIMESPAN(c->pressure[PRESSURE_MEMORY].threshold_usec, 1));
593
594 if (c->pressure[PRESSURE_CPU].threshold_usec != USEC_INFINITY)
595 fprintf(f, "%sCPUPressureThresholdSec: %s\n",
596 prefix, FORMAT_TIMESPAN(c->pressure[PRESSURE_CPU].threshold_usec, 1));
597
598 if (c->pressure[PRESSURE_IO].threshold_usec != USEC_INFINITY)
599 fprintf(f, "%sIOPressureThresholdSec: %s\n",
600 prefix, FORMAT_TIMESPAN(c->pressure[PRESSURE_IO].threshold_usec, 1));
601
602 if (c->moom_mem_pressure_duration_usec != USEC_INFINITY)
603 fprintf(f, "%sManagedOOMMemoryPressureDurationSec: %s\n",
604 prefix, FORMAT_TIMESPAN(c->moom_mem_pressure_duration_usec, 1));
605
606 LIST_FOREACH(device_allow, a, c->device_allow)
607 /* strna() below should be redundant, for avoiding -Werror=format-overflow= error. See #30223. */
608 fprintf(f,
609 "%sDeviceAllow: %s %s\n",
610 prefix,
611 a->path,
612 strna(cgroup_device_permissions_to_string(a->permissions)));
613
614 LIST_FOREACH(device_weights, iw, c->io_device_weights)
615 fprintf(f,
616 "%sIODeviceWeight: %s %" PRIu64 "\n",
617 prefix,
618 iw->path,
619 iw->weight);
620
621 LIST_FOREACH(device_latencies, l, c->io_device_latencies)
622 fprintf(f,
623 "%sIODeviceLatencyTargetSec: %s %s\n",
624 prefix,
625 l->path,
626 FORMAT_TIMESPAN(l->target_usec, 1));
627
628 LIST_FOREACH(device_limits, il, c->io_device_limits)
629 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
630 if (il->limits[type] != cgroup_io_limit_defaults[type])
631 fprintf(f,
632 "%s%s: %s %s\n",
633 prefix,
634 cgroup_io_limit_type_to_string(type),
635 il->path,
636 FORMAT_BYTES(il->limits[type]));
637
638 SET_FOREACH(iaai, c->ip_address_allow)
639 fprintf(f, "%sIPAddressAllow: %s\n", prefix,
640 IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
641 SET_FOREACH(iaai, c->ip_address_deny)
642 fprintf(f, "%sIPAddressDeny: %s\n", prefix,
643 IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
644
645 STRV_FOREACH(path, c->ip_filters_ingress)
646 fprintf(f, "%sIPIngressFilterPath: %s\n", prefix, *path);
647 STRV_FOREACH(path, c->ip_filters_egress)
648 fprintf(f, "%sIPEgressFilterPath: %s\n", prefix, *path);
649
650 LIST_FOREACH(programs, p, c->bpf_foreign_programs)
651 fprintf(f, "%sBPFProgram: %s:%s",
652 prefix, bpf_cgroup_attach_type_to_string(p->attach_type), p->bpffs_path);
653
654 if (c->socket_bind_allow) {
655 fprintf(f, "%sSocketBindAllow: ", prefix);
656 cgroup_context_dump_socket_bind_items(c->socket_bind_allow, f);
657 fputc('\n', f);
658 }
659
660 if (c->socket_bind_deny) {
661 fprintf(f, "%sSocketBindDeny: ", prefix);
662 cgroup_context_dump_socket_bind_items(c->socket_bind_deny, f);
663 fputc('\n', f);
664 }
665
666 if (c->restrict_network_interfaces) {
667 char *iface;
668 SET_FOREACH(iface, c->restrict_network_interfaces)
669 fprintf(f, "%sRestrictNetworkInterfaces: %s\n", prefix, iface);
670 }
671
672 FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets)
673 fprintf(f, "%sNFTSet: %s:%s:%s:%s\n", prefix, nft_set_source_to_string(nft_set->source),
674 nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set);
675
676 STRV_FOREACH(rule, c->moom_rules)
677 fprintf(f, "%sOOMRules: %s\n", prefix, *rule);
678 }
679
680 void cgroup_context_dump_socket_bind_item(const CGroupSocketBindItem *item, FILE *f) {
681 const char *family, *colon1, *protocol = "", *colon2 = "";
682
683 family = strempty(af_to_ipv4_ipv6(item->address_family));
684 colon1 = isempty(family) ? "" : ":";
685
686 if (item->ip_protocol != 0) {
687 protocol = ip_protocol_to_tcp_udp(item->ip_protocol);
688 colon2 = ":";
689 }
690
691 if (item->nr_ports == 0)
692 fprintf(f, "%s%s%s%sany", family, colon1, protocol, colon2);
693 else if (item->nr_ports == 1)
694 fprintf(f, "%s%s%s%s%" PRIu16, family, colon1, protocol, colon2, item->port_min);
695 else {
696 uint16_t port_max = item->port_min + item->nr_ports - 1;
697 fprintf(f, "%s%s%s%s%" PRIu16 "-%" PRIu16, family, colon1, protocol, colon2,
698 item->port_min, port_max);
699 }
700 }
701
702 void cgroup_context_dump_socket_bind_items(const CGroupSocketBindItem *items, FILE *f) {
703 bool first = true;
704
705 LIST_FOREACH(socket_bind_items, bi, items) {
706 if (first)
707 first = false;
708 else
709 fputc(' ', f);
710
711 cgroup_context_dump_socket_bind_item(bi, f);
712 }
713 }
714
715 int cgroup_context_add_device_allow(CGroupContext *c, const char *dev, CGroupDevicePermissions p) {
716 _cleanup_free_ CGroupDeviceAllow *a = NULL;
717 _cleanup_free_ char *d = NULL;
718
719 assert(c);
720 assert(dev);
721 assert(p >= 0 && p < _CGROUP_DEVICE_PERMISSIONS_MAX);
722
723 if (p == 0)
724 p = _CGROUP_DEVICE_PERMISSIONS_ALL;
725
726 a = new(CGroupDeviceAllow, 1);
727 if (!a)
728 return -ENOMEM;
729
730 d = strdup(dev);
731 if (!d)
732 return -ENOMEM;
733
734 *a = (CGroupDeviceAllow) {
735 .path = TAKE_PTR(d),
736 .permissions = p,
737 };
738
739 LIST_PREPEND(device_allow, c->device_allow, a);
740 TAKE_PTR(a);
741
742 return 0;
743 }
744
745 int cgroup_context_add_or_update_device_allow(CGroupContext *c, const char *dev, CGroupDevicePermissions p) {
746 assert(c);
747 assert(dev);
748 assert(p >= 0 && p < _CGROUP_DEVICE_PERMISSIONS_MAX);
749
750 if (p == 0)
751 p = _CGROUP_DEVICE_PERMISSIONS_ALL;
752
753 LIST_FOREACH(device_allow, b, c->device_allow)
754 if (path_equal(b->path, dev)) {
755 b->permissions = p;
756 return 0;
757 }
758
759 return cgroup_context_add_device_allow(c, dev, p);
760 }
761
762 int cgroup_context_add_bpf_foreign_program(CGroupContext *c, uint32_t attach_type, const char *bpffs_path) {
763 CGroupBPFForeignProgram *p;
764 _cleanup_free_ char *d = NULL;
765
766 assert(c);
767 assert(bpffs_path);
768
769 if (!path_is_normalized(bpffs_path) || !path_is_absolute(bpffs_path))
770 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not normalized.");
771
772 d = strdup(bpffs_path);
773 if (!d)
774 return log_oom();
775
776 p = new(CGroupBPFForeignProgram, 1);
777 if (!p)
778 return log_oom();
779
780 *p = (CGroupBPFForeignProgram) {
781 .attach_type = attach_type,
782 .bpffs_path = TAKE_PTR(d),
783 };
784
785 LIST_PREPEND(programs, c->bpf_foreign_programs, TAKE_PTR(p));
786
787 return 0;
788 }
789
790 static void unit_set_xattr_graceful(Unit *u, const char *name, const void *data, size_t size) {
791 int r;
792
793 assert(u);
794 assert(name);
795
796 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
797 if (!crt || !crt->cgroup_path)
798 return;
799
800 r = cg_set_xattr(crt->cgroup_path, name, data, size, 0);
801 if (r < 0)
802 log_unit_debug_errno(u, r, "Failed to set '%s' xattr on control group %s, ignoring: %m", name, empty_to_root(crt->cgroup_path));
803 }
804
805 static void unit_remove_xattr_graceful(Unit *u, const char *name) {
806 int r;
807
808 assert(u);
809 assert(name);
810
811 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
812 if (!crt || !crt->cgroup_path)
813 return;
814
815 r = cg_remove_xattr(crt->cgroup_path, name);
816 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
817 log_unit_debug_errno(u, r, "Failed to remove '%s' xattr flag on control group %s, ignoring: %m", name, empty_to_root(crt->cgroup_path));
818 }
819
820 static void cgroup_oomd_xattr_apply(Unit *u) {
821 CGroupContext *c;
822
823 assert(u);
824
825 c = unit_get_cgroup_context(u);
826 if (!c)
827 return;
828
829 if (c->moom_preference == MANAGED_OOM_PREFERENCE_OMIT)
830 unit_set_xattr_graceful(u, "user.oomd_omit", "1", 1);
831
832 if (c->moom_preference == MANAGED_OOM_PREFERENCE_AVOID)
833 unit_set_xattr_graceful(u, "user.oomd_avoid", "1", 1);
834
835 if (c->moom_preference != MANAGED_OOM_PREFERENCE_AVOID)
836 unit_remove_xattr_graceful(u, "user.oomd_avoid");
837
838 if (c->moom_preference != MANAGED_OOM_PREFERENCE_OMIT)
839 unit_remove_xattr_graceful(u, "user.oomd_omit");
840 }
841
842 static int cgroup_log_xattr_apply(Unit *u) {
843 ExecContext *c;
844 size_t len, allowed_patterns_len, denied_patterns_len;
845 _cleanup_free_ char *patterns = NULL, *allowed_patterns = NULL, *denied_patterns = NULL;
846 char *last;
847 int r;
848
849 assert(u);
850
851 c = unit_get_exec_context(u);
852 if (!c)
853 /* Some unit types have a cgroup context but no exec context, so we do not log
854 * any error here to avoid confusion. */
855 return 0;
856
857 if (set_isempty(c->log_filter_allowed_patterns) && set_isempty(c->log_filter_denied_patterns)) {
858 unit_remove_xattr_graceful(u, "user.journald_log_filter_patterns");
859 return 0;
860 }
861
862 r = set_make_nulstr(c->log_filter_allowed_patterns, &allowed_patterns, &allowed_patterns_len);
863 if (r < 0)
864 return log_debug_errno(r, "Failed to make nulstr from set: %m");
865
866 r = set_make_nulstr(c->log_filter_denied_patterns, &denied_patterns, &denied_patterns_len);
867 if (r < 0)
868 return log_debug_errno(r, "Failed to make nulstr from set: %m");
869
870 /* Use nul character separated strings without trailing nul */
871 allowed_patterns_len = LESS_BY(allowed_patterns_len, 1u);
872 denied_patterns_len = LESS_BY(denied_patterns_len, 1u);
873
874 len = allowed_patterns_len + 1 + denied_patterns_len;
875 patterns = new(char, len);
876 if (!patterns)
877 return log_oom_debug();
878
879 last = mempcpy_safe(patterns, allowed_patterns, allowed_patterns_len);
880 *(last++) = '\xff';
881 memcpy_safe(last, denied_patterns, denied_patterns_len);
882
883 unit_set_xattr_graceful(u, "user.journald_log_filter_patterns", patterns, len);
884
885 return 0;
886 }
887
888 static void cgroup_invocation_id_xattr_apply(Unit *u) {
889 bool b;
890
891 assert(u);
892
893 b = !sd_id128_is_null(u->invocation_id);
894 FOREACH_STRING(xn, "trusted.invocation_id", "user.invocation_id") {
895 if (b)
896 unit_set_xattr_graceful(u, xn, SD_ID128_TO_STRING(u->invocation_id), 32);
897 else
898 unit_remove_xattr_graceful(u, xn);
899 }
900 }
901
902 static void cgroup_coredump_xattr_apply(Unit *u) {
903 CGroupContext *c;
904
905 assert(u);
906
907 c = unit_get_cgroup_context(u);
908 if (!c)
909 return;
910
911 if (unit_cgroup_delegate(u) && c->coredump_receive)
912 unit_set_xattr_graceful(u, "user.coredump_receive", "1", 1);
913 else
914 unit_remove_xattr_graceful(u, "user.coredump_receive");
915 }
916
917 static void cgroup_delegate_xattr_apply(Unit *u) {
918 bool b;
919
920 assert(u);
921
922 /* Indicate on the cgroup whether delegation is on, via an xattr. This is best-effort, as old kernels
923 * didn't support xattrs on cgroups at all. Later they got support for setting 'trusted.*' xattrs,
924 * and even later 'user.*' xattrs. We started setting this field when 'trusted.*' was added, and
925 * given this is now pretty much API, let's continue to support that. But also set 'user.*' as well,
926 * since it is readable by any user, not just CAP_SYS_ADMIN. This hence comes with slightly weaker
927 * security (as users who got delegated cgroups could turn it off if they like), but this shouldn't
928 * be a big problem given this communicates delegation state to clients, but the manager never reads
929 * it. */
930 b = unit_cgroup_delegate(u);
931 FOREACH_STRING(xn, "trusted.delegate", "user.delegate") {
932 if (b)
933 unit_set_xattr_graceful(u, xn, "1", 1);
934 else
935 unit_remove_xattr_graceful(u, xn);
936 }
937 }
938
939 static void cgroup_survive_xattr_apply(Unit *u) {
940 assert(u);
941
942 if (u->survive_final_kill_signal)
943 unit_set_xattr_graceful(u, "user.survive_final_kill_signal", "1", 1);
944 else
945 unit_remove_xattr_graceful(u, "user.survive_final_kill_signal");
946 }
947
948 static void cgroup_xattr_apply(Unit *u) {
949 assert(u);
950
951 /* The 'user.*' xattrs can be set from a user manager. */
952 cgroup_oomd_xattr_apply(u);
953 cgroup_log_xattr_apply(u);
954 cgroup_coredump_xattr_apply(u);
955
956 if (!MANAGER_IS_SYSTEM(u->manager))
957 return;
958
959 cgroup_invocation_id_xattr_apply(u);
960 cgroup_delegate_xattr_apply(u);
961 cgroup_survive_xattr_apply(u);
962 }
963
964 static int lookup_block_device(const char *p, dev_t *ret) {
965 dev_t rdev, dev = 0;
966 mode_t mode;
967 int r;
968
969 assert(p);
970 assert(ret);
971
972 r = device_path_parse_major_minor(p, &mode, &rdev);
973 if (r == -ENODEV) { /* not a parsable device node, need to go to disk */
974 struct stat st;
975
976 if (stat(p, &st) < 0)
977 return log_warning_errno(errno, "Couldn't stat device '%s': %m", p);
978
979 mode = st.st_mode;
980 rdev = st.st_rdev;
981 dev = st.st_dev;
982 } else if (r < 0)
983 return log_warning_errno(r, "Failed to parse major/minor from path '%s': %m", p);
984
985 if (S_ISCHR(mode))
986 return log_warning_errno(SYNTHETIC_ERRNO(ENOTBLK),
987 "Device node '%s' is a character device, but block device needed.", p);
988 if (S_ISBLK(mode))
989 *ret = rdev;
990 else if (major(dev) != 0)
991 *ret = dev; /* If this is not a device node then use the block device this file is stored on */
992 else {
993 /* If this is btrfs, getting the backing block device is a bit harder */
994 r = btrfs_get_block_device(p, ret);
995 if (r == -ENOTTY)
996 return log_warning_errno(SYNTHETIC_ERRNO(ENODEV),
997 "'%s' is not a block device node, and file system block device cannot be determined or is not local.", p);
998 if (r < 0)
999 return log_warning_errno(r, "Failed to determine block device backing btrfs file system '%s': %m", p);
1000 }
1001
1002 /* If this is a LUKS/DM device, recursively try to get the originating block device */
1003 (void) block_get_originating(*ret, ret, /* recursive= */ true);
1004
1005 /* If this is a partition, try to get the originating block device */
1006 (void) block_get_whole_disk(*ret, ret);
1007 return 0;
1008 }
1009
1010 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
1011 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
1012 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
1013 }
1014
1015 static bool cgroup_context_has_allowed_cpus(CGroupContext *c) {
1016 return c->cpuset_cpus.set || c->startup_cpuset_cpus.set;
1017 }
1018
1019 static bool cgroup_context_has_allowed_mems(CGroupContext *c) {
1020 return c->cpuset_mems.set || c->startup_cpuset_mems.set;
1021 }
1022
1023 uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
1024 assert(c);
1025
1026 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1027 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
1028 return c->startup_cpu_weight;
1029 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
1030 return c->cpu_weight;
1031 else
1032 return CGROUP_WEIGHT_DEFAULT;
1033 }
1034
1035 static CPUSet *cgroup_context_allowed_cpus(CGroupContext *c, ManagerState state) {
1036 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1037 c->startup_cpuset_cpus.set)
1038 return &c->startup_cpuset_cpus;
1039 else
1040 return &c->cpuset_cpus;
1041 }
1042
1043 static CPUSet *cgroup_context_allowed_mems(CGroupContext *c, ManagerState state) {
1044 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1045 c->startup_cpuset_mems.set)
1046 return &c->startup_cpuset_mems;
1047 else
1048 return &c->cpuset_mems;
1049 }
1050
1051 usec_t cgroup_cpu_adjust_period(usec_t period, usec_t quota, usec_t resolution, usec_t max_period) {
1052 /* kernel uses a minimum resolution of 1ms, so both period and (quota * period)
1053 * need to be higher than that boundary. quota is specified in USecPerSec.
1054 * Additionally, period must be at most max_period. */
1055 assert(quota > 0);
1056
1057 return MIN(MAX3(period, resolution, resolution * USEC_PER_SEC / quota), max_period);
1058 }
1059
1060 static usec_t cgroup_cpu_adjust_period_and_log(Unit *u, usec_t period, usec_t quota) {
1061 usec_t new_period;
1062
1063 assert(u);
1064
1065 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1066 if (!crt)
1067 return USEC_INFINITY;
1068
1069 if (quota == USEC_INFINITY)
1070 /* Always use default period for infinity quota. */
1071 return CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
1072
1073 if (period == USEC_INFINITY)
1074 /* Default period was requested. */
1075 period = CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
1076
1077 /* Clamp to interval [1ms, 1s] */
1078 new_period = cgroup_cpu_adjust_period(period, quota, USEC_PER_MSEC, USEC_PER_SEC);
1079
1080 if (new_period != period) {
1081 log_unit_full(u, crt->warned_clamping_cpu_quota_period ? LOG_DEBUG : LOG_WARNING,
1082 "Clamping CPU interval for cpu.max: period is now %s",
1083 FORMAT_TIMESPAN(new_period, 1));
1084 crt->warned_clamping_cpu_quota_period = true;
1085 }
1086
1087 return new_period;
1088 }
1089
1090 static void cgroup_apply_cpu_weight(Unit *u, uint64_t weight) {
1091 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1092
1093 if (weight == CGROUP_WEIGHT_IDLE)
1094 return;
1095 xsprintf(buf, "%" PRIu64 "\n", weight);
1096 (void) set_attribute_and_warn(u, "cpu.weight", buf);
1097 }
1098
1099 static void cgroup_apply_cpu_idle(Unit *u, uint64_t weight) {
1100 int r;
1101 bool is_idle;
1102 const char *idle_val;
1103
1104 assert(u);
1105
1106 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1107 if (!crt || !crt->cgroup_path)
1108 return;
1109
1110 is_idle = weight == CGROUP_WEIGHT_IDLE;
1111 idle_val = one_zero(is_idle);
1112 r = cg_set_attribute(crt->cgroup_path, "cpu.idle", idle_val);
1113 if (r < 0 && (r != -ENOENT || is_idle))
1114 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to set '%s' attribute on '%s' to '%s': %m",
1115 "cpu.idle", empty_to_root(crt->cgroup_path), idle_val);
1116 }
1117
1118 static void cgroup_apply_cpu_quota(Unit *u, usec_t quota, usec_t period) {
1119 char buf[(DECIMAL_STR_MAX(usec_t) + 1) * 2 + 1];
1120
1121 assert(u);
1122
1123 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
1124 if (quota != USEC_INFINITY)
1125 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
1126 MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC), period);
1127 else
1128 xsprintf(buf, "max " USEC_FMT "\n", period);
1129 (void) set_attribute_and_warn(u, "cpu.max", buf);
1130 }
1131
1132 static void cgroup_apply_cpuset(Unit *u, const char *name, const CPUSet *cpus) {
1133 _cleanup_free_ char *buf = NULL;
1134
1135 buf = cpu_set_to_range_string(cpus);
1136 if (!buf) {
1137 log_oom();
1138 return;
1139 }
1140
1141 (void) set_attribute_and_warn(u, name, buf);
1142 }
1143
1144 static int cgroup_cpuset_partition_invalid(const char *partition) {
1145 _cleanup_free_ char *part_str = NULL, *invalid = NULL;
1146 int r;
1147
1148 assert(partition);
1149
1150 /* An invalid line looks like <partition> invalid (<reason>) */
1151 r = extract_many_words(&partition, /* separators= */ NULL, /* flags= */ 0, &part_str, &invalid);
1152 if (r < 0)
1153 return r;
1154 if (r < 2)
1155 return false;
1156
1157 return streq_ptr(invalid, "invalid");
1158 }
1159
1160 static void cgroup_apply_cpuset_partition(Unit *u, const char *name, const char *partition) {
1161 _cleanup_free_ char *buf = NULL;
1162 CGroupRuntime *crt;
1163 int r;
1164
1165 assert(u);
1166 assert(name);
1167 assert(partition);
1168
1169 if (set_attribute_and_warn(u, name, partition) < 0)
1170 return;
1171
1172 /* We are writing and then reading back, crt is already checked while writing */
1173 crt = ASSERT_PTR(unit_get_cgroup_runtime(u));
1174
1175 r = cg_get_attribute(crt->cgroup_path, name, &buf);
1176 if (r < 0) {
1177 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to read back '%s' attribute on '%s' as '%.*s': %m",
1178 name, empty_to_root(crt->cgroup_path), (int) strcspn(partition, NEWLINE), partition);
1179 return;
1180 }
1181
1182 r = cgroup_cpuset_partition_invalid(buf);
1183 if (r < 0)
1184 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to read back '%s' attribute on '%s' as '%.*s': %m",
1185 name, empty_to_root(crt->cgroup_path), (int) strcspn(partition, NEWLINE), partition);
1186 else if (r)
1187 log_unit_warning(u, "Failed to set '%s' attribute on '%s' to '%.*s': %s",
1188 name, empty_to_root(crt->cgroup_path), (int) strcspn(partition, NEWLINE), partition, buf);
1189 }
1190
1191 static bool cgroup_context_has_io_config(CGroupContext *c) {
1192 assert(c);
1193
1194 return c->io_weight != CGROUP_WEIGHT_INVALID ||
1195 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
1196 c->io_device_weights ||
1197 c->io_device_latencies ||
1198 c->io_device_limits;
1199 }
1200
1201 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
1202 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1203 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
1204 return c->startup_io_weight;
1205 if (c->io_weight != CGROUP_WEIGHT_INVALID)
1206 return c->io_weight;
1207 return CGROUP_WEIGHT_DEFAULT;
1208 }
1209
1210 static int set_bfq_weight(Unit *u, dev_t dev, uint64_t io_weight) {
1211 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+STRLEN("\n")];
1212 uint64_t bfq_weight;
1213 int r;
1214
1215 assert(u);
1216
1217 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1218 if (!crt || !crt->cgroup_path)
1219 return -EOWNERDEAD;
1220
1221 /* FIXME: drop this function when distro kernels properly support BFQ through "io.weight"
1222 * See also: https://github.com/systemd/systemd/pull/13335 and
1223 * https://github.com/torvalds/linux/commit/65752aef0a407e1ef17ec78a7fc31ba4e0b360f9. */
1224 /* Adjust to kernel range is 1..1000, the default is 100. */
1225 bfq_weight = BFQ_WEIGHT(io_weight);
1226
1227 if (major(dev) > 0)
1228 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), bfq_weight);
1229 else
1230 xsprintf(buf, "%" PRIu64 "\n", bfq_weight);
1231
1232 r = cg_set_attribute(crt->cgroup_path, "io.bfq.weight", buf);
1233 if (r >= 0 && io_weight != bfq_weight)
1234 log_unit_debug(u, "%s=%" PRIu64 " scaled to io.bfq.weight=%" PRIu64,
1235 major(dev) > 0 ? "IODeviceWeight" : "IOWeight",
1236 io_weight, bfq_weight);
1237 return r;
1238 }
1239
1240 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
1241 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1242 dev_t dev;
1243 int r, r1, r2;
1244
1245 assert(u);
1246
1247 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1248 if (!crt || !crt->cgroup_path)
1249 return;
1250
1251 if (lookup_block_device(dev_path, &dev) < 0)
1252 return;
1253
1254 r1 = set_bfq_weight(u, dev, io_weight);
1255
1256 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), io_weight);
1257 r2 = cg_set_attribute(crt->cgroup_path, "io.weight", buf);
1258
1259 /* Look at the configured device, when both fail, prefer io.weight errno. */
1260 r = r2 == -EOPNOTSUPP ? r1 : r2;
1261
1262 if (r < 0)
1263 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r),
1264 r, "Failed to set 'io[.bfq].weight' attribute on '%s' to '%.*s': %m",
1265 empty_to_root(crt->cgroup_path), (int) strcspn(buf, NEWLINE), buf);
1266 }
1267
1268 static void cgroup_apply_io_device_latency(Unit *u, const char *dev_path, usec_t target) {
1269 char buf[DECIMAL_STR_MAX(dev_t)*2+2+7+DECIMAL_STR_MAX(uint64_t)+1];
1270 dev_t dev;
1271 int r;
1272
1273 r = lookup_block_device(dev_path, &dev);
1274 if (r < 0)
1275 return;
1276
1277 if (target != USEC_INFINITY)
1278 xsprintf(buf, DEVNUM_FORMAT_STR " target=%" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), target);
1279 else
1280 xsprintf(buf, DEVNUM_FORMAT_STR " target=max\n", DEVNUM_FORMAT_VAL(dev));
1281
1282 (void) set_attribute_and_warn(u, "io.latency", buf);
1283 }
1284
1285 static void cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
1286 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)],
1287 buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
1288 dev_t dev;
1289
1290 if (lookup_block_device(dev_path, &dev) < 0)
1291 return;
1292
1293 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
1294 if (limits[type] != cgroup_io_limit_defaults[type])
1295 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
1296 else
1297 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
1298
1299 xsprintf(buf, DEVNUM_FORMAT_STR " rbps=%s wbps=%s riops=%s wiops=%s\n", DEVNUM_FORMAT_VAL(dev),
1300 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
1301 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
1302 (void) set_attribute_and_warn(u, "io.max", buf);
1303 }
1304
1305 static bool cgroup_context_has_memory_config(CGroupContext *c) {
1306 assert(c);
1307
1308 return c->memory_min > 0 ||
1309 c->memory_low > 0 || c->startup_memory_low_set ||
1310 c->memory_high != CGROUP_LIMIT_MAX || c->startup_memory_high_set ||
1311 c->memory_max != CGROUP_LIMIT_MAX || c->startup_memory_max_set ||
1312 c->memory_swap_max != CGROUP_LIMIT_MAX || c->startup_memory_swap_max_set ||
1313 c->memory_zswap_max != CGROUP_LIMIT_MAX || c->startup_memory_zswap_max_set;
1314 }
1315
1316 static void cgroup_apply_memory_limit(Unit *u, const char *file, uint64_t v) {
1317 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max\n";
1318
1319 if (v != CGROUP_LIMIT_MAX)
1320 xsprintf(buf, "%" PRIu64 "\n", v);
1321
1322 (void) set_attribute_and_warn(u, file, buf);
1323 }
1324
1325 static void cgroup_apply_firewall(Unit *u) {
1326 assert(u);
1327
1328 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
1329
1330 if (bpf_firewall_compile(u) < 0)
1331 return;
1332
1333 (void) bpf_firewall_load_custom(u);
1334 (void) bpf_firewall_install(u);
1335 }
1336
1337 static void unit_modify_nft_set(Unit *u, bool add) {
1338 int r;
1339
1340 assert(u);
1341
1342 if (!MANAGER_IS_SYSTEM(u->manager))
1343 return;
1344
1345 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1346 return;
1347
1348 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1349 if (!crt || crt->cgroup_id == 0)
1350 return;
1351
1352 CGroupContext *c = ASSERT_PTR(unit_get_cgroup_context(u));
1353
1354 FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets) {
1355 if (nft_set->source != NFT_SET_SOURCE_CGROUP)
1356 continue;
1357
1358 if (!u->manager->nfnl) {
1359 r = sd_nfnl_socket_open(&u->manager->nfnl);
1360 if (r < 0)
1361 return (void) log_once_errno(LOG_WARNING, r, "Failed to open NETLINK_NETFILTER socket, ignoring: %m");
1362 }
1363
1364 uint64_t element = crt->cgroup_id;
1365
1366 r = nft_set_element_modify_any(u->manager->nfnl, add, nft_set->nfproto, nft_set->table, nft_set->set, &element, sizeof(element));
1367 if (r < 0)
1368 log_warning_errno(r, "Failed to %s NFT set entry: family %s, table %s, set %s, cgroup %" PRIu64 ", ignoring: %m",
1369 add? "add" : "delete", nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set, crt->cgroup_id);
1370 else
1371 log_debug("%s NFT set entry: family %s, table %s, set %s, cgroup %" PRIu64,
1372 add? "Added" : "Deleted", nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set, crt->cgroup_id);
1373 }
1374 }
1375
1376 static void cgroup_apply_socket_bind(Unit *u) {
1377 assert(u);
1378
1379 (void) bpf_socket_bind_install(u);
1380 }
1381
1382 static void cgroup_apply_restrict_network_interfaces(Unit *u) {
1383 assert(u);
1384
1385 (void) bpf_restrict_ifaces_install(u);
1386 }
1387
1388 static void cgroup_apply_bind_network_interface(Unit *u) {
1389 assert(u);
1390
1391 (void) bpf_bind_network_interface_install(u);
1392 }
1393
1394 static int cgroup_apply_devices(Unit *u) {
1395 _cleanup_(bpf_program_freep) BPFProgram *prog = NULL;
1396 CGroupContext *c;
1397 CGroupDevicePolicy policy;
1398 int r;
1399
1400 assert_se(c = unit_get_cgroup_context(u));
1401
1402 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1403 if (!crt || !crt->cgroup_path)
1404 return -EOWNERDEAD;
1405
1406 policy = c->device_policy;
1407
1408 r = bpf_devices_cgroup_init(&prog, policy, c->device_allow);
1409 if (r < 0)
1410 return log_unit_warning_errno(u, r, "Failed to initialize device control bpf program: %m");
1411
1412 bool allow_list_static = policy == CGROUP_DEVICE_POLICY_CLOSED ||
1413 (policy == CGROUP_DEVICE_POLICY_AUTO && c->device_allow);
1414
1415 bool any = false;
1416 if (allow_list_static) {
1417 r = bpf_devices_allow_list_static(prog, crt->cgroup_path);
1418 if (r > 0)
1419 any = true;
1420 }
1421
1422 LIST_FOREACH(device_allow, a, c->device_allow) {
1423 const char *val;
1424
1425 if (a->permissions == 0)
1426 continue;
1427
1428 if (path_startswith(a->path, "/dev/"))
1429 r = bpf_devices_allow_list_device(prog, crt->cgroup_path, a->path, a->permissions);
1430 else if ((val = startswith(a->path, "block-")))
1431 r = bpf_devices_allow_list_major(prog, crt->cgroup_path, val, 'b', a->permissions);
1432 else if ((val = startswith(a->path, "char-")))
1433 r = bpf_devices_allow_list_major(prog, crt->cgroup_path, val, 'c', a->permissions);
1434 else {
1435 log_unit_debug(u, "Ignoring device '%s' while writing cgroup attribute.", a->path);
1436 continue;
1437 }
1438
1439 if (r > 0)
1440 any = true;
1441 }
1442
1443 if (prog && !any) {
1444 log_unit_warning(u, "No devices matched by device filter.");
1445
1446 /* The kernel verifier would reject a program we would build with the normal intro and outro
1447 but no allow-listing rules (outro would contain an unreachable instruction for successful
1448 return). */
1449 policy = CGROUP_DEVICE_POLICY_STRICT;
1450 }
1451
1452 r = bpf_devices_apply_policy(&prog, policy, any, crt->cgroup_path, &crt->bpf_device_control_installed);
1453 if (r < 0) {
1454 static bool warned = false;
1455
1456 log_full_errno(warned ? LOG_DEBUG : LOG_WARNING, r,
1457 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1458 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1459 "(This warning is only shown for the first loaded unit using device ACL.)", u->id);
1460
1461 warned = true;
1462 }
1463 return r;
1464 }
1465
1466 static void set_io_weight(Unit *u, uint64_t weight) {
1467 char buf[STRLEN("default \n")+DECIMAL_STR_MAX(uint64_t)];
1468
1469 assert(u);
1470
1471 (void) set_bfq_weight(u, makedev(0, 0), weight);
1472
1473 xsprintf(buf, "default %" PRIu64 "\n", weight);
1474 (void) set_attribute_and_warn(u, "io.weight", buf);
1475 }
1476
1477 static void cgroup_context_apply(
1478 Unit *u,
1479 CGroupMask apply_mask,
1480 ManagerState state) {
1481
1482 bool is_host_root, is_local_root;
1483 CGroupContext *c;
1484 int r;
1485
1486 assert(u);
1487
1488 /* Nothing to do? Exit early! */
1489 if (apply_mask == 0)
1490 return;
1491
1492 /* Some cgroup attributes are not supported on the host root cgroup, hence silently ignore them here. And other
1493 * attributes should only be managed for cgroups further down the tree. */
1494 is_local_root = unit_has_name(u, SPECIAL_ROOT_SLICE);
1495 is_host_root = unit_has_host_root_cgroup(u);
1496
1497 assert_se(c = unit_get_cgroup_context(u));
1498
1499 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1500 if (!crt || !crt->cgroup_path)
1501 return;
1502
1503 /* We generally ignore errors caused by read-only mounted cgroup trees (assuming we are running in a container
1504 * then), and missing cgroups, i.e. EROFS and ENOENT. */
1505
1506 /* These attributes don't exist on the host cgroup root. */
1507 if ((apply_mask & CGROUP_MASK_CPU) && !is_local_root) {
1508 uint64_t weight;
1509
1510 if (cgroup_context_has_cpu_weight(c))
1511 weight = cgroup_context_cpu_weight(c, state);
1512 else
1513 weight = CGROUP_WEIGHT_DEFAULT;
1514
1515 cgroup_apply_cpu_idle(u, weight);
1516 cgroup_apply_cpu_weight(u, weight);
1517 cgroup_apply_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
1518 }
1519
1520 if ((apply_mask & CGROUP_MASK_CPUSET) && !is_local_root) {
1521 cgroup_apply_cpuset(u, "cpuset.cpus", cgroup_context_allowed_cpus(c, state));
1522 cgroup_apply_cpuset(u, "cpuset.mems", cgroup_context_allowed_mems(c, state));
1523
1524 if (c->cpuset_partition >= 0)
1525 cgroup_apply_cpuset_partition(u, "cpuset.cpus.partition", cpuset_partition_to_string(c->cpuset_partition));
1526 }
1527
1528 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroup v2
1529 * controller), and in case of containers we want to leave control of these attributes to the container manager
1530 * (and we couldn't access that stuff anyway, even if we tried if proper delegation is used). */
1531 if ((apply_mask & CGROUP_MASK_IO) && !is_local_root) {
1532 bool has_io;
1533 uint64_t weight;
1534
1535 has_io = cgroup_context_has_io_config(c);
1536
1537 if (has_io)
1538 weight = cgroup_context_io_weight(c, state);
1539 else
1540 weight = CGROUP_WEIGHT_DEFAULT;
1541
1542 set_io_weight(u, weight);
1543
1544 if (has_io) {
1545 LIST_FOREACH(device_weights, w, c->io_device_weights)
1546 cgroup_apply_io_device_weight(u, w->path, w->weight);
1547
1548 LIST_FOREACH(device_limits, limit, c->io_device_limits)
1549 cgroup_apply_io_device_limit(u, limit->path, limit->limits);
1550
1551 LIST_FOREACH(device_latencies, latency, c->io_device_latencies)
1552 cgroup_apply_io_device_latency(u, latency->path, latency->target_usec);
1553 }
1554 }
1555
1556 /* 'memory' attributes do not exist on the root cgroup. */
1557 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_local_root) {
1558 uint64_t low = CGROUP_LIMIT_MIN, max = CGROUP_LIMIT_MAX, swap_max = CGROUP_LIMIT_MAX, zswap_max = CGROUP_LIMIT_MAX, high = CGROUP_LIMIT_MAX;
1559
1560 if (cgroup_context_has_memory_config(c)) {
1561 bool startup = IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING);
1562
1563 low = startup && c->startup_memory_low_set ? c->startup_memory_low : c->memory_low;
1564 high = startup && c->startup_memory_high_set ? c->startup_memory_high : c->memory_high;
1565 max = startup && c->startup_memory_max_set ? c->startup_memory_max : c->memory_max;
1566 swap_max = startup && c->startup_memory_swap_max_set ? c->startup_memory_swap_max : c->memory_swap_max;
1567 zswap_max = startup && c->startup_memory_zswap_max_set ? c->startup_memory_zswap_max : c->memory_zswap_max;
1568 }
1569
1570 cgroup_apply_memory_limit(u, "memory.min", c->memory_min);
1571 cgroup_apply_memory_limit(u, "memory.low", low);
1572 cgroup_apply_memory_limit(u, "memory.high", high);
1573 cgroup_apply_memory_limit(u, "memory.max", max);
1574 cgroup_apply_memory_limit(u, "memory.swap.max", swap_max);
1575 cgroup_apply_memory_limit(u, "memory.zswap.max", zswap_max);
1576
1577 (void) set_attribute_and_warn(u, "memory.oom.group", one_zero(c->memory_oom_group));
1578 (void) set_attribute_and_warn(u, "memory.zswap.writeback", one_zero(c->memory_zswap_writeback));
1579 }
1580
1581 if (apply_mask & CGROUP_MASK_PIDS) {
1582
1583 if (is_host_root) {
1584 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1585 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1586 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1587 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1588 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1589 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1590 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1591 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1592 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1593 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1594 * which is desirable so that there's an official way to release control of the sysctl from
1595 * systemd: set the limit to unbounded and reload. */
1596
1597 if (cgroup_tasks_max_isset(&c->tasks_max)) {
1598 u->manager->sysctl_pid_max_changed = true;
1599 r = procfs_tasks_set_limit(cgroup_tasks_max_resolve(&c->tasks_max));
1600 } else if (u->manager->sysctl_pid_max_changed)
1601 r = procfs_tasks_set_limit(TASKS_MAX);
1602 else
1603 r = 0;
1604 if (r < 0)
1605 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r,
1606 "Failed to write to tasks limit sysctls: %m");
1607 }
1608
1609 /* The attribute itself is not available on the host root cgroup, and in the container case we want to
1610 * leave it for the container manager. */
1611 if (!is_local_root) {
1612 if (cgroup_tasks_max_isset(&c->tasks_max)) {
1613 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
1614
1615 xsprintf(buf, "%" PRIu64 "\n", cgroup_tasks_max_resolve(&c->tasks_max));
1616 (void) set_attribute_and_warn(u, "pids.max", buf);
1617 } else
1618 (void) set_attribute_and_warn(u, "pids.max", "max\n");
1619 }
1620 }
1621
1622 /* On cgroup v2 we can apply BPF everywhere. */
1623 if (apply_mask & CGROUP_MASK_BPF_DEVICES)
1624 (void) cgroup_apply_devices(u);
1625
1626 if (apply_mask & CGROUP_MASK_BPF_FIREWALL)
1627 cgroup_apply_firewall(u);
1628
1629 if (apply_mask & CGROUP_MASK_BPF_FOREIGN)
1630 (void) bpf_foreign_install(u);
1631
1632 if (apply_mask & CGROUP_MASK_BPF_SOCKET_BIND)
1633 cgroup_apply_socket_bind(u);
1634
1635 if (apply_mask & CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES)
1636 cgroup_apply_restrict_network_interfaces(u);
1637
1638 if (apply_mask & CGROUP_MASK_BPF_BIND_NETWORK_INTERFACE)
1639 cgroup_apply_bind_network_interface(u);
1640
1641 unit_modify_nft_set(u, /* add= */ true);
1642 }
1643
1644 static bool unit_get_needs_bpf_firewall(Unit *u) {
1645 CGroupContext *c;
1646 assert(u);
1647
1648 c = unit_get_cgroup_context(u);
1649 if (!c)
1650 return false;
1651
1652 if (c->ip_accounting ||
1653 !set_isempty(c->ip_address_allow) ||
1654 !set_isempty(c->ip_address_deny) ||
1655 c->ip_filters_ingress ||
1656 c->ip_filters_egress)
1657 return true;
1658
1659 /* If any parent slice has an IP access list defined, it applies too */
1660 for (Unit *p = UNIT_GET_SLICE(u); p; p = UNIT_GET_SLICE(p)) {
1661 c = unit_get_cgroup_context(p);
1662 if (!c)
1663 return false;
1664
1665 if (!set_isempty(c->ip_address_allow) ||
1666 !set_isempty(c->ip_address_deny))
1667 return true;
1668 }
1669
1670 return false;
1671 }
1672
1673 static bool unit_get_needs_bpf_foreign_program(Unit *u) {
1674 CGroupContext *c;
1675 assert(u);
1676
1677 c = unit_get_cgroup_context(u);
1678 if (!c)
1679 return false;
1680
1681 return !!c->bpf_foreign_programs;
1682 }
1683
1684 static bool unit_get_needs_socket_bind(Unit *u) {
1685 CGroupContext *c;
1686 assert(u);
1687
1688 c = unit_get_cgroup_context(u);
1689 if (!c)
1690 return false;
1691
1692 return c->socket_bind_allow || c->socket_bind_deny;
1693 }
1694
1695 static bool unit_get_needs_restrict_network_interfaces(Unit *u) {
1696 CGroupContext *c;
1697 assert(u);
1698
1699 c = unit_get_cgroup_context(u);
1700 if (!c)
1701 return false;
1702
1703 return !set_isempty(c->restrict_network_interfaces);
1704 }
1705
1706 static bool unit_get_needs_bind_network_interface(Unit *u) {
1707 CGroupContext *c;
1708 assert(u);
1709
1710 c = unit_get_cgroup_context(u);
1711 if (!c)
1712 return false;
1713
1714 return c->bind_network_interface;
1715 }
1716
1717 static CGroupMask unit_get_cgroup_mask(Unit *u) {
1718 CGroupMask mask = 0;
1719 CGroupContext *c;
1720
1721 assert(u);
1722
1723 assert_se(c = unit_get_cgroup_context(u));
1724
1725 /* Figure out which controllers we need, based on the cgroup context object */
1726
1727 if (cgroup_context_has_cpu_weight(c) ||
1728 c->cpu_quota_per_sec_usec != USEC_INFINITY)
1729 mask |= CGROUP_MASK_CPU;
1730
1731 if (cgroup_context_has_allowed_cpus(c) || cgroup_context_has_allowed_mems(c))
1732 mask |= CGROUP_MASK_CPUSET;
1733
1734 if (c->io_accounting ||
1735 cgroup_context_has_io_config(c))
1736 mask |= CGROUP_MASK_IO;
1737
1738 if (c->memory_accounting ||
1739 cgroup_context_has_memory_config(c))
1740 mask |= CGROUP_MASK_MEMORY;
1741
1742 if (cgroup_context_has_device_policy(c))
1743 mask |= CGROUP_MASK_BPF_DEVICES;
1744
1745 if (c->tasks_accounting ||
1746 cgroup_tasks_max_isset(&c->tasks_max))
1747 mask |= CGROUP_MASK_PIDS;
1748
1749 return mask;
1750 }
1751
1752 static CGroupMask unit_get_bpf_mask(Unit *u) {
1753 CGroupMask mask = 0;
1754
1755 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
1756 * too. */
1757
1758 if (unit_get_needs_bpf_firewall(u))
1759 mask |= CGROUP_MASK_BPF_FIREWALL;
1760
1761 if (unit_get_needs_bpf_foreign_program(u))
1762 mask |= CGROUP_MASK_BPF_FOREIGN;
1763
1764 if (unit_get_needs_socket_bind(u))
1765 mask |= CGROUP_MASK_BPF_SOCKET_BIND;
1766
1767 if (unit_get_needs_restrict_network_interfaces(u))
1768 mask |= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES;
1769
1770 if (unit_get_needs_bind_network_interface(u))
1771 mask |= CGROUP_MASK_BPF_BIND_NETWORK_INTERFACE;
1772
1773 return mask;
1774 }
1775
1776 CGroupMask unit_get_own_mask(Unit *u) {
1777 CGroupContext *c;
1778
1779 /* Returns the mask of controllers the unit needs for itself. If a unit is not properly loaded, return an empty
1780 * mask, as we shouldn't reflect it in the cgroup hierarchy then. */
1781
1782 if (u->load_state != UNIT_LOADED)
1783 return 0;
1784
1785 c = unit_get_cgroup_context(u);
1786 if (!c)
1787 return 0;
1788
1789 return unit_get_cgroup_mask(u) | unit_get_bpf_mask(u) | unit_get_delegate_mask(u);
1790 }
1791
1792 CGroupMask unit_get_delegate_mask(Unit *u) {
1793 CGroupContext *c;
1794
1795 /* If delegation is turned on, then turn on selected controllers.
1796 *
1797 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1798
1799 if (!unit_cgroup_delegate(u))
1800 return 0;
1801
1802 assert_se(c = unit_get_cgroup_context(u));
1803 return c->delegate_controllers;
1804 }
1805
1806 static CGroupMask unit_get_subtree_mask(Unit *u) {
1807
1808 /* Returns the mask of this subtree, meaning of the group
1809 * itself and its children. */
1810
1811 return unit_get_own_mask(u) | unit_get_members_mask(u);
1812 }
1813
1814 CGroupMask unit_get_members_mask(Unit *u) {
1815 assert(u);
1816
1817 /* Returns the mask of controllers all of the unit's children require, merged */
1818
1819 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1820 if (crt && crt->cgroup_members_mask_valid)
1821 return crt->cgroup_members_mask; /* Use cached value if possible */
1822
1823 CGroupMask m = 0;
1824 if (u->type == UNIT_SLICE) {
1825 Unit *member;
1826
1827 UNIT_FOREACH_DEPENDENCY(member, u, UNIT_ATOM_SLICE_OF)
1828 m |= unit_get_subtree_mask(member); /* note that this calls ourselves again, for the children */
1829 }
1830
1831 if (crt) {
1832 crt->cgroup_members_mask = m;
1833 crt->cgroup_members_mask_valid = true;
1834 }
1835
1836 return m;
1837 }
1838
1839 CGroupMask unit_get_siblings_mask(Unit *u) {
1840 Unit *slice;
1841 assert(u);
1842
1843 /* Returns the mask of controllers all of the unit's siblings
1844 * require, i.e. the members mask of the unit's parent slice
1845 * if there is one. */
1846
1847 slice = UNIT_GET_SLICE(u);
1848 if (slice)
1849 return unit_get_members_mask(slice);
1850
1851 return unit_get_subtree_mask(u); /* we are the top-level slice */
1852 }
1853
1854 static CGroupMask unit_get_disable_mask(Unit *u) {
1855 CGroupContext *c;
1856
1857 c = unit_get_cgroup_context(u);
1858 if (!c)
1859 return 0;
1860
1861 return c->disable_controllers;
1862 }
1863
1864 static CGroupMask unit_get_ancestor_disable_mask(Unit *u) {
1865 CGroupMask mask;
1866 Unit *slice;
1867
1868 assert(u);
1869 mask = unit_get_disable_mask(u);
1870
1871 /* Returns the mask of controllers which are marked as forcibly
1872 * disabled in any ancestor unit or the unit in question. */
1873
1874 slice = UNIT_GET_SLICE(u);
1875 if (slice)
1876 mask |= unit_get_ancestor_disable_mask(slice);
1877
1878 return mask;
1879 }
1880
1881 CGroupMask unit_get_target_mask(Unit *u) {
1882 CGroupMask own_mask, mask;
1883
1884 /* This returns the cgroup mask of all controllers to enable for a specific cgroup, i.e. everything
1885 * it needs itself, plus all that its children need, plus all that its siblings need. This is
1886 * primarily useful on the legacy cgroup hierarchy, where we need to duplicate each cgroup in each
1887 * hierarchy that shall be enabled for it. */
1888
1889 own_mask = unit_get_own_mask(u);
1890
1891 if (own_mask & CGROUP_MASK_BPF_FIREWALL & ~u->manager->cgroup_supported)
1892 emit_bpf_firewall_warning(u);
1893
1894 mask = own_mask | unit_get_members_mask(u) | unit_get_siblings_mask(u);
1895
1896 mask &= u->manager->cgroup_supported;
1897 mask &= ~unit_get_ancestor_disable_mask(u);
1898
1899 return mask;
1900 }
1901
1902 CGroupMask unit_get_enable_mask(Unit *u) {
1903 CGroupMask mask;
1904
1905 /* This returns the cgroup mask of all controllers to enable
1906 * for the children of a specific cgroup. This is primarily
1907 * useful for the unified cgroup hierarchy, where each cgroup
1908 * controls which controllers are enabled for its children. */
1909
1910 mask = unit_get_members_mask(u);
1911 mask &= u->manager->cgroup_supported;
1912 mask &= ~unit_get_ancestor_disable_mask(u);
1913
1914 return mask;
1915 }
1916
1917 void unit_invalidate_cgroup_members_masks(Unit *u) {
1918 Unit *slice;
1919
1920 assert(u);
1921
1922 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
1923 if (!crt)
1924 return;
1925
1926 /* Recurse invalidate the member masks cache all the way up the tree */
1927 crt->cgroup_members_mask_valid = false;
1928
1929 slice = UNIT_GET_SLICE(u);
1930 if (slice)
1931 unit_invalidate_cgroup_members_masks(slice);
1932 }
1933
1934 static int unit_default_cgroup_path(const Unit *u, char **ret) {
1935 _cleanup_free_ char *p = NULL;
1936 int r;
1937
1938 assert(u);
1939 assert(ret);
1940
1941 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1942 p = strdup(u->manager->cgroup_root);
1943 else {
1944 _cleanup_free_ char *escaped = NULL, *slice_path = NULL;
1945 Unit *slice;
1946
1947 slice = UNIT_GET_SLICE(u);
1948 if (slice && !unit_has_name(slice, SPECIAL_ROOT_SLICE)) {
1949 r = cg_slice_to_path(slice->id, &slice_path);
1950 if (r < 0)
1951 return r;
1952 }
1953
1954 r = cg_escape(u->id, &escaped);
1955 if (r < 0)
1956 return r;
1957
1958 p = path_join(empty_to_root(u->manager->cgroup_root), slice_path, escaped);
1959 }
1960 if (!p)
1961 return -ENOMEM;
1962
1963 *ret = TAKE_PTR(p);
1964 return 0;
1965 }
1966
1967 static int unit_set_cgroup_path(Unit *u, const char *path) {
1968 _cleanup_free_ char *p = NULL;
1969 CGroupRuntime *crt;
1970 int r;
1971
1972 assert(u);
1973
1974 crt = unit_get_cgroup_runtime(u);
1975 if (crt && streq_ptr(crt->cgroup_path, path))
1976 return 0;
1977
1978 unit_release_cgroup(u, /* drop_cgroup_runtime= */ true);
1979
1980 crt = unit_setup_cgroup_runtime(u);
1981 if (!crt)
1982 return -ENOMEM;
1983
1984 if (path) {
1985 p = strdup(path);
1986 if (!p)
1987 return -ENOMEM;
1988
1989 r = hashmap_put(u->manager->cgroup_unit, p, u);
1990 if (r < 0)
1991 return r;
1992 }
1993
1994 assert(!crt->cgroup_path);
1995 crt->cgroup_path = TAKE_PTR(p);
1996
1997 return 1;
1998 }
1999
2000 int unit_get_cgroup_path_with_fallback(const Unit *u, char **ret) {
2001 assert(u);
2002 assert(ret);
2003
2004 const CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2005 if (!crt || !crt->cgroup_path)
2006 return unit_default_cgroup_path(u, ret);
2007
2008 return strdup_to_full(ret, crt->cgroup_path); /* returns 1 -> cgroup_path is alive */
2009 }
2010
2011 static int unit_watch_cgroup(Unit *u) {
2012 _cleanup_free_ char *events = NULL;
2013 int r;
2014
2015 assert(u);
2016
2017 /* Watches the "cgroups.events" attribute of this unit's cgroup for "empty" events. */
2018
2019 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2020 if (!crt || !crt->cgroup_path)
2021 return 0;
2022
2023 if (crt->cgroup_control_inotify_wd >= 0)
2024 return 0;
2025
2026 /* No point in watch the top-level slice, it's never going to run empty. */
2027 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
2028 return 0;
2029
2030 r = hashmap_ensure_allocated(&u->manager->cgroup_control_inotify_wd_unit, &trivial_hash_ops);
2031 if (r < 0)
2032 return log_oom();
2033
2034 r = cg_get_path(crt->cgroup_path, "cgroup.events", &events);
2035 if (r < 0)
2036 return log_oom();
2037
2038 crt->cgroup_control_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
2039 if (crt->cgroup_control_inotify_wd < 0) {
2040
2041 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
2042 * is not an error */
2043 return 0;
2044
2045 return log_unit_error_errno(u, errno, "Failed to add control inotify watch descriptor for control group %s: %m", empty_to_root(crt->cgroup_path));
2046 }
2047
2048 r = hashmap_put(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(crt->cgroup_control_inotify_wd), u);
2049 if (r < 0)
2050 return log_unit_error_errno(u, r, "Failed to add control inotify watch descriptor for control group %s to hash map: %m", empty_to_root(crt->cgroup_path));
2051
2052 return 0;
2053 }
2054
2055 static int unit_watch_cgroup_memory(Unit *u) {
2056 _cleanup_free_ char *events = NULL;
2057 int r;
2058
2059 assert(u);
2060
2061 /* Watches the "memory.events" attribute of this unit's cgroup for "oom_kill" events. */
2062
2063 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2064 if (!crt || !crt->cgroup_path)
2065 return 0;
2066
2067 CGroupContext *c = unit_get_cgroup_context(u);
2068 if (!c)
2069 return 0;
2070
2071 /* The "memory.events" attribute is only available if the memory controller is on. Let's hence tie
2072 * this to memory accounting, in a way watching for OOM kills is a form of memory accounting after
2073 * all. */
2074 if (!c->memory_accounting)
2075 return 0;
2076
2077 /* Don't watch inner nodes, as the kernel doesn't report oom_kill events recursively currently, and
2078 * we also don't want to generate a log message for each parent cgroup of a process. */
2079 if (u->type == UNIT_SLICE)
2080 return 0;
2081
2082 if (crt->cgroup_memory_inotify_wd >= 0)
2083 return 0;
2084
2085 r = hashmap_ensure_allocated(&u->manager->cgroup_memory_inotify_wd_unit, &trivial_hash_ops);
2086 if (r < 0)
2087 return log_oom();
2088
2089 r = cg_get_path(crt->cgroup_path, "memory.events", &events);
2090 if (r < 0)
2091 return log_oom();
2092
2093 crt->cgroup_memory_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
2094 if (crt->cgroup_memory_inotify_wd < 0) {
2095
2096 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
2097 * is not an error */
2098 return 0;
2099
2100 return log_unit_error_errno(u, errno, "Failed to add memory inotify watch descriptor for control group %s: %m", empty_to_root(crt->cgroup_path));
2101 }
2102
2103 r = hashmap_put(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(crt->cgroup_memory_inotify_wd), u);
2104 if (r < 0)
2105 return log_unit_error_errno(u, r, "Failed to add memory inotify watch descriptor for control group %s to hash map: %m", empty_to_root(crt->cgroup_path));
2106
2107 return 0;
2108 }
2109
2110 static int unit_update_cgroup(
2111 Unit *u,
2112 CGroupMask target_mask,
2113 CGroupMask enable_mask,
2114 ManagerState state) {
2115
2116 _cleanup_free_ char *cgroup = NULL, *cgroup_full_path = NULL;
2117 bool set_path, created;
2118 int r;
2119
2120 assert(u);
2121
2122 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2123 return 0;
2124
2125 r = unit_get_cgroup_path_with_fallback(u, &cgroup);
2126 if (r < 0)
2127 return log_unit_error_errno(u, r, "Failed to get cgroup path: %m");
2128 set_path = r == 0;
2129
2130 /* First, create our own group */
2131 r = cg_create(cgroup);
2132 if (r < 0)
2133 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", empty_to_root(cgroup));
2134 created = r;
2135
2136 if (set_path) {
2137 r = unit_set_cgroup_path(u, cgroup);
2138 if (r == -EEXIST)
2139 return log_unit_error_errno(u, r, "Picked control group '%s' as default, but it's in use already.", empty_to_root(cgroup));
2140 if (r < 0)
2141 return log_unit_error_errno(u, r, "Failed to set unit's control group path to '%s': %m", empty_to_root(cgroup));
2142 assert(r > 0);
2143 }
2144
2145 CGroupRuntime *crt = ASSERT_PTR(unit_get_cgroup_runtime(u));
2146
2147 uint64_t cgroup_id = 0;
2148 r = cg_get_path(crt->cgroup_path, /* suffix= */ NULL, &cgroup_full_path);
2149 if (r < 0)
2150 log_unit_warning_errno(u, r, "Failed to get full cgroup path on cgroup %s, ignoring: %m", empty_to_root(crt->cgroup_path));
2151 else {
2152 r = path_to_handle_u64(cgroup_full_path, &cgroup_id);
2153 if (r < 0)
2154 log_unit_full_errno(u, ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
2155 "Failed to get cgroup ID of cgroup %s, ignoring: %m", cgroup_full_path);
2156 }
2157
2158 crt->cgroup_id = cgroup_id;
2159
2160 /* Start watching it */
2161 (void) unit_watch_cgroup(u);
2162 (void) unit_watch_cgroup_memory(u);
2163
2164 /* For v2 we preserve enabled controllers in delegated units, adjust others, */
2165 if (created || !unit_cgroup_delegate(u)) {
2166 CGroupMask result_mask = 0;
2167
2168 /* Enable all controllers we need */
2169 r = cg_enable(u->manager->cgroup_supported, enable_mask, crt->cgroup_path, &result_mask);
2170 if (r < 0)
2171 log_unit_warning_errno(u, r, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", empty_to_root(crt->cgroup_path));
2172
2173 /* Remember what's actually enabled now */
2174 crt->cgroup_enabled_mask = result_mask;
2175 }
2176
2177 /* Keep track that this is now realized */
2178 crt->cgroup_realized_mask = target_mask;
2179
2180 /* Set attributes */
2181 cgroup_context_apply(u, target_mask, state);
2182 cgroup_xattr_apply(u);
2183
2184 /* For most units we expect that pressure monitoring is set up before the unit is started and we
2185 * won't touch it after. For PID 1 this is different though, because we couldn't possibly do that
2186 * given that PID 1 runs before init.scope is even set up. Hence, whenever init.scope is realized,
2187 * let's try to open the pressure interfaces anew. */
2188 if (unit_has_name(u, SPECIAL_INIT_SCOPE))
2189 for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++)
2190 (void) manager_setup_pressure_event_source(u->manager, t);
2191
2192 return 0;
2193 }
2194
2195 static int unit_attach_pid_to_cgroup_via_bus(Unit *u, const char *cgroup_path, pid_t pid) {
2196 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2197 int r;
2198
2199 assert(u);
2200 assert(cgroup_path);
2201 assert(pid_is_valid(pid));
2202
2203 if (MANAGER_IS_SYSTEM(u->manager))
2204 return -EINVAL;
2205
2206 if (!u->manager->system_bus)
2207 return -EIO;
2208
2209 /* Determine this unit's cgroup path relative to our cgroup root */
2210 const char *pp = path_startswith_full(cgroup_path,
2211 u->manager->cgroup_root,
2212 PATH_STARTSWITH_RETURN_LEADING_SLASH|PATH_STARTSWITH_REFUSE_DOT_DOT);
2213 if (!pp)
2214 return -EINVAL;
2215
2216 r = bus_call_method(u->manager->system_bus,
2217 bus_systemd_mgr,
2218 "AttachProcessesToUnit",
2219 &error, NULL,
2220 "ssau",
2221 NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
2222 if (r < 0)
2223 return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
2224
2225 return 0;
2226 }
2227
2228 int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
2229 _cleanup_free_ char *joined = NULL;
2230 const char *p;
2231 int ret = 0, r;
2232
2233 assert(u);
2234
2235 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2236 return -EINVAL;
2237
2238 if (set_isempty(pids))
2239 return 0;
2240
2241 r = unit_realize_cgroup(u);
2242 if (r < 0)
2243 return r;
2244
2245 CGroupRuntime *crt = ASSERT_PTR(unit_get_cgroup_runtime(u));
2246
2247 if (isempty(suffix_path))
2248 p = empty_to_root(crt->cgroup_path);
2249 else {
2250 assert(path_is_absolute(suffix_path));
2251
2252 joined = path_join(crt->cgroup_path, suffix_path);
2253 if (!joined)
2254 return -ENOMEM;
2255
2256 p = joined;
2257 }
2258
2259 PidRef *pid;
2260 SET_FOREACH(pid, pids) {
2261
2262 /* Unfortunately we cannot add pids by pidfd to a cgroup. Hence we have to use PIDs instead,
2263 * which of course is racy. Let's shorten the race a bit though, and re-validate the PID
2264 * before we use it */
2265 r = pidref_verify(pid);
2266 if (r < 0) {
2267 log_unit_info_errno(u, r, "PID " PID_FMT " vanished before we could move it to target cgroup '%s', skipping: %m", pid->pid, p);
2268 continue;
2269 }
2270
2271 r = cg_attach(p, pid->pid);
2272 if (r < 0) {
2273 bool again = MANAGER_IS_USER(u->manager) && ERRNO_IS_NEG_PRIVILEGE(r);
2274
2275 log_unit_full_errno(u, again ? LOG_DEBUG : LOG_INFO, r,
2276 "Couldn't move process "PID_FMT" to%s requested cgroup '%s': %m",
2277 pid->pid, again ? " directly" : "", p);
2278
2279 if (again) {
2280 int z;
2281
2282 /* If we are in a user instance, and we can't move the process ourselves due
2283 * to permission problems, let's ask the system instance about it instead.
2284 * Since it's more privileged it might be able to move the process across the
2285 * leaves of a subtree whose top node is not owned by us. */
2286
2287 z = unit_attach_pid_to_cgroup_via_bus(u, p, pid->pid);
2288 if (z >= 0)
2289 goto success;
2290
2291 log_unit_info_errno(u, z, "Couldn't move process "PID_FMT" to requested cgroup '%s' (directly or via the system bus): %m", pid->pid, p);
2292 }
2293
2294 RET_GATHER(ret, r);
2295 continue;
2296 }
2297
2298 success:
2299 /* the cgroup is definitely not empty now. in case the unit was in the cgroup empty queue,
2300 * drop it from there */
2301 unit_remove_from_cgroup_empty_queue(u);
2302
2303 if (ret >= 0)
2304 ret++; /* Count successful additions */
2305 }
2306
2307 return ret;
2308 }
2309
2310 int unit_remove_subcgroup(Unit *u, const char *suffix_path) {
2311 int r;
2312
2313 assert(u);
2314
2315 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2316 return -EINVAL;
2317
2318 if (!unit_cgroup_delegate(u))
2319 return -ENOMEDIUM;
2320
2321 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2322 if (!crt || !crt->cgroup_path)
2323 return -EOWNERDEAD;
2324
2325 _cleanup_free_ char *j = NULL;
2326 bool delete_root;
2327 const char *d;
2328 if (empty_or_root(suffix_path)) {
2329 d = empty_to_root(crt->cgroup_path);
2330 delete_root = false; /* Don't attempt to delete the main cgroup of this unit */
2331 } else {
2332 j = path_join(crt->cgroup_path, suffix_path);
2333 if (!j)
2334 return -ENOMEM;
2335
2336 d = j;
2337 delete_root = true;
2338 }
2339
2340 log_unit_debug(u, "Removing subcgroup '%s'...", d);
2341
2342 r = cg_trim(d, delete_root);
2343 if (r < 0)
2344 return log_unit_debug_errno(u, r, "Failed to fully %s cgroup '%s': %m", delete_root ? "remove" : "trim", d);
2345
2346 return 0;
2347 }
2348
2349 static bool unit_has_mask_realized(
2350 Unit *u,
2351 CGroupMask target_mask,
2352 CGroupMask enable_mask) {
2353
2354 assert(u);
2355
2356 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2357 if (!crt)
2358 return false;
2359
2360 /* Returns true if this unit is fully realized. We check four things:
2361 *
2362 * 1. Whether the cgroup was created at all
2363 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
2364 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
2365 * 4. Whether the invalidation mask is currently zero
2366 *
2367 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
2368 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
2369 * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
2370 * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
2371 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
2372 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
2373 * simply don't matter. */
2374
2375 return crt->cgroup_path &&
2376 ((crt->cgroup_realized_mask ^ target_mask) & CGROUP_MASK_V1) == 0 &&
2377 ((crt->cgroup_enabled_mask ^ enable_mask) & CGROUP_MASK_V2) == 0 &&
2378 crt->cgroup_invalidated_mask == 0;
2379 }
2380
2381 static bool unit_has_mask_disables_realized(
2382 Unit *u,
2383 CGroupMask target_mask,
2384 CGroupMask enable_mask) {
2385
2386 assert(u);
2387
2388 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2389 if (!crt)
2390 return true;
2391
2392 /* Returns true if all controllers which should be disabled are indeed disabled.
2393 *
2394 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
2395 * already removed. */
2396
2397 return !crt->cgroup_path ||
2398 (FLAGS_SET(crt->cgroup_realized_mask, target_mask & CGROUP_MASK_V1) &&
2399 FLAGS_SET(crt->cgroup_enabled_mask, enable_mask & CGROUP_MASK_V2));
2400 }
2401
2402 static bool unit_has_mask_enables_realized(
2403 Unit *u,
2404 CGroupMask target_mask,
2405 CGroupMask enable_mask) {
2406
2407 assert(u);
2408
2409 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2410 if (!crt)
2411 return false;
2412
2413 /* Returns true if all controllers which should be enabled are indeed enabled.
2414 *
2415 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
2416 * we want to add is already added. */
2417
2418 return crt->cgroup_path &&
2419 ((crt->cgroup_realized_mask | target_mask) & CGROUP_MASK_V1) == (crt->cgroup_realized_mask & CGROUP_MASK_V1) &&
2420 ((crt->cgroup_enabled_mask | enable_mask) & CGROUP_MASK_V2) == (crt->cgroup_enabled_mask & CGROUP_MASK_V2);
2421 }
2422
2423 void unit_add_to_cgroup_realize_queue(Unit *u) {
2424 assert(u);
2425
2426 if (u->in_cgroup_realize_queue)
2427 return;
2428
2429 LIST_APPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2430 u->in_cgroup_realize_queue = true;
2431 }
2432
2433 static void unit_remove_from_cgroup_realize_queue(Unit *u) {
2434 assert(u);
2435
2436 if (!u->in_cgroup_realize_queue)
2437 return;
2438
2439 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2440 u->in_cgroup_realize_queue = false;
2441 }
2442
2443 /* Controllers can only be enabled breadth-first, from the root of the
2444 * hierarchy downwards to the unit in question. */
2445 static int unit_realize_cgroup_now_enable(Unit *u, ManagerState state) {
2446 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2447 Unit *slice;
2448 int r;
2449
2450 assert(u);
2451
2452 /* First go deal with this unit's parent, or we won't be able to enable
2453 * any new controllers at this layer. */
2454 slice = UNIT_GET_SLICE(u);
2455 if (slice) {
2456 r = unit_realize_cgroup_now_enable(slice, state);
2457 if (r < 0)
2458 return r;
2459 }
2460
2461 target_mask = unit_get_target_mask(u);
2462 enable_mask = unit_get_enable_mask(u);
2463
2464 /* We can only enable in this direction, don't try to disable anything.
2465 */
2466 if (unit_has_mask_enables_realized(u, target_mask, enable_mask))
2467 return 0;
2468
2469 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2470
2471 new_target_mask = (crt ? crt->cgroup_realized_mask : 0) | target_mask;
2472 new_enable_mask = (crt ? crt->cgroup_enabled_mask : 0) | enable_mask;
2473
2474 return unit_update_cgroup(u, new_target_mask, new_enable_mask, state);
2475 }
2476
2477 /* Controllers can only be disabled depth-first, from the leaves of the
2478 * hierarchy upwards to the unit in question. */
2479 static int unit_realize_cgroup_now_disable(Unit *u, ManagerState state) {
2480 Unit *m;
2481
2482 assert(u);
2483
2484 if (u->type != UNIT_SLICE)
2485 return 0;
2486
2487 UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
2488 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2489 int r;
2490
2491 CGroupRuntime *rt = unit_get_cgroup_runtime(m);
2492 if (!rt)
2493 continue;
2494
2495 /* The cgroup for this unit might not actually be fully realised yet, in which case it isn't
2496 * holding any controllers open anyway. */
2497 if (!rt->cgroup_path)
2498 continue;
2499
2500 /* We must disable those below us first in order to release the controller. */
2501 (void) unit_realize_cgroup_now_disable(m, state);
2502
2503 target_mask = unit_get_target_mask(m);
2504 enable_mask = unit_get_enable_mask(m);
2505
2506 /* We can only disable in this direction, don't try to enable anything. */
2507 if (unit_has_mask_disables_realized(m, target_mask, enable_mask))
2508 continue;
2509
2510 new_target_mask = rt->cgroup_realized_mask & target_mask;
2511 new_enable_mask = rt->cgroup_enabled_mask & enable_mask;
2512
2513 r = unit_update_cgroup(m, new_target_mask, new_enable_mask, state);
2514 if (r < 0)
2515 return r;
2516 }
2517
2518 return 0;
2519 }
2520
2521 /* Check if necessary controllers and attributes for a unit are in place.
2522 *
2523 * - If so, do nothing.
2524 * - If not, create paths, move processes over, and set attributes.
2525 *
2526 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
2527 * a depth-first way. As such the process looks like this:
2528 *
2529 * Suppose we have a cgroup hierarchy which looks like this:
2530 *
2531 * root
2532 * / \
2533 * / \
2534 * / \
2535 * a b
2536 * / \ / \
2537 * / \ / \
2538 * c d e f
2539 * / \ / \ / \ / \
2540 * h i j k l m n o
2541 *
2542 * 1. We want to realise cgroup "d" now.
2543 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
2544 * 3. cgroup "k" just started requesting the memory controller.
2545 *
2546 * To make this work we must do the following in order:
2547 *
2548 * 1. Disable CPU controller in k, j
2549 * 2. Disable CPU controller in d
2550 * 3. Enable memory controller in root
2551 * 4. Enable memory controller in a
2552 * 5. Enable memory controller in d
2553 * 6. Enable memory controller in k
2554 *
2555 * Notice that we need to touch j in one direction, but not the other. We also
2556 * don't go beyond d when disabling -- it's up to "a" to get realized if it
2557 * wants to disable further. The basic rules are therefore:
2558 *
2559 * - If you're disabling something, you need to realise all of the cgroups from
2560 * your recursive descendants to the root. This starts from the leaves.
2561 * - If you're enabling something, you need to realise from the root cgroup
2562 * downwards, but you don't need to iterate your recursive descendants.
2563 *
2564 * Returns 0 on success and < 0 on failure. */
2565 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
2566 CGroupMask target_mask, enable_mask;
2567 Unit *slice;
2568 int r;
2569
2570 assert(u);
2571
2572 unit_remove_from_cgroup_realize_queue(u);
2573
2574 target_mask = unit_get_target_mask(u);
2575 enable_mask = unit_get_enable_mask(u);
2576
2577 if (unit_has_mask_realized(u, target_mask, enable_mask))
2578 return 0;
2579
2580 /* Disable controllers below us, if there are any */
2581 r = unit_realize_cgroup_now_disable(u, state);
2582 if (r < 0)
2583 return r;
2584
2585 /* Enable controllers above us, if there are any */
2586 slice = UNIT_GET_SLICE(u);
2587 if (slice) {
2588 r = unit_realize_cgroup_now_enable(slice, state);
2589 if (r < 0)
2590 return r;
2591 }
2592
2593 /* Now actually deal with the cgroup we were trying to realise and set attributes */
2594 r = unit_update_cgroup(u, target_mask, enable_mask, state);
2595 if (r < 0)
2596 return r;
2597
2598 CGroupRuntime *crt = ASSERT_PTR(unit_get_cgroup_runtime(u));
2599
2600 /* Now, reset the invalidation mask */
2601 crt->cgroup_invalidated_mask = 0;
2602 return 0;
2603 }
2604
2605 unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
2606 ManagerState state;
2607 unsigned n = 0;
2608 Unit *i;
2609 int r;
2610
2611 assert(m);
2612
2613 state = manager_state(m);
2614
2615 while ((i = m->cgroup_realize_queue)) {
2616 assert(i->in_cgroup_realize_queue);
2617
2618 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
2619 /* Maybe things changed, and the unit is not actually active anymore? */
2620 unit_remove_from_cgroup_realize_queue(i);
2621 continue;
2622 }
2623
2624 r = unit_realize_cgroup_now(i, state);
2625 if (r < 0)
2626 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
2627
2628 n++;
2629 }
2630
2631 return n;
2632 }
2633
2634 void unit_add_family_to_cgroup_realize_queue(Unit *u) {
2635 assert(u);
2636 assert(u->type == UNIT_SLICE);
2637
2638 /* Family of a unit for is defined as (immediate) children of the unit and immediate children of all
2639 * its ancestors.
2640 *
2641 * Ideally we would enqueue ancestor path only (bottom up). However, on cgroup-v1 scheduling becomes
2642 * very weird if two units that own processes reside in the same slice, but one is realized in the
2643 * "cpu" hierarchy and one is not (for example because one has CPUWeight= set and the other does
2644 * not), because that means individual processes need to be scheduled against whole cgroups. Let's
2645 * avoid this asymmetry by always ensuring that siblings of a unit are always realized in their v1
2646 * controller hierarchies too (if unit requires the controller to be realized).
2647 *
2648 * The function must invalidate cgroup_members_mask of all ancestors in order to calculate up to date
2649 * masks. */
2650
2651 do {
2652 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2653
2654 /* Children of u likely changed when we're called */
2655 if (crt)
2656 crt->cgroup_members_mask_valid = false;
2657
2658 Unit *m;
2659 UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
2660
2661 /* No point in doing cgroup application for units without active processes. */
2662 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
2663 continue;
2664
2665 /* We only enqueue siblings if they were realized once at least, in the main
2666 * hierarchy. */
2667 crt = unit_get_cgroup_runtime(m);
2668 if (!crt || !crt->cgroup_path)
2669 continue;
2670
2671 /* If the unit doesn't need any new controllers and has current ones
2672 * realized, it doesn't need any changes. */
2673 if (unit_has_mask_realized(m,
2674 unit_get_target_mask(m),
2675 unit_get_enable_mask(m)))
2676 continue;
2677
2678 unit_add_to_cgroup_realize_queue(m);
2679 }
2680
2681 /* Parent comes after children */
2682 unit_add_to_cgroup_realize_queue(u);
2683
2684 u = UNIT_GET_SLICE(u);
2685 } while (u);
2686 }
2687
2688 int unit_realize_cgroup(Unit *u) {
2689 Unit *slice;
2690
2691 assert(u);
2692
2693 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2694 return 0;
2695
2696 /* So, here's the deal: when realizing the cgroups for this unit, we need to first create all
2697 * parents, but there's more actually: for the weight-based controllers we also need to make sure
2698 * that all our siblings (i.e. units that are in the same slice as we are) have cgroups, too. On the
2699 * other hand, when a controller is removed from realized set, it may become unnecessary in siblings
2700 * and ancestors and they should be (de)realized too.
2701 *
2702 * This call will defer work on the siblings and derealized ancestors to the next event loop
2703 * iteration and synchronously creates the parent cgroups (unit_realize_cgroup_now). */
2704
2705 slice = UNIT_GET_SLICE(u);
2706 if (slice)
2707 unit_add_family_to_cgroup_realize_queue(slice);
2708
2709 /* And realize this one now (and apply the values) */
2710 return unit_realize_cgroup_now(u, manager_state(u->manager));
2711 }
2712
2713 void unit_release_cgroup(Unit *u, bool drop_cgroup_runtime) {
2714 assert(u);
2715
2716 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
2717 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
2718
2719 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2720 if (!crt)
2721 return;
2722
2723 if (crt->cgroup_path) {
2724 (void) hashmap_remove(u->manager->cgroup_unit, crt->cgroup_path);
2725 crt->cgroup_path = mfree(crt->cgroup_path);
2726 }
2727
2728 if (crt->cgroup_control_inotify_wd >= 0) {
2729 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, crt->cgroup_control_inotify_wd) < 0)
2730 log_unit_debug_errno(u, errno, "Failed to remove cgroup control inotify watch %i for %s, ignoring: %m", crt->cgroup_control_inotify_wd, u->id);
2731
2732 (void) hashmap_remove(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(crt->cgroup_control_inotify_wd));
2733 crt->cgroup_control_inotify_wd = -1;
2734 }
2735
2736 if (crt->cgroup_memory_inotify_wd >= 0) {
2737 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, crt->cgroup_memory_inotify_wd) < 0)
2738 log_unit_debug_errno(u, errno, "Failed to remove cgroup memory inotify watch %i for %s, ignoring: %m", crt->cgroup_memory_inotify_wd, u->id);
2739
2740 (void) hashmap_remove(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(crt->cgroup_memory_inotify_wd));
2741 crt->cgroup_memory_inotify_wd = -1;
2742 }
2743
2744 if (drop_cgroup_runtime)
2745 *(CGroupRuntime**) ((uint8_t*) u + UNIT_VTABLE(u)->cgroup_runtime_offset) = cgroup_runtime_free(crt);
2746 }
2747
2748 int unit_cgroup_is_empty(Unit *u) {
2749 int r;
2750
2751 assert(u);
2752
2753 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2754 if (!crt)
2755 return -ENXIO;
2756 if (!crt->cgroup_path)
2757 return -EOWNERDEAD;
2758
2759 r = cg_is_empty(crt->cgroup_path);
2760 if (r < 0)
2761 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", empty_to_root(crt->cgroup_path));
2762 return r;
2763 }
2764
2765 static bool unit_maybe_release_cgroup(Unit *u) {
2766 int r;
2767
2768 /* Releases the cgroup only if it is recursively empty.
2769 * Returns true if the cgroup was released, false otherwise. */
2770
2771 assert(u);
2772
2773 /* Don't release the cgroup if there are still processes under it. If we get notified later when all
2774 * the processes exit (e.g. the processes were in D-state and exited after the unit was marked as
2775 * failed) we need the cgroup paths to continue to be tracked by the manager so they can be looked up
2776 * and cleaned up later. */
2777 r = unit_cgroup_is_empty(u);
2778 if (r > 0) {
2779 /* Do not free CGroupRuntime when called from unit_prune_cgroup. Various accounting data
2780 * we should keep, especially CPU usage and *_peak ones which would be shown even after
2781 * the unit stops. */
2782 unit_release_cgroup(u, /* drop_cgroup_runtime= */ false);
2783 return true;
2784 }
2785
2786 return false;
2787 }
2788
2789 static int unit_prune_cgroup_via_bus(Unit *u) {
2790 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2791 int r;
2792
2793 assert(u);
2794 assert(u->manager);
2795
2796 if (MANAGER_IS_SYSTEM(u->manager))
2797 return -EINVAL;
2798
2799 if (!u->manager->system_bus)
2800 return -EIO;
2801
2802 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2803 if (!crt || !crt->cgroup_path)
2804 return -EOWNERDEAD;
2805
2806 /* Determine this unit's cgroup path relative to our cgroup root */
2807 const char *pp = path_startswith_full(
2808 crt->cgroup_path,
2809 u->manager->cgroup_root,
2810 PATH_STARTSWITH_RETURN_LEADING_SLASH|PATH_STARTSWITH_REFUSE_DOT_DOT);
2811 if (!pp)
2812 return -EINVAL;
2813
2814 r = bus_call_method(u->manager->system_bus,
2815 bus_systemd_mgr,
2816 "RemoveSubgroupFromUnit",
2817 &error, NULL,
2818 "sst",
2819 NULL /* empty unit name means client's unit, i.e. us */,
2820 pp,
2821 (uint64_t) 0);
2822 if (r < 0)
2823 return log_unit_debug_errno(u, r, "Failed to trim cgroup via the bus: %s", bus_error_message(&error, r));
2824
2825 return 0;
2826 }
2827
2828 void unit_prune_cgroup(Unit *u) {
2829 bool is_root_slice;
2830 int r;
2831
2832 assert(u);
2833
2834 /* Removes the cgroup, if empty and possible, and stops watching it. */
2835 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2836 if (!crt || !crt->cgroup_path)
2837 return;
2838
2839 /* Cache the last resource usage values before we destroy the cgroup */
2840 (void) unit_get_cpu_usage(u, /* ret= */ NULL);
2841
2842 for (CGroupMemoryAccountingMetric metric = 0; metric <= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST; metric++)
2843 (void) unit_get_memory_accounting(u, metric, /* ret= */ NULL);
2844
2845 /* All IO metrics are read at once from the underlying cgroup, so issue just a single call */
2846 (void) unit_get_io_accounting(u, _CGROUP_IO_ACCOUNTING_METRIC_INVALID, /* ret= */ NULL);
2847
2848 /* We do not cache IP metrics here because the firewall objects are not freed with cgroups */
2849
2850 #if BPF_FRAMEWORK
2851 (void) bpf_restrict_fs_cleanup(u); /* Remove cgroup from the global LSM BPF map */
2852 #endif
2853
2854 unit_modify_nft_set(u, /* add= */ false);
2855
2856 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
2857
2858 r = cg_trim(crt->cgroup_path, !is_root_slice);
2859 if (r < 0) {
2860 int k = unit_prune_cgroup_via_bus(u);
2861
2862 if (k >= 0)
2863 log_unit_debug_errno(u, r, "Failed to destroy cgroup %s on our own (%m), but worked when talking to PID 1.", empty_to_root(crt->cgroup_path));
2864 else {
2865 /* One reason we could have failed here is, that the cgroup still contains a process.
2866 * However, if the cgroup becomes removable at a later time, it might be removed when
2867 * the containing slice is stopped. So even if we failed now, this unit shouldn't
2868 * assume that the cgroup is still realized the next time it is started. Do not
2869 * return early on error, continue cleanup. */
2870 log_unit_full_errno(u, r == -EBUSY ? LOG_DEBUG : LOG_WARNING, r,
2871 "Failed to destroy cgroup %s, ignoring: %m", empty_to_root(crt->cgroup_path));
2872 }
2873 }
2874
2875 if (is_root_slice)
2876 return;
2877
2878 if (!unit_maybe_release_cgroup(u)) /* Returns true if the cgroup was released */
2879 return;
2880
2881 assert(crt == unit_get_cgroup_runtime(u));
2882 assert(!crt->cgroup_path);
2883
2884 crt->cgroup_realized_mask = 0;
2885 crt->cgroup_enabled_mask = 0;
2886
2887 crt->bpf_device_control_installed = bpf_program_free(crt->bpf_device_control_installed);
2888 }
2889
2890 int unit_search_main_pid(Unit *u, PidRef *ret) {
2891 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
2892 _cleanup_fclose_ FILE *f = NULL;
2893 int r;
2894
2895 assert(u);
2896 assert(ret);
2897
2898 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
2899 if (!crt || !crt->cgroup_path)
2900 return -ENXIO;
2901
2902 r = cg_enumerate_processes(crt->cgroup_path, &f);
2903 if (r < 0)
2904 return r;
2905
2906 for (;;) {
2907 _cleanup_(pidref_done) PidRef npidref = PIDREF_NULL;
2908
2909 /* cg_read_pidref() will return an error on unmapped PIDs.
2910 * We can't reasonably deal with units that contain those. */
2911 r = cg_read_pidref(f, &npidref, CGROUP_DONT_SKIP_UNMAPPED);
2912 if (r < 0)
2913 return r;
2914 if (r == 0)
2915 break;
2916
2917 if (pidref_equal(&pidref, &npidref)) /* seen already, cgroupfs reports duplicates! */
2918 continue;
2919
2920 if (pidref_is_my_child(&npidref) <= 0) /* ignore processes further down the tree */
2921 continue;
2922
2923 if (pidref_is_set(&pidref) != 0)
2924 /* Dang, there's more than one daemonized PID in this group, so we don't know what
2925 * process is the main process. */
2926 return -ENODATA;
2927
2928 pidref = TAKE_PIDREF(npidref);
2929 }
2930
2931 if (!pidref_is_set(&pidref))
2932 return -ENODATA;
2933
2934 *ret = TAKE_PIDREF(pidref);
2935 return 0;
2936 }
2937
2938 static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
2939 Manager *m = ASSERT_PTR(userdata);
2940 Unit *u;
2941 int r;
2942
2943 assert(s);
2944
2945 u = m->cgroup_empty_queue;
2946 if (!u)
2947 return 0;
2948
2949 assert(u->in_cgroup_empty_queue);
2950 u->in_cgroup_empty_queue = false;
2951 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
2952
2953 if (m->cgroup_empty_queue) {
2954 /* More stuff queued, let's make sure we remain enabled */
2955 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
2956 if (r < 0)
2957 log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
2958 }
2959
2960 /* Update state based on OOM kills before we notify about cgroup empty event */
2961 (void) unit_check_oom(u);
2962 (void) unit_check_oomd_kill(u);
2963
2964 unit_add_to_gc_queue(u);
2965
2966 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)))
2967 unit_prune_cgroup(u);
2968 else if (UNIT_VTABLE(u)->notify_cgroup_empty)
2969 UNIT_VTABLE(u)->notify_cgroup_empty(u);
2970
2971 return 0;
2972 }
2973
2974 static void unit_add_to_cgroup_empty_queue(Unit *u) {
2975 int r;
2976
2977 assert(u);
2978
2979 /* Note that cgroup empty events are dispatched in a separate queue with a lower priority than
2980 * the SIGCHLD handler, so that we always use SIGCHLD if we can get it first, and only use
2981 * the cgroup empty notifications if there's no SIGCHLD pending (which might happen if the cgroup
2982 * doesn't contain processes that are our own child, which is typically the case for scope units). */
2983
2984 if (u->in_cgroup_empty_queue)
2985 return;
2986
2987 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
2988 u->in_cgroup_empty_queue = true;
2989
2990 /* Trigger the defer event */
2991 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
2992 if (r < 0)
2993 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
2994 }
2995
2996 static void unit_remove_from_cgroup_empty_queue(Unit *u) {
2997 assert(u);
2998
2999 if (!u->in_cgroup_empty_queue)
3000 return;
3001
3002 LIST_REMOVE(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
3003 u->in_cgroup_empty_queue = false;
3004 }
3005
3006 int unit_check_oomd_kill(Unit *u) {
3007 _cleanup_free_ char *value = NULL;
3008 bool increased;
3009 uint64_t n = 0;
3010 int r;
3011
3012 assert(u);
3013
3014 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3015 if (!crt || !crt->cgroup_path)
3016 return 0;
3017
3018 r = cg_get_xattr(crt->cgroup_path, "user.oomd_ooms", &value, /* ret_size= */ NULL);
3019 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
3020 return r;
3021
3022 if (!isempty(value)) {
3023 r = safe_atou64(value, &n);
3024 if (r < 0)
3025 return r;
3026 }
3027
3028 increased = n > crt->managed_oom_kill_last;
3029 crt->managed_oom_kill_last = n;
3030
3031 if (!increased)
3032 return 0;
3033
3034 n = 0;
3035 value = mfree(value);
3036 r = cg_get_xattr(crt->cgroup_path, "user.oomd_kill", &value, /* ret_size= */ NULL);
3037 if (r >= 0 && !isempty(value))
3038 (void) safe_atou64(value, &n);
3039
3040 if (n > 0)
3041 log_unit_struct(u, LOG_NOTICE,
3042 LOG_MESSAGE_ID(SD_MESSAGE_UNIT_OOMD_KILL_STR),
3043 LOG_UNIT_INVOCATION_ID(u),
3044 LOG_UNIT_MESSAGE(u, "systemd-oomd killed %"PRIu64" process(es) in this unit.", n),
3045 LOG_ITEM("N_PROCESSES=%" PRIu64, n));
3046 else
3047 log_unit_struct(u, LOG_NOTICE,
3048 LOG_MESSAGE_ID(SD_MESSAGE_UNIT_OOMD_KILL_STR),
3049 LOG_UNIT_INVOCATION_ID(u),
3050 LOG_UNIT_MESSAGE(u, "systemd-oomd killed some process(es) in this unit."));
3051
3052 unit_notify_cgroup_oom(u, /* managed_oom= */ true);
3053
3054 return 1;
3055 }
3056
3057 int unit_check_oom(Unit *u) {
3058 bool increased;
3059 uint64_t c = 0;
3060 int r;
3061
3062 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3063 if (!crt || !crt->cgroup_path)
3064 return 0;
3065
3066 CGroupContext *ctx = ASSERT_PTR(unit_get_cgroup_context(u));
3067
3068 /* If memory.oom.group=1, then look up the oom_group_kill field, which reports how many times the
3069 * kernel killed every process recursively in this cgroup and its descendants, similar to
3070 * systemd-oomd. Because the memory.events.local file was only introduced in kernel 5.12, we fall
3071 * back to reading oom_kill if we can't find the file or field. */
3072
3073 if (ctx->memory_oom_group) {
3074 r = cg_get_keyed_attribute_uint64(
3075 crt->cgroup_path,
3076 "memory.events.local",
3077 "oom_group_kill",
3078 &c);
3079 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
3080 return log_unit_debug_errno(u, r, "Failed to read oom_group_kill field of memory.events.local cgroup attribute, ignoring: %m");
3081 }
3082
3083 if (!ctx->memory_oom_group || r < 0) {
3084 r = cg_get_keyed_attribute_uint64(
3085 crt->cgroup_path,
3086 "memory.events",
3087 "oom_kill",
3088 &c);
3089 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
3090 return log_unit_debug_errno(u, r, "Failed to read oom_kill field of memory.events cgroup attribute: %m");
3091 }
3092
3093 increased = c > crt->oom_kill_last;
3094 crt->oom_kill_last = c;
3095
3096 if (!increased)
3097 return 0;
3098
3099 log_unit_struct(u, LOG_NOTICE,
3100 LOG_MESSAGE_ID(SD_MESSAGE_UNIT_OUT_OF_MEMORY_STR),
3101 LOG_UNIT_INVOCATION_ID(u),
3102 LOG_UNIT_MESSAGE(u, "The kernel OOM killer killed some processes in this unit."));
3103
3104 unit_notify_cgroup_oom(u, /* managed_oom= */ false);
3105
3106 return 1;
3107 }
3108
3109 static int on_cgroup_oom_event(sd_event_source *s, void *userdata) {
3110 Manager *m = ASSERT_PTR(userdata);
3111 Unit *u;
3112 int r;
3113
3114 assert(s);
3115
3116 u = m->cgroup_oom_queue;
3117 if (!u)
3118 return 0;
3119
3120 assert(u->in_cgroup_oom_queue);
3121 u->in_cgroup_oom_queue = false;
3122 LIST_REMOVE(cgroup_oom_queue, m->cgroup_oom_queue, u);
3123
3124 if (m->cgroup_oom_queue) {
3125 /* More stuff queued, let's make sure we remain enabled */
3126 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
3127 if (r < 0)
3128 log_debug_errno(r, "Failed to reenable cgroup oom event source, ignoring: %m");
3129 }
3130
3131 (void) unit_check_oom(u);
3132 unit_add_to_gc_queue(u);
3133
3134 return 0;
3135 }
3136
3137 static void unit_add_to_cgroup_oom_queue(Unit *u) {
3138 int r;
3139
3140 assert(u);
3141
3142 if (u->in_cgroup_oom_queue)
3143 return;
3144
3145 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3146 if (!crt || !crt->cgroup_path)
3147 return;
3148
3149 LIST_PREPEND(cgroup_oom_queue, u->manager->cgroup_oom_queue, u);
3150 u->in_cgroup_oom_queue = true;
3151
3152 /* Trigger the defer event */
3153 if (!u->manager->cgroup_oom_event_source) {
3154 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
3155
3156 r = sd_event_add_defer(u->manager->event, &s, on_cgroup_oom_event, u->manager);
3157 if (r < 0) {
3158 log_error_errno(r, "Failed to create cgroup oom event source: %m");
3159 return;
3160 }
3161
3162 r = sd_event_source_set_priority(s, EVENT_PRIORITY_CGROUP_OOM);
3163 if (r < 0) {
3164 log_error_errno(r, "Failed to set priority of cgroup oom event source: %m");
3165 return;
3166 }
3167
3168 (void) sd_event_source_set_description(s, "cgroup-oom");
3169 u->manager->cgroup_oom_event_source = TAKE_PTR(s);
3170 }
3171
3172 r = sd_event_source_set_enabled(u->manager->cgroup_oom_event_source, SD_EVENT_ONESHOT);
3173 if (r < 0)
3174 log_error_errno(r, "Failed to enable cgroup oom event source: %m");
3175 }
3176
3177 static int unit_check_cgroup_events(Unit *u) {
3178 char *values[2] = {};
3179 int r;
3180
3181 assert(u);
3182
3183 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3184 if (!crt || !crt->cgroup_path)
3185 return 0;
3186
3187 r = cg_get_keyed_attribute(
3188 crt->cgroup_path,
3189 "cgroup.events",
3190 STRV_MAKE("populated", "frozen"),
3191 values);
3192 if (r < 0)
3193 return r;
3194
3195 /* The cgroup.events notifications can be merged together so act as we saw the given state for the
3196 * first time. The functions we call to handle given state are idempotent, which makes them
3197 * effectively remember the previous state. */
3198 if (streq(values[0], "1"))
3199 unit_remove_from_cgroup_empty_queue(u);
3200 else
3201 unit_add_to_cgroup_empty_queue(u);
3202
3203 /* Disregard freezer state changes due to operations not initiated by us.
3204 * See: https://github.com/systemd/systemd/pull/13512/files#r416469963 and
3205 * https://github.com/systemd/systemd/pull/13512#issuecomment-573007207 */
3206 if (IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_FREEZING_BY_PARENT, FREEZER_THAWING))
3207 unit_freezer_complete(u, streq(values[1], "0") ? FREEZER_RUNNING : FREEZER_FROZEN);
3208
3209 free_many_charp(values, ELEMENTSOF(values));
3210 return 0;
3211 }
3212
3213 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
3214 Manager *m = ASSERT_PTR(userdata);
3215
3216 assert(s);
3217 assert(fd >= 0);
3218
3219 for (;;) {
3220 union inotify_event_buffer buffer;
3221 ssize_t l;
3222
3223 l = read(fd, &buffer, sizeof(buffer));
3224 if (l < 0) {
3225 if (ERRNO_IS_TRANSIENT(errno))
3226 return 0;
3227
3228 return log_error_errno(errno, "Failed to read control group inotify events: %m");
3229 }
3230
3231 FOREACH_INOTIFY_EVENT_WARN(e, buffer, l) {
3232 Unit *u;
3233
3234 if (e->wd < 0)
3235 /* Queue overflow has no watch descriptor */
3236 continue;
3237
3238 if (e->mask & IN_IGNORED)
3239 /* The watch was just removed */
3240 continue;
3241
3242 /* Note that inotify might deliver events for a watch even after it was removed,
3243 * because it was queued before the removal. Let's ignore this here safely. */
3244
3245 u = hashmap_get(m->cgroup_control_inotify_wd_unit, INT_TO_PTR(e->wd));
3246 if (u)
3247 unit_check_cgroup_events(u);
3248
3249 u = hashmap_get(m->cgroup_memory_inotify_wd_unit, INT_TO_PTR(e->wd));
3250 if (u)
3251 unit_add_to_cgroup_oom_queue(u);
3252 }
3253 }
3254 }
3255
3256 static int cg_bpf_mask_supported(CGroupMask *ret) {
3257 CGroupMask mask = 0;
3258 int r;
3259
3260 assert(ret);
3261
3262 /* BPF-based firewall, device access control, and pinned foreign prog */
3263 if (bpf_program_supported() > 0)
3264 mask |= CGROUP_MASK_BPF_FIREWALL |
3265 CGROUP_MASK_BPF_DEVICES |
3266 CGROUP_MASK_BPF_FOREIGN;
3267
3268 /* BPF-based bind{4|6} hooks */
3269 r = bpf_socket_bind_supported();
3270 if (r < 0)
3271 return r;
3272 if (r > 0)
3273 mask |= CGROUP_MASK_BPF_SOCKET_BIND;
3274
3275 /* BPF-based cgroup_skb/{egress|ingress} hooks */
3276 r = bpf_restrict_ifaces_supported();
3277 if (r < 0)
3278 return r;
3279 if (r > 0)
3280 mask |= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES;
3281
3282 /* BPF-based cgroup/sock_create hooks */
3283 r = bpf_bind_network_interface_supported();
3284 if (r < 0)
3285 return r;
3286 if (r > 0)
3287 mask |= CGROUP_MASK_BPF_BIND_NETWORK_INTERFACE;
3288
3289 *ret = mask;
3290 return 0;
3291 }
3292
3293 int manager_setup_cgroup(Manager *m) {
3294 int r;
3295
3296 assert(m);
3297
3298 /* 1. Determine hierarchy */
3299 m->cgroup_root = mfree(m->cgroup_root);
3300 r = cg_pid_get_path(0, &m->cgroup_root);
3301 if (r < 0)
3302 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
3303
3304 /* Chop off the init scope, if we are already located in it */
3305 char *e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
3306 if (e)
3307 *e = 0;
3308
3309 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
3310 * easily prepend it everywhere. */
3311 delete_trailing_chars(m->cgroup_root, "/");
3312
3313 /* 2. Pin the cgroupfs mount, so that it cannot be unmounted */
3314 safe_close(m->pin_cgroupfs_fd);
3315 m->pin_cgroupfs_fd = open("/sys/fs/cgroup", O_PATH|O_CLOEXEC|O_DIRECTORY);
3316 if (m->pin_cgroupfs_fd < 0)
3317 return log_error_errno(errno, "Failed to pin cgroup hierarchy: %m");
3318
3319 /* 3. Allocate cgroup empty defer event source */
3320 m->cgroup_empty_event_source = sd_event_source_disable_unref(m->cgroup_empty_event_source);
3321 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
3322 if (r < 0)
3323 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
3324
3325 /* Schedule cgroup empty checks early, but after having processed service notification messages or
3326 * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of
3327 * notification, and we collected the metadata the notification and SIGCHLD stuff offers first. */
3328 r = sd_event_source_set_priority(m->cgroup_empty_event_source, EVENT_PRIORITY_CGROUP_EMPTY);
3329 if (r < 0)
3330 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
3331
3332 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
3333 if (r < 0)
3334 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
3335
3336 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
3337
3338 /* 4. Install cgroup empty event notifier inotify object */
3339 m->cgroup_inotify_event_source = sd_event_source_disable_unref(m->cgroup_inotify_event_source);
3340 safe_close(m->cgroup_inotify_fd);
3341
3342 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
3343 if (m->cgroup_inotify_fd < 0)
3344 return log_error_errno(errno, "Failed to create control group inotify object: %m");
3345
3346 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
3347 if (r < 0)
3348 return log_error_errno(r, "Failed to watch control group inotify object: %m");
3349
3350 /* Process cgroup empty notifications early. Note that when this event is dispatched it'll
3351 * just add the unit to a cgroup empty queue, hence let's run earlier than that. Also see
3352 * handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
3353 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, EVENT_PRIORITY_CGROUP_INOTIFY);
3354 if (r < 0)
3355 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
3356
3357 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
3358
3359 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
3360 const char *scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
3361 r = cg_create_and_attach(scope_path, /* pid= */ 0);
3362 if (r >= 0) {
3363 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
3364 r = cg_migrate(m->cgroup_root, scope_path, 0);
3365 if (r < 0)
3366 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
3367
3368 } else if (!MANAGER_IS_TEST_RUN(m))
3369 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
3370
3371 /* 6. Figure out which controllers are supported */
3372 r = cg_mask_supported_subtree(m->cgroup_root, &m->cgroup_supported);
3373 if (r < 0)
3374 return log_error_errno(r, "Failed to determine supported controllers: %m");
3375
3376 /* 7. Figure out which bpf-based pseudo-controllers are supported */
3377 CGroupMask mask;
3378 r = cg_bpf_mask_supported(&mask);
3379 if (r < 0)
3380 return log_error_errno(r, "Failed to determine supported bpf-based pseudo-controllers: %m");
3381 m->cgroup_supported |= mask;
3382
3383 /* 8. Log which controllers are supported */
3384 for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
3385 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c),
3386 yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
3387
3388 return 0;
3389 }
3390
3391 void manager_shutdown_cgroup(Manager *m, bool delete) {
3392 assert(m);
3393
3394 /* We can't really delete the group, since we are in it. But
3395 * let's trim it. */
3396 if (delete && m->cgroup_root && !FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
3397 (void) cg_trim(m->cgroup_root, false);
3398
3399 m->cgroup_empty_event_source = sd_event_source_disable_unref(m->cgroup_empty_event_source);
3400
3401 m->cgroup_control_inotify_wd_unit = hashmap_free(m->cgroup_control_inotify_wd_unit);
3402 m->cgroup_memory_inotify_wd_unit = hashmap_free(m->cgroup_memory_inotify_wd_unit);
3403
3404 m->cgroup_inotify_event_source = sd_event_source_disable_unref(m->cgroup_inotify_event_source);
3405 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
3406
3407 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
3408
3409 m->cgroup_root = mfree(m->cgroup_root);
3410 }
3411
3412 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
3413 char *p;
3414 Unit *u;
3415
3416 assert(m);
3417 assert(cgroup);
3418
3419 u = hashmap_get(m->cgroup_unit, cgroup);
3420 if (u)
3421 return u;
3422
3423 p = strdupa_safe(cgroup);
3424 for (;;) {
3425 char *e;
3426
3427 e = strrchr(p, '/');
3428 if (!e || e == p)
3429 return NULL; /* reached cgroup root? return NULL and possibly fall back to manager_get_unit_by_pidref_watching() */
3430
3431 *e = 0;
3432
3433 u = hashmap_get(m->cgroup_unit, p);
3434 if (u)
3435 return u;
3436 }
3437 }
3438
3439 Unit* manager_get_unit_by_pidref_cgroup(Manager *m, const PidRef *pid) {
3440 _cleanup_free_ char *cgroup = NULL;
3441
3442 assert(m);
3443
3444 if (cg_pidref_get_path(pid, &cgroup) < 0)
3445 return NULL;
3446
3447 return manager_get_unit_by_cgroup(m, cgroup);
3448 }
3449
3450 Unit* manager_get_unit_by_pidref_watching(Manager *m, const PidRef *pid) {
3451 Unit *u, **array;
3452
3453 assert(m);
3454
3455 if (!pidref_is_set(pid))
3456 return NULL;
3457
3458 u = hashmap_get(m->watch_pids, pid);
3459 if (u)
3460 return u;
3461
3462 array = hashmap_get(m->watch_pids_more, pid);
3463 if (array)
3464 return array[0];
3465
3466 return NULL;
3467 }
3468
3469 Unit* manager_get_unit_by_pidref(Manager *m, PidRef *pid) {
3470 Unit *u;
3471
3472 assert(m);
3473
3474 /* Note that a process might be owned by multiple units, we return only one here, which is good
3475 * enough for most cases, though not strictly correct. We prefer the one reported by cgroup
3476 * membership, as that's the most relevant one as children of the process will be assigned to that
3477 * one, too, before all else. */
3478
3479 if (!pidref_is_set(pid))
3480 return NULL;
3481
3482 if (pidref_is_self(pid))
3483 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
3484 if (pid->pid == 1)
3485 return NULL;
3486
3487 u = manager_get_unit_by_pidref_cgroup(m, pid);
3488 if (u)
3489 return u;
3490
3491 u = manager_get_unit_by_pidref_watching(m, pid);
3492 if (u)
3493 return u;
3494
3495 return NULL;
3496 }
3497
3498 int unit_get_memory_available(Unit *u, uint64_t *ret) {
3499 uint64_t available = UINT64_MAX, current = 0;
3500
3501 assert(u);
3502 assert(ret);
3503
3504 /* If data from cgroups can be accessed, try to find out how much more memory a unit can
3505 * claim before hitting the configured cgroup limits (if any). Consider both MemoryHigh
3506 * and MemoryMax, and also any slice the unit might be nested below. */
3507
3508 do {
3509 uint64_t unit_available, unit_limit = UINT64_MAX;
3510 CGroupContext *unit_context;
3511
3512 /* No point in continuing if we can't go any lower */
3513 if (available == 0)
3514 break;
3515
3516 unit_context = unit_get_cgroup_context(u);
3517 if (!unit_context)
3518 return -ENODATA;
3519
3520 (void) unit_get_memory_accounting(u, CGROUP_MEMORY_CURRENT, &current);
3521 /* in case of error, previous current propagates as lower bound */
3522
3523 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
3524 unit_limit = physical_memory();
3525 else if (unit_context->memory_max == UINT64_MAX && unit_context->memory_high == UINT64_MAX)
3526 continue;
3527 unit_limit = MIN3(unit_limit, unit_context->memory_max, unit_context->memory_high);
3528
3529 unit_available = LESS_BY(unit_limit, current);
3530 available = MIN(unit_available, available);
3531 } while ((u = UNIT_GET_SLICE(u)));
3532
3533 *ret = available;
3534
3535 return 0;
3536 }
3537
3538 int unit_get_memory_accounting(Unit *u, CGroupMemoryAccountingMetric metric, uint64_t *ret) {
3539
3540 static const char* const attributes_table[_CGROUP_MEMORY_ACCOUNTING_METRIC_MAX] = {
3541 [CGROUP_MEMORY_CURRENT] = "memory.current",
3542 [CGROUP_MEMORY_PEAK] = "memory.peak",
3543 [CGROUP_MEMORY_SWAP_CURRENT] = "memory.swap.current",
3544 [CGROUP_MEMORY_SWAP_PEAK] = "memory.swap.peak",
3545 [CGROUP_MEMORY_ZSWAP_CURRENT] = "memory.zswap.current",
3546 };
3547
3548 uint64_t bytes;
3549 bool updated = false;
3550 int r;
3551
3552 assert(u);
3553 assert(metric >= 0);
3554 assert(metric < _CGROUP_MEMORY_ACCOUNTING_METRIC_MAX);
3555
3556 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
3557 return -ENODATA;
3558
3559 /* The root cgroup doesn't expose this information. */
3560 if (unit_has_host_root_cgroup(u)) {
3561 /* System-wide memory usage can be acquired from /proc/ */
3562 if (metric == CGROUP_MEMORY_CURRENT)
3563 return procfs_memory_get_used(ret);
3564
3565 return -ENODATA;
3566 }
3567
3568 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3569 if (!crt)
3570 return -ENODATA;
3571 if (!crt->cgroup_path)
3572 /* If the cgroup is already gone, we try to find the last cached value. */
3573 goto finish;
3574
3575 if (!FLAGS_SET(crt->cgroup_realized_mask, CGROUP_MASK_MEMORY))
3576 return -ENODATA;
3577
3578 r = cg_get_attribute_as_uint64(crt->cgroup_path, attributes_table[metric], &bytes);
3579 if (r < 0 && r != -ENODATA)
3580 return r;
3581 updated = r >= 0;
3582
3583 finish:
3584 if (metric <= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST) {
3585 uint64_t *last = &crt->memory_accounting_last[metric];
3586
3587 if (updated)
3588 *last = bytes;
3589 else if (*last != UINT64_MAX)
3590 bytes = *last;
3591 else
3592 return -ENODATA;
3593
3594 } else if (!updated)
3595 return -ENODATA;
3596
3597 if (ret)
3598 *ret = bytes;
3599
3600 return 0;
3601 }
3602
3603 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
3604 assert(u);
3605 assert(ret);
3606
3607 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
3608 return -ENODATA;
3609
3610 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3611 if (!crt || !crt->cgroup_path)
3612 return -ENODATA;
3613
3614 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3615 if (unit_has_host_root_cgroup(u))
3616 return procfs_tasks_get_current(ret);
3617
3618 if ((crt->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
3619 return -ENODATA;
3620
3621 return cg_get_attribute_as_uint64(crt->cgroup_path, "pids.current", ret);
3622 }
3623
3624 static int unit_get_cpu_usage_raw(const Unit *u, const CGroupRuntime *crt, nsec_t *ret) {
3625 int r;
3626
3627 assert(u);
3628 assert(crt);
3629 assert(ret);
3630
3631 if (!crt->cgroup_path)
3632 return -ENODATA;
3633
3634 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3635 if (unit_has_host_root_cgroup(u))
3636 return procfs_cpu_get_usage(ret);
3637
3638 uint64_t us;
3639
3640 r = cg_get_keyed_attribute_uint64(crt->cgroup_path, "cpu.stat", "usage_usec", &us);
3641 if (r < 0)
3642 return r;
3643
3644 *ret = us * NSEC_PER_USEC;
3645
3646 return 0;
3647 }
3648
3649 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
3650 nsec_t ns;
3651 int r;
3652
3653 assert(u);
3654
3655 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
3656 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
3657 * call this function with a NULL return value. */
3658
3659 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3660 if (!crt)
3661 return -ENODATA;
3662
3663 r = unit_get_cpu_usage_raw(u, crt, &ns);
3664 if (r == -ENODATA && crt->cpu_usage_last != NSEC_INFINITY) {
3665 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
3666 * cached value. */
3667
3668 if (ret)
3669 *ret = crt->cpu_usage_last;
3670 return 0;
3671 }
3672 if (r < 0)
3673 return r;
3674
3675 if (ns > crt->cpu_usage_base)
3676 ns -= crt->cpu_usage_base;
3677 else
3678 ns = 0;
3679
3680 crt->cpu_usage_last = ns;
3681 if (ret)
3682 *ret = ns;
3683
3684 return 0;
3685 }
3686
3687 int unit_get_ip_accounting(
3688 Unit *u,
3689 CGroupIPAccountingMetric metric,
3690 uint64_t *ret) {
3691
3692 uint64_t value;
3693 int fd, r;
3694
3695 assert(u);
3696 assert(metric >= 0);
3697 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
3698 assert(ret);
3699
3700 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
3701 return -ENODATA;
3702
3703 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3704 if (!crt)
3705 return -ENODATA;
3706
3707 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
3708 crt->ip_accounting_ingress_map_fd :
3709 crt->ip_accounting_egress_map_fd;
3710 if (fd < 0)
3711 return -ENODATA;
3712
3713 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
3714 r = bpf_firewall_read_accounting(fd, &value, NULL);
3715 else
3716 r = bpf_firewall_read_accounting(fd, NULL, &value);
3717 if (r < 0)
3718 return r;
3719
3720 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
3721 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
3722 * ip_accounting_extra[] field, and add them in here transparently. */
3723
3724 *ret = value + crt->ip_accounting_extra[metric];
3725
3726 return r;
3727 }
3728
3729 static uint64_t unit_get_effective_limit_one(Unit *u, CGroupLimitType type) {
3730 CGroupContext *cc;
3731
3732 assert(u);
3733 assert(UNIT_HAS_CGROUP_CONTEXT(u));
3734
3735 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
3736 switch (type) {
3737 case CGROUP_LIMIT_MEMORY_MAX:
3738 case CGROUP_LIMIT_MEMORY_HIGH:
3739 return physical_memory();
3740 case CGROUP_LIMIT_TASKS_MAX:
3741 return system_tasks_max();
3742 default:
3743 assert_not_reached();
3744 }
3745
3746 cc = ASSERT_PTR(unit_get_cgroup_context(u));
3747 switch (type) {
3748 case CGROUP_LIMIT_MEMORY_MAX:
3749 return cc->memory_max;
3750 case CGROUP_LIMIT_MEMORY_HIGH:
3751 return cc->memory_high;
3752 case CGROUP_LIMIT_TASKS_MAX:
3753 return cgroup_tasks_max_resolve(&cc->tasks_max);
3754 default:
3755 assert_not_reached();
3756 }
3757 }
3758
3759 int unit_get_effective_limit(Unit *u, CGroupLimitType type, uint64_t *ret) {
3760 uint64_t infimum;
3761
3762 assert(u);
3763 assert(ret);
3764 assert(type >= 0);
3765 assert(type < _CGROUP_LIMIT_TYPE_MAX);
3766
3767 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3768 return -EINVAL;
3769
3770 infimum = unit_get_effective_limit_one(u, type);
3771 for (Unit *slice = UNIT_GET_SLICE(u); slice; slice = UNIT_GET_SLICE(slice))
3772 infimum = MIN(infimum, unit_get_effective_limit_one(slice, type));
3773
3774 *ret = infimum;
3775 return 0;
3776 }
3777
3778 static int unit_get_io_accounting_raw(
3779 const Unit *u,
3780 const CGroupRuntime *crt,
3781 uint64_t ret[static _CGROUP_IO_ACCOUNTING_METRIC_MAX]) {
3782
3783 static const char* const field_names[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3784 [CGROUP_IO_READ_BYTES] = "rbytes=",
3785 [CGROUP_IO_WRITE_BYTES] = "wbytes=",
3786 [CGROUP_IO_READ_OPERATIONS] = "rios=",
3787 [CGROUP_IO_WRITE_OPERATIONS] = "wios=",
3788 };
3789
3790 uint64_t acc[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {};
3791 _cleanup_free_ char *path = NULL;
3792 _cleanup_fclose_ FILE *f = NULL;
3793 int r;
3794
3795 assert(u);
3796 assert(crt);
3797
3798 if (!crt->cgroup_path)
3799 return -ENODATA;
3800
3801 if (unit_has_host_root_cgroup(u))
3802 return -ENODATA; /* TODO: return useful data for the top-level cgroup */
3803
3804 if (!FLAGS_SET(crt->cgroup_realized_mask, CGROUP_MASK_IO))
3805 return -ENODATA;
3806
3807 r = cg_get_path(crt->cgroup_path, "io.stat", &path);
3808 if (r < 0)
3809 return r;
3810
3811 f = fopen(path, "re");
3812 if (!f)
3813 return -errno;
3814
3815 for (;;) {
3816 _cleanup_free_ char *line = NULL;
3817 const char *p;
3818
3819 r = read_line(f, LONG_LINE_MAX, &line);
3820 if (r < 0)
3821 return r;
3822 if (r == 0)
3823 break;
3824
3825 p = line;
3826 p += strcspn(p, WHITESPACE); /* Skip over device major/minor */
3827 p += strspn(p, WHITESPACE); /* Skip over following whitespace */
3828
3829 for (;;) {
3830 _cleanup_free_ char *word = NULL;
3831
3832 r = extract_first_word(&p, &word, NULL, EXTRACT_RETAIN_ESCAPE);
3833 if (r < 0)
3834 return r;
3835 if (r == 0)
3836 break;
3837
3838 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
3839 const char *x;
3840
3841 x = startswith(word, field_names[i]);
3842 if (x) {
3843 uint64_t w;
3844
3845 r = safe_atou64(x, &w);
3846 if (r < 0)
3847 return r;
3848
3849 /* Sum up the stats of all devices */
3850 acc[i] += w;
3851 break;
3852 }
3853 }
3854 }
3855 }
3856
3857 memcpy(ret, acc, sizeof(acc));
3858 return 0;
3859 }
3860
3861 int unit_get_io_accounting(
3862 Unit *u,
3863 CGroupIOAccountingMetric metric,
3864 uint64_t *ret) {
3865
3866 uint64_t raw[_CGROUP_IO_ACCOUNTING_METRIC_MAX];
3867 int r;
3868
3869 /*
3870 * Retrieve an IO counter, subtracting the value of the counter value at the time the unit was started.
3871 * If ret == NULL and metric == _<...>_INVALID, no return value is expected (refresh the caches only).
3872 */
3873
3874 assert(u);
3875 assert(metric >= 0 || (!ret && metric == _CGROUP_IO_ACCOUNTING_METRIC_INVALID));
3876 assert(metric < _CGROUP_IO_ACCOUNTING_METRIC_MAX);
3877
3878 if (!UNIT_CGROUP_BOOL(u, io_accounting))
3879 return -ENODATA;
3880
3881 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3882 if (!crt)
3883 return -ENODATA;
3884
3885 r = unit_get_io_accounting_raw(u, crt, raw);
3886 if (r == -ENODATA && metric >= 0 && crt->io_accounting_last[metric] != UINT64_MAX)
3887 goto done;
3888 if (r < 0)
3889 return r;
3890
3891 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
3892 /* Saturated subtraction */
3893 if (raw[i] > crt->io_accounting_base[i])
3894 crt->io_accounting_last[i] = raw[i] - crt->io_accounting_base[i];
3895 else
3896 crt->io_accounting_last[i] = 0;
3897 }
3898
3899 done:
3900 if (ret)
3901 *ret = crt->io_accounting_last[metric];
3902
3903 return 0;
3904 }
3905
3906 static int unit_reset_cpu_accounting(Unit *unit, CGroupRuntime *crt) {
3907 int r;
3908
3909 assert(crt);
3910
3911 crt->cpu_usage_base = 0;
3912 crt->cpu_usage_last = NSEC_INFINITY;
3913
3914 if (unit) {
3915 r = unit_get_cpu_usage_raw(unit, crt, &crt->cpu_usage_base);
3916 if (r < 0 && r != -ENODATA)
3917 return r;
3918 }
3919
3920 return 0;
3921 }
3922
3923 static int unit_reset_io_accounting(Unit *unit, CGroupRuntime *crt) {
3924 int r;
3925
3926 assert(crt);
3927
3928 zero(crt->io_accounting_base);
3929 FOREACH_ELEMENT(i, crt->io_accounting_last)
3930 *i = UINT64_MAX;
3931
3932 if (unit) {
3933 r = unit_get_io_accounting_raw(unit, crt, crt->io_accounting_base);
3934 if (r < 0 && r != -ENODATA)
3935 return r;
3936 }
3937
3938 return 0;
3939 }
3940
3941 static void cgroup_runtime_reset_memory_accounting_last(CGroupRuntime *crt) {
3942 assert(crt);
3943
3944 FOREACH_ELEMENT(i, crt->memory_accounting_last)
3945 *i = UINT64_MAX;
3946 }
3947
3948 static int cgroup_runtime_reset_ip_accounting(CGroupRuntime *crt) {
3949 int r = 0;
3950
3951 assert(crt);
3952
3953 if (crt->ip_accounting_ingress_map_fd >= 0)
3954 RET_GATHER(r, bpf_firewall_reset_accounting(crt->ip_accounting_ingress_map_fd));
3955
3956 if (crt->ip_accounting_egress_map_fd >= 0)
3957 RET_GATHER(r, bpf_firewall_reset_accounting(crt->ip_accounting_egress_map_fd));
3958
3959 zero(crt->ip_accounting_extra);
3960
3961 return r;
3962 }
3963
3964 int unit_reset_accounting(Unit *u) {
3965 int r = 0;
3966
3967 assert(u);
3968
3969 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3970 if (!crt)
3971 return 0;
3972
3973 cgroup_runtime_reset_memory_accounting_last(crt);
3974 RET_GATHER(r, unit_reset_cpu_accounting(u, crt));
3975 RET_GATHER(r, unit_reset_io_accounting(u, crt));
3976 RET_GATHER(r, cgroup_runtime_reset_ip_accounting(crt));
3977
3978 return r;
3979 }
3980
3981 bool unit_invalidate_cgroup(Unit *u, CGroupMask m) {
3982 assert(u);
3983
3984 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3985 return false;
3986
3987 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
3988 if (!crt)
3989 return false;
3990
3991 /* If all controllers shall be invalidated, let's unconditionally submit the unit to realize queue.
3992 * We initialize the field to _CGROUP_MASK_ALL after all, and semantically it makes sense to use
3993 * it as a special signal to forcibly re-realize cgroup. */
3994 if (m != _CGROUP_MASK_ALL &&
3995 FLAGS_SET(crt->cgroup_invalidated_mask, m)) /* NOP? */
3996 return false;
3997
3998 crt->cgroup_invalidated_mask |= m;
3999 unit_add_to_cgroup_realize_queue(u);
4000
4001 return true;
4002 }
4003
4004 void unit_invalidate_cgroup_bpf_firewall(Unit *u) {
4005 assert(u);
4006
4007 if (!unit_invalidate_cgroup(u, CGROUP_MASK_BPF_FIREWALL))
4008 return;
4009
4010 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
4011 * list of our children includes our own. */
4012 if (u->type == UNIT_SLICE) {
4013 Unit *member;
4014
4015 UNIT_FOREACH_DEPENDENCY(member, u, UNIT_ATOM_SLICE_OF)
4016 unit_invalidate_cgroup_bpf_firewall(member);
4017 }
4018 }
4019
4020 void unit_cgroup_catchup(Unit *u) {
4021 assert(u);
4022
4023 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4024 return;
4025
4026 /* We dropped the inotify watch during reexec/reload, so we need to
4027 * check these as they may have changed.
4028 * Note that (currently) the kernel doesn't actually update cgroup
4029 * file modification times, so we can't just serialize and then check
4030 * the mtime for file(s) we are interested in. */
4031 (void) unit_check_cgroup_events(u);
4032 unit_add_to_cgroup_oom_queue(u);
4033 }
4034
4035 bool unit_cgroup_delegate(Unit *u) {
4036 CGroupContext *c;
4037
4038 assert(u);
4039
4040 if (!UNIT_VTABLE(u)->can_delegate)
4041 return false;
4042
4043 c = unit_get_cgroup_context(u);
4044 if (!c)
4045 return false;
4046
4047 return c->delegate;
4048 }
4049
4050 void unit_cgroup_disable_all_controllers(Unit *u) {
4051 int r;
4052
4053 assert(u);
4054
4055 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
4056 if (!crt || !crt->cgroup_path)
4057 return;
4058
4059 if (!unit_cgroup_delegate(u))
4060 return;
4061
4062 /* For delegated units, the previous payload may have enabled controllers (e.g. "pids") in
4063 * cgroup.subtree_control. These persist after the service stops and turn the cgroup into an
4064 * "internal node", causing clone3(CLONE_INTO_CGROUP) to fail with EBUSY. Clear them now, right
4065 * before the new start, so that resource control is preserved for lingering processes as long as
4066 * possible. Ignore errors — if sub-cgroups still have live processes the write will fail, but so
4067 * will the upcoming spawn. */
4068 r = cg_enable(u->manager->cgroup_supported, /* mask= */ 0, crt->cgroup_path, &crt->cgroup_enabled_mask);
4069 if (r < 0)
4070 log_unit_debug_errno(u, r, "Failed to disable controllers on cgroup %s, ignoring: %m", empty_to_root(crt->cgroup_path));
4071 }
4072
4073 void manager_invalidate_startup_units(Manager *m) {
4074 Unit *u;
4075
4076 assert(m);
4077
4078 SET_FOREACH(u, m->startup_units)
4079 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_CPUSET);
4080 }
4081
4082 static int unit_cgroup_freezer_kernel_state(Unit *u, FreezerState *ret) {
4083 _cleanup_free_ char *val = NULL;
4084 FreezerState s;
4085 int r;
4086
4087 assert(u);
4088 assert(ret);
4089
4090 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
4091 if (!crt || !crt->cgroup_path)
4092 return -EOWNERDEAD;
4093
4094 r = cg_get_keyed_attribute(
4095 crt->cgroup_path,
4096 "cgroup.events",
4097 STRV_MAKE("frozen"),
4098 &val);
4099 if (r < 0)
4100 return r;
4101
4102 if (streq(val, "0"))
4103 s = FREEZER_RUNNING;
4104 else if (streq(val, "1"))
4105 s = FREEZER_FROZEN;
4106 else {
4107 log_unit_debug(u, "Unexpected cgroup frozen state: %s", val);
4108 s = _FREEZER_STATE_INVALID;
4109 }
4110
4111 *ret = s;
4112 return 0;
4113 }
4114
4115 int unit_cgroup_freezer_action(Unit *u, FreezerAction action) {
4116 _cleanup_free_ char *path = NULL;
4117 FreezerState current, next, objective;
4118 bool action_in_progress = false;
4119 int r;
4120
4121 assert(u);
4122 assert(action >= 0);
4123 assert(action < _FREEZER_ACTION_MAX);
4124
4125 unit_next_freezer_state(u, action, &next, &objective);
4126
4127 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
4128 if (!crt || !crt->cgroup_path)
4129 /* No realized cgroup = nothing to freeze */
4130 goto finish;
4131
4132 r = unit_cgroup_freezer_kernel_state(u, &current);
4133 if (r < 0)
4134 return r;
4135
4136 if (current == objective) {
4137 if (objective == FREEZER_FROZEN)
4138 goto finish;
4139
4140 /* Skip thaw only if no freeze operation was in flight */
4141 if (IN_SET(u->freezer_state, FREEZER_RUNNING, FREEZER_THAWING))
4142 goto finish;
4143 } else
4144 action_in_progress = true;
4145
4146 if (next == freezer_state_finish(next)) {
4147 /* We're directly transitioning into a finished state, which in theory means that
4148 * the cgroup's current state already matches the objective and thus we'd return 0.
4149 * But, reality shows otherwise (such case would have been handled by current == objective
4150 * branch above). This indicates that our freezer_state tracking has diverged
4151 * from the real state of the cgroup, which can happen if someone meddles with the
4152 * cgroup from underneath us. This really shouldn't happen during normal operation,
4153 * though. So, let's warn about it and fix up the state to be valid */
4154
4155 log_unit_warning(u, "Unit wants to transition to %s freezer state but cgroup is unexpectedly %s, fixing up.",
4156 freezer_state_to_string(next), freezer_state_to_string(current) ?: "(invalid)");
4157
4158 if (next == FREEZER_FROZEN)
4159 next = FREEZER_FREEZING;
4160 else if (next == FREEZER_FROZEN_BY_PARENT)
4161 next = FREEZER_FREEZING_BY_PARENT;
4162 else if (next == FREEZER_RUNNING)
4163 next = FREEZER_THAWING;
4164 else
4165 assert_not_reached();
4166 }
4167
4168 r = cg_get_path(crt->cgroup_path, "cgroup.freeze", &path);
4169 if (r < 0)
4170 return r;
4171
4172 r = write_string_file(path, one_zero(objective == FREEZER_FROZEN), WRITE_STRING_FILE_DISABLE_BUFFER);
4173 if (r < 0)
4174 return r;
4175
4176 finish:
4177 if (action_in_progress)
4178 unit_set_freezer_state(u, next);
4179 else
4180 unit_set_freezer_state(u, freezer_state_finish(next));
4181
4182 return action_in_progress;
4183 }
4184
4185 int unit_get_cpuset(Unit *u, CPUSet *cpus, const char *name) {
4186 _cleanup_free_ char *v = NULL;
4187 int r;
4188
4189 assert(u);
4190 assert(cpus);
4191
4192 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
4193 if (!crt || !crt->cgroup_path)
4194 return -ENODATA;
4195
4196 if ((crt->cgroup_realized_mask & CGROUP_MASK_CPUSET) == 0)
4197 return -ENODATA;
4198
4199 r = cg_get_attribute(crt->cgroup_path, name, &v);
4200 if (r == -ENOENT)
4201 return -ENODATA;
4202 if (r < 0)
4203 return r;
4204
4205 return parse_cpu_set(v, cpus);
4206 }
4207
4208 CGroupRuntime* cgroup_runtime_new(void) {
4209 _cleanup_(cgroup_runtime_freep) CGroupRuntime *crt = NULL;
4210
4211 crt = new(CGroupRuntime, 1);
4212 if (!crt)
4213 return NULL;
4214
4215 *crt = (CGroupRuntime) {
4216 .cgroup_control_inotify_wd = -1,
4217 .cgroup_memory_inotify_wd = -1,
4218
4219 .ip_accounting_ingress_map_fd = -EBADF,
4220 .ip_accounting_egress_map_fd = -EBADF,
4221
4222 .ipv4_allow_map_fd = -EBADF,
4223 .ipv6_allow_map_fd = -EBADF,
4224 .ipv4_deny_map_fd = -EBADF,
4225 .ipv6_deny_map_fd = -EBADF,
4226
4227 .initial_bind_network_interface_link_fd = -EBADF,
4228
4229 .cgroup_invalidated_mask = _CGROUP_MASK_ALL,
4230
4231 .deserialized_cgroup_realized = -1,
4232 };
4233
4234 unit_reset_cpu_accounting(/* unit= */ NULL, crt);
4235 unit_reset_io_accounting(/* unit= */ NULL, crt);
4236 cgroup_runtime_reset_memory_accounting_last(crt);
4237 assert_se(cgroup_runtime_reset_ip_accounting(crt) >= 0);
4238
4239 return TAKE_PTR(crt);
4240 }
4241
4242 CGroupRuntime* cgroup_runtime_free(CGroupRuntime *crt) {
4243 if (!crt)
4244 return NULL;
4245
4246 fdset_free(crt->initial_socket_bind_link_fds);
4247 #if BPF_FRAMEWORK
4248 bpf_link_free(crt->ipv4_socket_bind_link);
4249 bpf_link_free(crt->ipv6_socket_bind_link);
4250 #endif
4251 hashmap_free(crt->bpf_foreign_by_key);
4252
4253 bpf_program_free(crt->bpf_device_control_installed);
4254
4255 #if BPF_FRAMEWORK
4256 bpf_link_free(crt->restrict_ifaces_ingress_bpf_link);
4257 bpf_link_free(crt->restrict_ifaces_egress_bpf_link);
4258
4259 bpf_link_free(crt->bpf_bind_network_interface_link);
4260 #endif
4261
4262 fdset_free(crt->initial_restrict_ifaces_link_fds);
4263 safe_close(crt->initial_bind_network_interface_link_fd);
4264
4265 bpf_firewall_close(crt);
4266
4267 free(crt->cgroup_path);
4268
4269 return mfree(crt);
4270 }
4271
4272 static const char* const ip_accounting_metric_field_table[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
4273 [CGROUP_IP_INGRESS_BYTES] = "ip-accounting-ingress-bytes",
4274 [CGROUP_IP_INGRESS_PACKETS] = "ip-accounting-ingress-packets",
4275 [CGROUP_IP_EGRESS_BYTES] = "ip-accounting-egress-bytes",
4276 [CGROUP_IP_EGRESS_PACKETS] = "ip-accounting-egress-packets",
4277 };
4278
4279 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(ip_accounting_metric_field, CGroupIPAccountingMetric);
4280
4281 static const char* const io_accounting_metric_field_base_table[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
4282 [CGROUP_IO_READ_BYTES] = "io-accounting-read-bytes-base",
4283 [CGROUP_IO_WRITE_BYTES] = "io-accounting-write-bytes-base",
4284 [CGROUP_IO_READ_OPERATIONS] = "io-accounting-read-operations-base",
4285 [CGROUP_IO_WRITE_OPERATIONS] = "io-accounting-write-operations-base",
4286 };
4287
4288 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(io_accounting_metric_field_base, CGroupIOAccountingMetric);
4289
4290 static const char* const io_accounting_metric_field_last_table[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
4291 [CGROUP_IO_READ_BYTES] = "io-accounting-read-bytes-last",
4292 [CGROUP_IO_WRITE_BYTES] = "io-accounting-write-bytes-last",
4293 [CGROUP_IO_READ_OPERATIONS] = "io-accounting-read-operations-last",
4294 [CGROUP_IO_WRITE_OPERATIONS] = "io-accounting-write-operations-last",
4295 };
4296
4297 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(io_accounting_metric_field_last, CGroupIOAccountingMetric);
4298
4299 static const char* const memory_accounting_metric_field_last_table[_CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST + 1] = {
4300 [CGROUP_MEMORY_PEAK] = "memory-accounting-peak",
4301 [CGROUP_MEMORY_SWAP_PEAK] = "memory-accounting-swap-peak",
4302 };
4303
4304 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(memory_accounting_metric_field_last, CGroupMemoryAccountingMetric);
4305
4306 static int serialize_cgroup_mask(FILE *f, const char *key, CGroupMask mask) {
4307 _cleanup_free_ char *s = NULL;
4308 int r;
4309
4310 assert(f);
4311 assert(key);
4312
4313 if (mask == 0)
4314 return 0;
4315
4316 r = cg_mask_to_string(mask, &s);
4317 if (r < 0)
4318 return log_error_errno(r, "Failed to format cgroup mask: %m");
4319
4320 return serialize_item(f, key, s);
4321 }
4322
4323 int cgroup_runtime_serialize(Unit *u, FILE *f, FDSet *fds) {
4324 int r;
4325
4326 assert(u);
4327 assert(f);
4328 assert(fds);
4329
4330 CGroupRuntime *crt = unit_get_cgroup_runtime(u);
4331 if (!crt)
4332 return 0;
4333
4334 if (crt->cgroup_path)
4335 (void) serialize_item(f, "cgroup", crt->cgroup_path);
4336 if (crt->cgroup_id != 0)
4337 (void) serialize_item_format(f, "cgroup-id", "%" PRIu64, crt->cgroup_id);
4338
4339 (void) serialize_cgroup_mask(f, "cgroup-realized-mask", crt->cgroup_realized_mask);
4340 (void) serialize_cgroup_mask(f, "cgroup-enabled-mask", crt->cgroup_enabled_mask);
4341 (void) serialize_cgroup_mask(f, "cgroup-invalidated-mask", crt->cgroup_invalidated_mask);
4342
4343 (void) serialize_item_format(f, "cpu-usage-base", "%" PRIu64, crt->cpu_usage_base);
4344 if (crt->cpu_usage_last != NSEC_INFINITY)
4345 (void) serialize_item_format(f, "cpu-usage-last", "%" PRIu64, crt->cpu_usage_last);
4346
4347 if (crt->managed_oom_kill_last > 0)
4348 (void) serialize_item_format(f, "managed-oom-kill-last", "%" PRIu64, crt->managed_oom_kill_last);
4349
4350 if (crt->oom_kill_last > 0)
4351 (void) serialize_item_format(f, "oom-kill-last", "%" PRIu64, crt->oom_kill_last);
4352
4353 for (CGroupMemoryAccountingMetric metric = 0; metric <= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST; metric++) {
4354 uint64_t v;
4355
4356 r = unit_get_memory_accounting(u, metric, &v);
4357 if (r >= 0)
4358 (void) serialize_item_format(f, memory_accounting_metric_field_last_to_string(metric), "%" PRIu64, v);
4359 }
4360
4361 for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
4362 uint64_t v;
4363
4364 r = unit_get_ip_accounting(u, m, &v);
4365 if (r >= 0)
4366 (void) serialize_item_format(f, ip_accounting_metric_field_to_string(m), "%" PRIu64, v);
4367 }
4368
4369 for (CGroupIOAccountingMetric im = 0; im < _CGROUP_IO_ACCOUNTING_METRIC_MAX; im++) {
4370 (void) serialize_item_format(f, io_accounting_metric_field_base_to_string(im), "%" PRIu64, crt->io_accounting_base[im]);
4371
4372 if (crt->io_accounting_last[im] != UINT64_MAX)
4373 (void) serialize_item_format(f, io_accounting_metric_field_last_to_string(im), "%" PRIu64, crt->io_accounting_last[im]);
4374 }
4375
4376 (void) bpf_socket_bind_serialize(u, f, fds);
4377
4378 (void) bpf_program_serialize_attachment(f, fds, "ip-bpf-ingress-installed", crt->ip_bpf_ingress_installed);
4379 (void) bpf_program_serialize_attachment(f, fds, "ip-bpf-egress-installed", crt->ip_bpf_egress_installed);
4380 (void) bpf_program_serialize_attachment(f, fds, "bpf-device-control-installed", crt->bpf_device_control_installed);
4381 (void) bpf_program_serialize_attachment_set(f, fds, "ip-bpf-custom-ingress-installed", crt->ip_bpf_custom_ingress_installed);
4382 (void) bpf_program_serialize_attachment_set(f, fds, "ip-bpf-custom-egress-installed", crt->ip_bpf_custom_egress_installed);
4383
4384 (void) bpf_restrict_ifaces_serialize(u, f, fds);
4385
4386 (void) bpf_bind_network_interface_serialize(u, f, fds);
4387
4388 return 0;
4389 }
4390
4391 #define MATCH_DESERIALIZE(u, key, l, v, parse_func, target) \
4392 ({ \
4393 bool _deserialize_matched = streq(l, key); \
4394 if (_deserialize_matched) { \
4395 CGroupRuntime *crt = unit_setup_cgroup_runtime(u); \
4396 if (!crt) \
4397 log_oom_debug(); \
4398 else { \
4399 int _deserialize_r = parse_func(v); \
4400 if (_deserialize_r < 0) \
4401 log_unit_debug_errno(u, _deserialize_r, \
4402 "Failed to parse \"%s=%s\", ignoring.", l, v); \
4403 else \
4404 crt->target = _deserialize_r; \
4405 } \
4406 } \
4407 _deserialize_matched; \
4408 })
4409
4410 #define MATCH_DESERIALIZE_IMMEDIATE(u, key, l, v, parse_func, target) \
4411 ({ \
4412 bool _deserialize_matched = streq(l, key); \
4413 if (_deserialize_matched) { \
4414 CGroupRuntime *crt = unit_setup_cgroup_runtime(u); \
4415 if (!crt) \
4416 log_oom_debug(); \
4417 else { \
4418 int _deserialize_r = parse_func(v, &crt->target); \
4419 if (_deserialize_r < 0) \
4420 log_unit_debug_errno(u, _deserialize_r, \
4421 "Failed to parse \"%s=%s\", ignoring", l, v); \
4422 } \
4423 } \
4424 _deserialize_matched; \
4425 })
4426
4427 #define MATCH_DESERIALIZE_METRIC(u, key, l, v, parse_func, target) \
4428 ({ \
4429 bool _deserialize_matched = streq(l, key); \
4430 if (_deserialize_matched) { \
4431 CGroupRuntime *crt = unit_setup_cgroup_runtime(u); \
4432 if (!crt) \
4433 log_oom_debug(); \
4434 else { \
4435 int _deserialize_r = parse_func(v); \
4436 if (_deserialize_r < 0) \
4437 log_unit_debug_errno(u, _deserialize_r, \
4438 "Failed to parse \"%s=%s\", ignoring.", l, v); \
4439 else \
4440 crt->target = _deserialize_r; \
4441 } \
4442 } \
4443 _deserialize_matched; \
4444 })
4445
4446 int cgroup_runtime_deserialize_one(Unit *u, const char *key, const char *value, FDSet *fds) {
4447 int r;
4448
4449 assert(u);
4450 assert(value);
4451
4452 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4453 return 0;
4454
4455 if (MATCH_DESERIALIZE_IMMEDIATE(u, "cpu-usage-base", key, value, safe_atou64, cpu_usage_base))
4456 return 1;
4457
4458 if (MATCH_DESERIALIZE_IMMEDIATE(u, "cpu-usage-last", key, value, safe_atou64, cpu_usage_last))
4459 return 1;
4460
4461 if (MATCH_DESERIALIZE_IMMEDIATE(u, "managed-oom-kill-last", key, value, safe_atou64, managed_oom_kill_last))
4462 return 1;
4463
4464 if (MATCH_DESERIALIZE_IMMEDIATE(u, "oom-kill-last", key, value, safe_atou64, oom_kill_last))
4465 return 1;
4466
4467 if (streq(key, "cgroup")) {
4468 r = unit_set_cgroup_path(u, value);
4469 if (r < 0)
4470 log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", value);
4471
4472 return 1;
4473 }
4474
4475 if (MATCH_DESERIALIZE_IMMEDIATE(u, "cgroup-id", key, value, safe_atou64, cgroup_id))
4476 return 1;
4477
4478 if (MATCH_DESERIALIZE_IMMEDIATE(u, "cgroup-realized", key, value, parse_tristate, deserialized_cgroup_realized))
4479 return 1;
4480
4481 if (MATCH_DESERIALIZE_IMMEDIATE(u, "cgroup-realized-mask", key, value, cg_mask_from_string, cgroup_realized_mask))
4482 return 1;
4483
4484 if (MATCH_DESERIALIZE_IMMEDIATE(u, "cgroup-enabled-mask", key, value, cg_mask_from_string, cgroup_enabled_mask))
4485 return 1;
4486
4487 if (MATCH_DESERIALIZE_IMMEDIATE(u, "cgroup-invalidated-mask", key, value, cg_mask_from_string, cgroup_invalidated_mask))
4488 return 1;
4489
4490 if (STR_IN_SET(key,
4491 "bpf-device-control-installed",
4492 "ip-bpf-ingress-installed", "ip-bpf-egress-installed",
4493 "ip-bpf-custom-ingress-installed", "ip-bpf-custom-egress-installed")) {
4494
4495 CGroupRuntime *crt = unit_setup_cgroup_runtime(u);
4496 if (!crt)
4497 log_oom_debug();
4498 else {
4499 if (streq(key, "bpf-device-control-installed"))
4500 (void) bpf_program_deserialize_attachment(value, fds, &crt->bpf_device_control_installed);
4501
4502 if (streq(key, "ip-bpf-ingress-installed"))
4503 (void) bpf_program_deserialize_attachment(value, fds, &crt->ip_bpf_ingress_installed);
4504
4505 if (streq(key, "ip-bpf-egress-installed"))
4506 (void) bpf_program_deserialize_attachment(value, fds, &crt->ip_bpf_egress_installed);
4507
4508 if (streq(key, "ip-bpf-custom-ingress-installed"))
4509 (void) bpf_program_deserialize_attachment_set(value, fds, &crt->ip_bpf_custom_ingress_installed);
4510
4511 if (streq(key, "ip-bpf-custom-egress-installed"))
4512 (void) bpf_program_deserialize_attachment_set(value, fds, &crt->ip_bpf_custom_egress_installed);
4513 }
4514
4515 return 1;
4516 }
4517
4518 /* We keep the previous bpf link fds stashed until we reattach anew, to close the window where
4519 * the cgroup restrictions would otherwise be lifted. */
4520
4521 if (STR_IN_SET(key, "ipv4-socket-bind-bpf-link-fd", "ipv6-socket-bind-bpf-link-fd")) {
4522 _cleanup_close_ int fd = -EBADF;
4523
4524 fd = deserialize_fd(fds, value);
4525 if (fd >= 0) {
4526 r = bpf_socket_bind_add_initial_link_fd(u, fd);
4527 if (r >= 0)
4528 TAKE_FD(fd);
4529 }
4530
4531 return 1;
4532 }
4533
4534 if (streq(key, "restrict-ifaces-bpf-fd")) {
4535 _cleanup_close_ int fd = -EBADF;
4536
4537 fd = deserialize_fd(fds, value);
4538 if (fd >= 0) {
4539 r = bpf_restrict_ifaces_add_initial_link_fd(u, fd);
4540 if (r >= 0)
4541 TAKE_FD(fd);
4542 }
4543
4544 return 1;
4545 }
4546
4547 if (streq(key, "bind-iface-bpf-fd")) {
4548 _cleanup_close_ int fd = -EBADF;
4549
4550 fd = deserialize_fd(fds, value);
4551 if (fd >= 0) {
4552 CGroupRuntime *crt = unit_setup_cgroup_runtime(u);
4553 if (!crt)
4554 log_oom_debug();
4555 else
4556 close_and_replace(crt->initial_bind_network_interface_link_fd, fd);
4557 }
4558
4559 return 1;
4560 }
4561
4562 CGroupMemoryAccountingMetric mm = memory_accounting_metric_field_last_from_string(key);
4563 if (mm >= 0) {
4564 uint64_t c;
4565
4566 r = safe_atou64(value, &c);
4567 if (r < 0)
4568 log_unit_debug(u, "Failed to parse memory accounting last value %s, ignoring.", value);
4569 else {
4570 CGroupRuntime *crt = unit_setup_cgroup_runtime(u);
4571 if (!crt)
4572 log_oom_debug();
4573 else
4574 crt->memory_accounting_last[mm] = c;
4575 }
4576
4577 return 1;
4578 }
4579
4580 CGroupIPAccountingMetric ipm = ip_accounting_metric_field_from_string(key);
4581 if (ipm >= 0) {
4582 uint64_t c;
4583
4584 r = safe_atou64(value, &c);
4585 if (r < 0)
4586 log_unit_debug(u, "Failed to parse IP accounting value %s, ignoring.", value);
4587 else {
4588 CGroupRuntime *crt = unit_setup_cgroup_runtime(u);
4589 if (!crt)
4590 log_oom_debug();
4591 else
4592 crt->ip_accounting_extra[ipm] = c;
4593 }
4594
4595 return 1;
4596 }
4597
4598 CGroupIOAccountingMetric iom = io_accounting_metric_field_base_from_string(key);
4599 if (iom >= 0) {
4600 uint64_t c;
4601
4602 r = safe_atou64(value, &c);
4603 if (r < 0)
4604 log_unit_debug(u, "Failed to parse IO accounting base value %s, ignoring.", value);
4605 else {
4606 CGroupRuntime *crt = unit_setup_cgroup_runtime(u);
4607 if (!crt)
4608 log_oom_debug();
4609 else
4610 crt->io_accounting_base[iom] = c;
4611 }
4612
4613 return 1;
4614 }
4615
4616 iom = io_accounting_metric_field_last_from_string(key);
4617 if (iom >= 0) {
4618 uint64_t c;
4619
4620 r = safe_atou64(value, &c);
4621 if (r < 0)
4622 log_unit_debug(u, "Failed to parse IO accounting last value %s, ignoring.", value);
4623 else {
4624 CGroupRuntime *crt = unit_setup_cgroup_runtime(u);
4625 if (!crt)
4626 log_oom_debug();
4627 else
4628 crt->io_accounting_last[iom] = c;
4629 }
4630 return 1;
4631 }
4632
4633 return 0;
4634 }
4635
4636 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
4637 [CGROUP_DEVICE_POLICY_AUTO] = "auto",
4638 [CGROUP_DEVICE_POLICY_CLOSED] = "closed",
4639 [CGROUP_DEVICE_POLICY_STRICT] = "strict",
4640 };
4641
4642 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);
4643
4644 static const char* const cpuset_partition_table[_CPUSET_PARTITION_MAX] = {
4645 [CPUSET_PARTITION_MEMBER] = "member",
4646 [CPUSET_PARTITION_ROOT] = "root",
4647 [CPUSET_PARTITION_ISOLATED] = "isolated",
4648 };
4649
4650 DEFINE_STRING_TABLE_LOOKUP(cpuset_partition, CPUSetPartition);
4651
4652 static const char* const cgroup_pressure_watch_table[_CGROUP_PRESSURE_WATCH_MAX] = {
4653 [CGROUP_PRESSURE_WATCH_NO] = "no",
4654 [CGROUP_PRESSURE_WATCH_YES] = "yes",
4655 [CGROUP_PRESSURE_WATCH_AUTO] = "auto",
4656 [CGROUP_PRESSURE_WATCH_SKIP] = "skip",
4657 };
4658
4659 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(cgroup_pressure_watch, CGroupPressureWatch, CGROUP_PRESSURE_WATCH_YES);
4660
4661 static const char* const cgroup_ip_accounting_metric_table[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
4662 [CGROUP_IP_INGRESS_BYTES] = "IPIngressBytes",
4663 [CGROUP_IP_EGRESS_BYTES] = "IPEgressBytes",
4664 [CGROUP_IP_INGRESS_PACKETS] = "IPIngressPackets",
4665 [CGROUP_IP_EGRESS_PACKETS] = "IPEgressPackets",
4666 };
4667
4668 DEFINE_STRING_TABLE_LOOKUP(cgroup_ip_accounting_metric, CGroupIPAccountingMetric);
4669
4670 static const char* const cgroup_io_accounting_metric_table[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
4671 [CGROUP_IO_READ_BYTES] = "IOReadBytes",
4672 [CGROUP_IO_WRITE_BYTES] = "IOWriteBytes",
4673 [CGROUP_IO_READ_OPERATIONS] = "IOReadOperations",
4674 [CGROUP_IO_WRITE_OPERATIONS] = "IOWriteOperations",
4675 };
4676
4677 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_accounting_metric, CGroupIOAccountingMetric);
4678
4679 static const char* const cgroup_memory_accounting_metric_table[_CGROUP_MEMORY_ACCOUNTING_METRIC_MAX] = {
4680 [CGROUP_MEMORY_CURRENT] = "MemoryCurrent",
4681 [CGROUP_MEMORY_PEAK] = "MemoryPeak",
4682 [CGROUP_MEMORY_SWAP_CURRENT] = "MemorySwapCurrent",
4683 [CGROUP_MEMORY_SWAP_PEAK] = "MemorySwapPeak",
4684 [CGROUP_MEMORY_ZSWAP_CURRENT] = "MemoryZSwapCurrent",
4685 };
4686
4687 DEFINE_STRING_TABLE_LOOKUP(cgroup_memory_accounting_metric, CGroupMemoryAccountingMetric);
4688
4689 static const char *const cgroup_effective_limit_type_table[_CGROUP_LIMIT_TYPE_MAX] = {
4690 [CGROUP_LIMIT_MEMORY_MAX] = "EffectiveMemoryMax",
4691 [CGROUP_LIMIT_MEMORY_HIGH] = "EffectiveMemoryHigh",
4692 [CGROUP_LIMIT_TASKS_MAX] = "EffectiveTasksMax",
4693 };
4694
4695 DEFINE_STRING_TABLE_LOOKUP(cgroup_effective_limit_type, CGroupLimitType);