1:255.11-alt1
[systemd_ALT.git] / src / core / cgroup.c
blob61539afdbfcb0e240cd1e3dc67f4f35c3e8b74fb
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <fcntl.h>
5 #include "sd-messages.h"
7 #include "af-list.h"
8 #include "alloc-util.h"
9 #include "blockdev-util.h"
10 #include "bpf-devices.h"
11 #include "bpf-firewall.h"
12 #include "bpf-foreign.h"
13 #include "bpf-socket-bind.h"
14 #include "btrfs-util.h"
15 #include "bus-error.h"
16 #include "bus-locator.h"
17 #include "cgroup-setup.h"
18 #include "cgroup-util.h"
19 #include "cgroup.h"
20 #include "devnum-util.h"
21 #include "fd-util.h"
22 #include "fileio.h"
23 #include "firewall-util.h"
24 #include "in-addr-prefix-util.h"
25 #include "inotify-util.h"
26 #include "io-util.h"
27 #include "ip-protocol-list.h"
28 #include "limits-util.h"
29 #include "nulstr-util.h"
30 #include "parse-util.h"
31 #include "path-util.h"
32 #include "percent-util.h"
33 #include "process-util.h"
34 #include "procfs-util.h"
35 #include "restrict-ifaces.h"
36 #include "special.h"
37 #include "stdio-util.h"
38 #include "string-table.h"
39 #include "string-util.h"
40 #include "virt.h"
42 #if BPF_FRAMEWORK
43 #include "bpf-dlopen.h"
44 #include "bpf-link.h"
45 #include "bpf/restrict_fs/restrict-fs-skel.h"
46 #endif
48 #define CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
50 /* Returns the log level to use when cgroup attribute writes fail. When an attribute is missing or we have access
51 * problems we downgrade to LOG_DEBUG. This is supposed to be nice to container managers and kernels which want to mask
52 * out specific attributes from us. */
53 #define LOG_LEVEL_CGROUP_WRITE(r) (IN_SET(abs(r), ENOENT, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING)
55 uint64_t cgroup_tasks_max_resolve(const CGroupTasksMax *tasks_max) {
56 if (tasks_max->scale == 0)
57 return tasks_max->value;
59 return system_tasks_max_scale(tasks_max->value, tasks_max->scale);
62 bool manager_owns_host_root_cgroup(Manager *m) {
63 assert(m);
65 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
66 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
67 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
68 * we run in any kind of container virtualization. */
70 if (MANAGER_IS_USER(m))
71 return false;
73 if (detect_container() > 0)
74 return false;
76 return empty_or_root(m->cgroup_root);
79 bool unit_has_startup_cgroup_constraints(Unit *u) {
80 assert(u);
82 /* Returns true if this unit has any directives which apply during
83 * startup/shutdown phases. */
85 CGroupContext *c;
87 c = unit_get_cgroup_context(u);
88 if (!c)
89 return false;
91 return c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID ||
92 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
93 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
94 c->startup_cpuset_cpus.set ||
95 c->startup_cpuset_mems.set ||
96 c->startup_memory_high_set ||
97 c->startup_memory_max_set ||
98 c->startup_memory_swap_max_set||
99 c->startup_memory_zswap_max_set ||
100 c->startup_memory_low_set;
103 bool unit_has_host_root_cgroup(const Unit *u) {
104 assert(u);
105 assert(u->manager);
107 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
108 * the manager manages the root cgroup. */
110 if (!manager_owns_host_root_cgroup(u->manager))
111 return false;
113 return unit_has_name(u, SPECIAL_ROOT_SLICE);
116 static int set_attribute_and_warn(Unit *u, const char *controller, const char *attribute, const char *value) {
117 int r;
119 r = cg_set_attribute(controller, u->cgroup_path, attribute, value);
120 if (r < 0)
121 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to set '%s' attribute on '%s' to '%.*s': %m",
122 strna(attribute), empty_to_root(u->cgroup_path), (int) strcspn(value, NEWLINE), value);
124 return r;
127 static void cgroup_compat_warn(void) {
128 static bool cgroup_compat_warned = false;
130 if (cgroup_compat_warned)
131 return;
133 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
134 "See cgroup-compat debug messages for details.");
136 cgroup_compat_warned = true;
139 #define log_cgroup_compat(unit, fmt, ...) do { \
140 cgroup_compat_warn(); \
141 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
142 } while (false)
144 void cgroup_context_init(CGroupContext *c) {
145 assert(c);
147 /* Initialize everything to the kernel defaults. When initializing a bool member to 'true', make
148 * sure to serialize in execute-serialize.c using serialize_bool() instead of
149 * serialize_bool_elide(), as sd-executor will initialize here to 'true', but serialize_bool_elide()
150 * skips serialization if the value is 'false' (as that's the common default), so if the value at
151 * runtime is zero it would be lost after deserialization. Same when initializing uint64_t and other
152 * values, update/add a conditional serialization check. This is to minimize the amount of
153 * serialized data that is sent to the sd-executor, so that there is less work to do on the default
154 * cases. */
156 *c = (CGroupContext) {
157 .cpu_weight = CGROUP_WEIGHT_INVALID,
158 .startup_cpu_weight = CGROUP_WEIGHT_INVALID,
159 .cpu_quota_per_sec_usec = USEC_INFINITY,
160 .cpu_quota_period_usec = USEC_INFINITY,
162 .cpu_shares = CGROUP_CPU_SHARES_INVALID,
163 .startup_cpu_shares = CGROUP_CPU_SHARES_INVALID,
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,
174 .memory_limit = CGROUP_LIMIT_MAX,
176 .io_weight = CGROUP_WEIGHT_INVALID,
177 .startup_io_weight = CGROUP_WEIGHT_INVALID,
179 .blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
180 .startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
182 .tasks_max = CGROUP_TASKS_MAX_UNSET,
184 .moom_swap = MANAGED_OOM_AUTO,
185 .moom_mem_pressure = MANAGED_OOM_AUTO,
186 .moom_preference = MANAGED_OOM_PREFERENCE_NONE,
188 .memory_pressure_watch = _CGROUP_PRESSURE_WATCH_INVALID,
189 .memory_pressure_threshold_usec = USEC_INFINITY,
193 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
194 assert(c);
195 assert(a);
197 LIST_REMOVE(device_allow, c->device_allow, a);
198 free(a->path);
199 free(a);
202 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
203 assert(c);
204 assert(w);
206 LIST_REMOVE(device_weights, c->io_device_weights, w);
207 free(w->path);
208 free(w);
211 void cgroup_context_free_io_device_latency(CGroupContext *c, CGroupIODeviceLatency *l) {
212 assert(c);
213 assert(l);
215 LIST_REMOVE(device_latencies, c->io_device_latencies, l);
216 free(l->path);
217 free(l);
220 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
221 assert(c);
222 assert(l);
224 LIST_REMOVE(device_limits, c->io_device_limits, l);
225 free(l->path);
226 free(l);
229 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
230 assert(c);
231 assert(w);
233 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
234 free(w->path);
235 free(w);
238 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
239 assert(c);
240 assert(b);
242 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
243 free(b->path);
244 free(b);
247 void cgroup_context_remove_bpf_foreign_program(CGroupContext *c, CGroupBPFForeignProgram *p) {
248 assert(c);
249 assert(p);
251 LIST_REMOVE(programs, c->bpf_foreign_programs, p);
252 free(p->bpffs_path);
253 free(p);
256 void cgroup_context_remove_socket_bind(CGroupSocketBindItem **head) {
257 assert(head);
259 LIST_CLEAR(socket_bind_items, *head, free);
262 void cgroup_context_done(CGroupContext *c) {
263 assert(c);
265 while (c->io_device_weights)
266 cgroup_context_free_io_device_weight(c, c->io_device_weights);
268 while (c->io_device_latencies)
269 cgroup_context_free_io_device_latency(c, c->io_device_latencies);
271 while (c->io_device_limits)
272 cgroup_context_free_io_device_limit(c, c->io_device_limits);
274 while (c->blockio_device_weights)
275 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
277 while (c->blockio_device_bandwidths)
278 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
280 while (c->device_allow)
281 cgroup_context_free_device_allow(c, c->device_allow);
283 cgroup_context_remove_socket_bind(&c->socket_bind_allow);
284 cgroup_context_remove_socket_bind(&c->socket_bind_deny);
286 c->ip_address_allow = set_free(c->ip_address_allow);
287 c->ip_address_deny = set_free(c->ip_address_deny);
289 c->ip_filters_ingress = strv_free(c->ip_filters_ingress);
290 c->ip_filters_egress = strv_free(c->ip_filters_egress);
292 while (c->bpf_foreign_programs)
293 cgroup_context_remove_bpf_foreign_program(c, c->bpf_foreign_programs);
295 c->restrict_network_interfaces = set_free_free(c->restrict_network_interfaces);
297 cpu_set_reset(&c->cpuset_cpus);
298 cpu_set_reset(&c->startup_cpuset_cpus);
299 cpu_set_reset(&c->cpuset_mems);
300 cpu_set_reset(&c->startup_cpuset_mems);
302 c->delegate_subgroup = mfree(c->delegate_subgroup);
304 nft_set_context_clear(&c->nft_set_context);
307 static int unit_get_kernel_memory_limit(Unit *u, const char *file, uint64_t *ret) {
308 assert(u);
310 if (!u->cgroup_realized)
311 return -EOWNERDEAD;
313 return cg_get_attribute_as_uint64("memory", u->cgroup_path, file, ret);
316 static int unit_compare_memory_limit(Unit *u, const char *property_name, uint64_t *ret_unit_value, uint64_t *ret_kernel_value) {
317 CGroupContext *c;
318 CGroupMask m;
319 const char *file;
320 uint64_t unit_value;
321 int r;
323 /* Compare kernel memcg configuration against our internal systemd state. Unsupported (and will
324 * return -ENODATA) on cgroup v1.
326 * Returns:
328 * <0: On error.
329 * 0: If the kernel memory setting doesn't match our configuration.
330 * >0: If the kernel memory setting matches our configuration.
332 * The following values are only guaranteed to be populated on return >=0:
334 * - ret_unit_value will contain our internal expected value for the unit, page-aligned.
335 * - ret_kernel_value will contain the actual value presented by the kernel. */
337 assert(u);
339 r = cg_all_unified();
340 if (r < 0)
341 return log_debug_errno(r, "Failed to determine cgroup hierarchy version: %m");
343 /* Unsupported on v1.
345 * We don't return ENOENT, since that could actually mask a genuine problem where somebody else has
346 * silently masked the controller. */
347 if (r == 0)
348 return -ENODATA;
350 /* The root slice doesn't have any controller files, so we can't compare anything. */
351 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
352 return -ENODATA;
354 /* It's possible to have MemoryFoo set without systemd wanting to have the memory controller enabled,
355 * for example, in the case of DisableControllers= or cgroup_disable on the kernel command line. To
356 * avoid specious errors in these scenarios, check that we even expect the memory controller to be
357 * enabled at all. */
358 m = unit_get_target_mask(u);
359 if (!FLAGS_SET(m, CGROUP_MASK_MEMORY))
360 return -ENODATA;
362 assert_se(c = unit_get_cgroup_context(u));
364 bool startup = u->manager && IN_SET(manager_state(u->manager), MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING);
366 if (streq(property_name, "MemoryLow")) {
367 unit_value = unit_get_ancestor_memory_low(u);
368 file = "memory.low";
369 } else if (startup && streq(property_name, "StartupMemoryLow")) {
370 unit_value = unit_get_ancestor_startup_memory_low(u);
371 file = "memory.low";
372 } else if (streq(property_name, "MemoryMin")) {
373 unit_value = unit_get_ancestor_memory_min(u);
374 file = "memory.min";
375 } else if (streq(property_name, "MemoryHigh")) {
376 unit_value = c->memory_high;
377 file = "memory.high";
378 } else if (startup && streq(property_name, "StartupMemoryHigh")) {
379 unit_value = c->startup_memory_high;
380 file = "memory.high";
381 } else if (streq(property_name, "MemoryMax")) {
382 unit_value = c->memory_max;
383 file = "memory.max";
384 } else if (startup && streq(property_name, "StartupMemoryMax")) {
385 unit_value = c->startup_memory_max;
386 file = "memory.max";
387 } else if (streq(property_name, "MemorySwapMax")) {
388 unit_value = c->memory_swap_max;
389 file = "memory.swap.max";
390 } else if (startup && streq(property_name, "StartupMemorySwapMax")) {
391 unit_value = c->startup_memory_swap_max;
392 file = "memory.swap.max";
393 } else if (streq(property_name, "MemoryZSwapMax")) {
394 unit_value = c->memory_zswap_max;
395 file = "memory.zswap.max";
396 } else if (startup && streq(property_name, "StartupMemoryZSwapMax")) {
397 unit_value = c->startup_memory_zswap_max;
398 file = "memory.zswap.max";
399 } else
400 return -EINVAL;
402 r = unit_get_kernel_memory_limit(u, file, ret_kernel_value);
403 if (r < 0)
404 return log_unit_debug_errno(u, r, "Failed to parse %s: %m", file);
406 /* It's intended (soon) in a future kernel to not expose cgroup memory limits rounded to page
407 * boundaries, but instead separate the user-exposed limit, which is whatever userspace told us, from
408 * our internal page-counting. To support those future kernels, just check the value itself first
409 * without any page-alignment. */
410 if (*ret_kernel_value == unit_value) {
411 *ret_unit_value = unit_value;
412 return 1;
415 /* The current kernel behaviour, by comparison, is that even if you write a particular number of
416 * bytes into a cgroup memory file, it always returns that number page-aligned down (since the kernel
417 * internally stores cgroup limits in pages). As such, so long as it aligns properly, everything is
418 * cricket. */
419 if (unit_value != CGROUP_LIMIT_MAX)
420 unit_value = PAGE_ALIGN_DOWN(unit_value);
422 *ret_unit_value = unit_value;
424 return *ret_kernel_value == *ret_unit_value;
427 #define FORMAT_CGROUP_DIFF_MAX 128
429 static char *format_cgroup_memory_limit_comparison(char *buf, size_t l, Unit *u, const char *property_name) {
430 uint64_t kval, sval;
431 int r;
433 assert(u);
434 assert(buf);
435 assert(l > 0);
437 r = unit_compare_memory_limit(u, property_name, &sval, &kval);
439 /* memory.swap.max is special in that it relies on CONFIG_MEMCG_SWAP (and the default swapaccount=1).
440 * In the absence of reliably being able to detect whether memcg swap support is available or not,
441 * only complain if the error is not ENOENT. This is similarly the case for memory.zswap.max relying
442 * on CONFIG_ZSWAP. */
443 if (r > 0 || IN_SET(r, -ENODATA, -EOWNERDEAD) ||
444 (r == -ENOENT && STR_IN_SET(property_name,
445 "MemorySwapMax",
446 "StartupMemorySwapMax",
447 "MemoryZSwapMax",
448 "StartupMemoryZSwapMax")))
449 buf[0] = 0;
450 else if (r < 0) {
451 errno = -r;
452 (void) snprintf(buf, l, " (error getting kernel value: %m)");
453 } else
454 (void) snprintf(buf, l, " (different value in kernel: %" PRIu64 ")", kval);
456 return buf;
459 const char *cgroup_device_permissions_to_string(CGroupDevicePermissions p) {
460 static const char *table[_CGROUP_DEVICE_PERMISSIONS_MAX] = {
461 /* Lets simply define a table with every possible combination. As long as those are just 8 we
462 * can get away with it. If this ever grows to more we need to revisit this logic though. */
463 [0] = "",
464 [CGROUP_DEVICE_READ] = "r",
465 [CGROUP_DEVICE_WRITE] = "w",
466 [CGROUP_DEVICE_MKNOD] = "m",
467 [CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE] = "rw",
468 [CGROUP_DEVICE_READ|CGROUP_DEVICE_MKNOD] = "rm",
469 [CGROUP_DEVICE_WRITE|CGROUP_DEVICE_MKNOD] = "wm",
470 [CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE|CGROUP_DEVICE_MKNOD] = "rwm",
473 if (p < 0 || p >= _CGROUP_DEVICE_PERMISSIONS_MAX)
474 return NULL;
476 return table[p];
479 CGroupDevicePermissions cgroup_device_permissions_from_string(const char *s) {
480 CGroupDevicePermissions p = 0;
482 if (!s)
483 return _CGROUP_DEVICE_PERMISSIONS_INVALID;
485 for (const char *c = s; *c; c++) {
486 if (*c == 'r')
487 p |= CGROUP_DEVICE_READ;
488 else if (*c == 'w')
489 p |= CGROUP_DEVICE_WRITE;
490 else if (*c == 'm')
491 p |= CGROUP_DEVICE_MKNOD;
492 else
493 return _CGROUP_DEVICE_PERMISSIONS_INVALID;
496 return p;
499 void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
500 _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;
501 CGroupContext *c;
502 struct in_addr_prefix *iaai;
504 char cda[FORMAT_CGROUP_DIFF_MAX];
505 char cdb[FORMAT_CGROUP_DIFF_MAX];
506 char cdc[FORMAT_CGROUP_DIFF_MAX];
507 char cdd[FORMAT_CGROUP_DIFF_MAX];
508 char cde[FORMAT_CGROUP_DIFF_MAX];
509 char cdf[FORMAT_CGROUP_DIFF_MAX];
510 char cdg[FORMAT_CGROUP_DIFF_MAX];
511 char cdh[FORMAT_CGROUP_DIFF_MAX];
512 char cdi[FORMAT_CGROUP_DIFF_MAX];
513 char cdj[FORMAT_CGROUP_DIFF_MAX];
514 char cdk[FORMAT_CGROUP_DIFF_MAX];
516 assert(u);
517 assert(f);
519 assert_se(c = unit_get_cgroup_context(u));
521 prefix = strempty(prefix);
523 (void) cg_mask_to_string(c->disable_controllers, &disable_controllers_str);
524 (void) cg_mask_to_string(c->delegate_controllers, &delegate_controllers_str);
526 /* "Delegate=" means "yes, but no controllers". Show this as "(none)". */
527 const char *delegate_str = delegate_controllers_str ?: c->delegate ? "(none)" : "no";
529 cpuset_cpus = cpu_set_to_range_string(&c->cpuset_cpus);
530 startup_cpuset_cpus = cpu_set_to_range_string(&c->startup_cpuset_cpus);
531 cpuset_mems = cpu_set_to_range_string(&c->cpuset_mems);
532 startup_cpuset_mems = cpu_set_to_range_string(&c->startup_cpuset_mems);
534 fprintf(f,
535 "%sCPUAccounting: %s\n"
536 "%sIOAccounting: %s\n"
537 "%sBlockIOAccounting: %s\n"
538 "%sMemoryAccounting: %s\n"
539 "%sTasksAccounting: %s\n"
540 "%sIPAccounting: %s\n"
541 "%sCPUWeight: %" PRIu64 "\n"
542 "%sStartupCPUWeight: %" PRIu64 "\n"
543 "%sCPUShares: %" PRIu64 "\n"
544 "%sStartupCPUShares: %" PRIu64 "\n"
545 "%sCPUQuotaPerSecSec: %s\n"
546 "%sCPUQuotaPeriodSec: %s\n"
547 "%sAllowedCPUs: %s\n"
548 "%sStartupAllowedCPUs: %s\n"
549 "%sAllowedMemoryNodes: %s\n"
550 "%sStartupAllowedMemoryNodes: %s\n"
551 "%sIOWeight: %" PRIu64 "\n"
552 "%sStartupIOWeight: %" PRIu64 "\n"
553 "%sBlockIOWeight: %" PRIu64 "\n"
554 "%sStartupBlockIOWeight: %" PRIu64 "\n"
555 "%sDefaultMemoryMin: %" PRIu64 "\n"
556 "%sDefaultMemoryLow: %" PRIu64 "\n"
557 "%sMemoryMin: %" PRIu64 "%s\n"
558 "%sMemoryLow: %" PRIu64 "%s\n"
559 "%sStartupMemoryLow: %" PRIu64 "%s\n"
560 "%sMemoryHigh: %" PRIu64 "%s\n"
561 "%sStartupMemoryHigh: %" PRIu64 "%s\n"
562 "%sMemoryMax: %" PRIu64 "%s\n"
563 "%sStartupMemoryMax: %" PRIu64 "%s\n"
564 "%sMemorySwapMax: %" PRIu64 "%s\n"
565 "%sStartupMemorySwapMax: %" PRIu64 "%s\n"
566 "%sMemoryZSwapMax: %" PRIu64 "%s\n"
567 "%sStartupMemoryZSwapMax: %" PRIu64 "%s\n"
568 "%sMemoryLimit: %" PRIu64 "\n"
569 "%sTasksMax: %" PRIu64 "\n"
570 "%sDevicePolicy: %s\n"
571 "%sDisableControllers: %s\n"
572 "%sDelegate: %s\n"
573 "%sManagedOOMSwap: %s\n"
574 "%sManagedOOMMemoryPressure: %s\n"
575 "%sManagedOOMMemoryPressureLimit: " PERMYRIAD_AS_PERCENT_FORMAT_STR "\n"
576 "%sManagedOOMPreference: %s\n"
577 "%sMemoryPressureWatch: %s\n"
578 "%sCoredumpReceive: %s\n",
579 prefix, yes_no(c->cpu_accounting),
580 prefix, yes_no(c->io_accounting),
581 prefix, yes_no(c->blockio_accounting),
582 prefix, yes_no(c->memory_accounting),
583 prefix, yes_no(c->tasks_accounting),
584 prefix, yes_no(c->ip_accounting),
585 prefix, c->cpu_weight,
586 prefix, c->startup_cpu_weight,
587 prefix, c->cpu_shares,
588 prefix, c->startup_cpu_shares,
589 prefix, FORMAT_TIMESPAN(c->cpu_quota_per_sec_usec, 1),
590 prefix, FORMAT_TIMESPAN(c->cpu_quota_period_usec, 1),
591 prefix, strempty(cpuset_cpus),
592 prefix, strempty(startup_cpuset_cpus),
593 prefix, strempty(cpuset_mems),
594 prefix, strempty(startup_cpuset_mems),
595 prefix, c->io_weight,
596 prefix, c->startup_io_weight,
597 prefix, c->blockio_weight,
598 prefix, c->startup_blockio_weight,
599 prefix, c->default_memory_min,
600 prefix, c->default_memory_low,
601 prefix, c->memory_min, format_cgroup_memory_limit_comparison(cda, sizeof(cda), u, "MemoryMin"),
602 prefix, c->memory_low, format_cgroup_memory_limit_comparison(cdb, sizeof(cdb), u, "MemoryLow"),
603 prefix, c->startup_memory_low, format_cgroup_memory_limit_comparison(cdc, sizeof(cdc), u, "StartupMemoryLow"),
604 prefix, c->memory_high, format_cgroup_memory_limit_comparison(cdd, sizeof(cdd), u, "MemoryHigh"),
605 prefix, c->startup_memory_high, format_cgroup_memory_limit_comparison(cde, sizeof(cde), u, "StartupMemoryHigh"),
606 prefix, c->memory_max, format_cgroup_memory_limit_comparison(cdf, sizeof(cdf), u, "MemoryMax"),
607 prefix, c->startup_memory_max, format_cgroup_memory_limit_comparison(cdg, sizeof(cdg), u, "StartupMemoryMax"),
608 prefix, c->memory_swap_max, format_cgroup_memory_limit_comparison(cdh, sizeof(cdh), u, "MemorySwapMax"),
609 prefix, c->startup_memory_swap_max, format_cgroup_memory_limit_comparison(cdi, sizeof(cdi), u, "StartupMemorySwapMax"),
610 prefix, c->memory_zswap_max, format_cgroup_memory_limit_comparison(cdj, sizeof(cdj), u, "MemoryZSwapMax"),
611 prefix, c->startup_memory_zswap_max, format_cgroup_memory_limit_comparison(cdk, sizeof(cdk), u, "StartupMemoryZSwapMax"),
612 prefix, c->memory_limit,
613 prefix, cgroup_tasks_max_resolve(&c->tasks_max),
614 prefix, cgroup_device_policy_to_string(c->device_policy),
615 prefix, strempty(disable_controllers_str),
616 prefix, delegate_str,
617 prefix, managed_oom_mode_to_string(c->moom_swap),
618 prefix, managed_oom_mode_to_string(c->moom_mem_pressure),
619 prefix, PERMYRIAD_AS_PERCENT_FORMAT_VAL(UINT32_SCALE_TO_PERMYRIAD(c->moom_mem_pressure_limit)),
620 prefix, managed_oom_preference_to_string(c->moom_preference),
621 prefix, cgroup_pressure_watch_to_string(c->memory_pressure_watch),
622 prefix, yes_no(c->coredump_receive));
624 if (c->delegate_subgroup)
625 fprintf(f, "%sDelegateSubgroup: %s\n",
626 prefix, c->delegate_subgroup);
628 if (c->memory_pressure_threshold_usec != USEC_INFINITY)
629 fprintf(f, "%sMemoryPressureThresholdSec: %s\n",
630 prefix, FORMAT_TIMESPAN(c->memory_pressure_threshold_usec, 1));
632 LIST_FOREACH(device_allow, a, c->device_allow)
633 /* strna() below should be redundant, for avoiding -Werror=format-overflow= error. See #30223. */
634 fprintf(f,
635 "%sDeviceAllow: %s %s\n",
636 prefix,
637 a->path,
638 strna(cgroup_device_permissions_to_string(a->permissions)));
640 LIST_FOREACH(device_weights, iw, c->io_device_weights)
641 fprintf(f,
642 "%sIODeviceWeight: %s %" PRIu64 "\n",
643 prefix,
644 iw->path,
645 iw->weight);
647 LIST_FOREACH(device_latencies, l, c->io_device_latencies)
648 fprintf(f,
649 "%sIODeviceLatencyTargetSec: %s %s\n",
650 prefix,
651 l->path,
652 FORMAT_TIMESPAN(l->target_usec, 1));
654 LIST_FOREACH(device_limits, il, c->io_device_limits)
655 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
656 if (il->limits[type] != cgroup_io_limit_defaults[type])
657 fprintf(f,
658 "%s%s: %s %s\n",
659 prefix,
660 cgroup_io_limit_type_to_string(type),
661 il->path,
662 FORMAT_BYTES(il->limits[type]));
664 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
665 fprintf(f,
666 "%sBlockIODeviceWeight: %s %" PRIu64,
667 prefix,
668 w->path,
669 w->weight);
671 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
672 if (b->rbps != CGROUP_LIMIT_MAX)
673 fprintf(f,
674 "%sBlockIOReadBandwidth: %s %s\n",
675 prefix,
676 b->path,
677 FORMAT_BYTES(b->rbps));
678 if (b->wbps != CGROUP_LIMIT_MAX)
679 fprintf(f,
680 "%sBlockIOWriteBandwidth: %s %s\n",
681 prefix,
682 b->path,
683 FORMAT_BYTES(b->wbps));
686 SET_FOREACH(iaai, c->ip_address_allow)
687 fprintf(f, "%sIPAddressAllow: %s\n", prefix,
688 IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
689 SET_FOREACH(iaai, c->ip_address_deny)
690 fprintf(f, "%sIPAddressDeny: %s\n", prefix,
691 IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
693 STRV_FOREACH(path, c->ip_filters_ingress)
694 fprintf(f, "%sIPIngressFilterPath: %s\n", prefix, *path);
695 STRV_FOREACH(path, c->ip_filters_egress)
696 fprintf(f, "%sIPEgressFilterPath: %s\n", prefix, *path);
698 LIST_FOREACH(programs, p, c->bpf_foreign_programs)
699 fprintf(f, "%sBPFProgram: %s:%s",
700 prefix, bpf_cgroup_attach_type_to_string(p->attach_type), p->bpffs_path);
702 if (c->socket_bind_allow) {
703 fprintf(f, "%sSocketBindAllow: ", prefix);
704 cgroup_context_dump_socket_bind_items(c->socket_bind_allow, f);
705 fputc('\n', f);
708 if (c->socket_bind_deny) {
709 fprintf(f, "%sSocketBindDeny: ", prefix);
710 cgroup_context_dump_socket_bind_items(c->socket_bind_deny, f);
711 fputc('\n', f);
714 if (c->restrict_network_interfaces) {
715 char *iface;
716 SET_FOREACH(iface, c->restrict_network_interfaces)
717 fprintf(f, "%sRestrictNetworkInterfaces: %s\n", prefix, iface);
720 FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets)
721 fprintf(f, "%sNFTSet: %s:%s:%s:%s\n", prefix, nft_set_source_to_string(nft_set->source),
722 nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set);
725 void cgroup_context_dump_socket_bind_item(const CGroupSocketBindItem *item, FILE *f) {
726 const char *family, *colon1, *protocol = "", *colon2 = "";
728 family = strempty(af_to_ipv4_ipv6(item->address_family));
729 colon1 = isempty(family) ? "" : ":";
731 if (item->ip_protocol != 0) {
732 protocol = ip_protocol_to_tcp_udp(item->ip_protocol);
733 colon2 = ":";
736 if (item->nr_ports == 0)
737 fprintf(f, "%s%s%s%sany", family, colon1, protocol, colon2);
738 else if (item->nr_ports == 1)
739 fprintf(f, "%s%s%s%s%" PRIu16, family, colon1, protocol, colon2, item->port_min);
740 else {
741 uint16_t port_max = item->port_min + item->nr_ports - 1;
742 fprintf(f, "%s%s%s%s%" PRIu16 "-%" PRIu16, family, colon1, protocol, colon2,
743 item->port_min, port_max);
747 void cgroup_context_dump_socket_bind_items(const CGroupSocketBindItem *items, FILE *f) {
748 bool first = true;
750 LIST_FOREACH(socket_bind_items, bi, items) {
751 if (first)
752 first = false;
753 else
754 fputc(' ', f);
756 cgroup_context_dump_socket_bind_item(bi, f);
760 int cgroup_context_add_device_allow(CGroupContext *c, const char *dev, CGroupDevicePermissions p) {
761 _cleanup_free_ CGroupDeviceAllow *a = NULL;
762 _cleanup_free_ char *d = NULL;
764 assert(c);
765 assert(dev);
766 assert(p >= 0 && p < _CGROUP_DEVICE_PERMISSIONS_MAX);
768 if (p == 0)
769 p = _CGROUP_DEVICE_PERMISSIONS_ALL;
771 a = new(CGroupDeviceAllow, 1);
772 if (!a)
773 return -ENOMEM;
775 d = strdup(dev);
776 if (!d)
777 return -ENOMEM;
779 *a = (CGroupDeviceAllow) {
780 .path = TAKE_PTR(d),
781 .permissions = p,
784 LIST_PREPEND(device_allow, c->device_allow, a);
785 TAKE_PTR(a);
787 return 0;
790 int cgroup_context_add_or_update_device_allow(CGroupContext *c, const char *dev, CGroupDevicePermissions p) {
791 assert(c);
792 assert(dev);
793 assert(p >= 0 && p < _CGROUP_DEVICE_PERMISSIONS_MAX);
795 if (p == 0)
796 p = _CGROUP_DEVICE_PERMISSIONS_ALL;
798 LIST_FOREACH(device_allow, b, c->device_allow)
799 if (path_equal(b->path, dev)) {
800 b->permissions = p;
801 return 0;
804 return cgroup_context_add_device_allow(c, dev, p);
807 int cgroup_context_add_bpf_foreign_program(CGroupContext *c, uint32_t attach_type, const char *bpffs_path) {
808 CGroupBPFForeignProgram *p;
809 _cleanup_free_ char *d = NULL;
811 assert(c);
812 assert(bpffs_path);
814 if (!path_is_normalized(bpffs_path) || !path_is_absolute(bpffs_path))
815 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not normalized: %m");
817 d = strdup(bpffs_path);
818 if (!d)
819 return log_oom();
821 p = new(CGroupBPFForeignProgram, 1);
822 if (!p)
823 return log_oom();
825 *p = (CGroupBPFForeignProgram) {
826 .attach_type = attach_type,
827 .bpffs_path = TAKE_PTR(d),
830 LIST_PREPEND(programs, c->bpf_foreign_programs, TAKE_PTR(p));
832 return 0;
835 #define UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(entry) \
836 uint64_t unit_get_ancestor_##entry(Unit *u) { \
837 CGroupContext *c; \
839 /* 1. Is entry set in this unit? If so, use that. \
840 * 2. Is the default for this entry set in any \
841 * ancestor? If so, use that. \
842 * 3. Otherwise, return CGROUP_LIMIT_MIN. */ \
844 assert(u); \
846 c = unit_get_cgroup_context(u); \
847 if (c && c->entry##_set) \
848 return c->entry; \
850 while ((u = UNIT_GET_SLICE(u))) { \
851 c = unit_get_cgroup_context(u); \
852 if (c && c->default_##entry##_set) \
853 return c->default_##entry; \
856 /* We've reached the root, but nobody had default for \
857 * this entry set, so set it to the kernel default. */ \
858 return CGROUP_LIMIT_MIN; \
861 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_low);
862 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(startup_memory_low);
863 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_min);
865 static void unit_set_xattr_graceful(Unit *u, const char *name, const void *data, size_t size) {
866 int r;
868 assert(u);
869 assert(name);
871 if (!u->cgroup_path)
872 return;
874 r = cg_set_xattr(u->cgroup_path, name, data, size, 0);
875 if (r < 0)
876 log_unit_debug_errno(u, r, "Failed to set '%s' xattr on control group %s, ignoring: %m", name, empty_to_root(u->cgroup_path));
879 static void unit_remove_xattr_graceful(Unit *u, const char *name) {
880 int r;
882 assert(u);
883 assert(name);
885 if (!u->cgroup_path)
886 return;
888 r = cg_remove_xattr(u->cgroup_path, name);
889 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
890 log_unit_debug_errno(u, r, "Failed to remove '%s' xattr flag on control group %s, ignoring: %m", name, empty_to_root(u->cgroup_path));
893 static void cgroup_oomd_xattr_apply(Unit *u) {
894 CGroupContext *c;
896 assert(u);
898 c = unit_get_cgroup_context(u);
899 if (!c)
900 return;
902 if (c->moom_preference == MANAGED_OOM_PREFERENCE_OMIT)
903 unit_set_xattr_graceful(u, "user.oomd_omit", "1", 1);
905 if (c->moom_preference == MANAGED_OOM_PREFERENCE_AVOID)
906 unit_set_xattr_graceful(u, "user.oomd_avoid", "1", 1);
908 if (c->moom_preference != MANAGED_OOM_PREFERENCE_AVOID)
909 unit_remove_xattr_graceful(u, "user.oomd_avoid");
911 if (c->moom_preference != MANAGED_OOM_PREFERENCE_OMIT)
912 unit_remove_xattr_graceful(u, "user.oomd_omit");
915 static int cgroup_log_xattr_apply(Unit *u) {
916 ExecContext *c;
917 size_t len, allowed_patterns_len, denied_patterns_len;
918 _cleanup_free_ char *patterns = NULL, *allowed_patterns = NULL, *denied_patterns = NULL;
919 char *last;
920 int r;
922 assert(u);
924 c = unit_get_exec_context(u);
925 if (!c)
926 /* Some unit types have a cgroup context but no exec context, so we do not log
927 * any error here to avoid confusion. */
928 return 0;
930 if (set_isempty(c->log_filter_allowed_patterns) && set_isempty(c->log_filter_denied_patterns)) {
931 unit_remove_xattr_graceful(u, "user.journald_log_filter_patterns");
932 return 0;
935 r = set_make_nulstr(c->log_filter_allowed_patterns, &allowed_patterns, &allowed_patterns_len);
936 if (r < 0)
937 return log_debug_errno(r, "Failed to make nulstr from set: %m");
939 r = set_make_nulstr(c->log_filter_denied_patterns, &denied_patterns, &denied_patterns_len);
940 if (r < 0)
941 return log_debug_errno(r, "Failed to make nulstr from set: %m");
943 /* Use nul character separated strings without trailing nul */
944 allowed_patterns_len = LESS_BY(allowed_patterns_len, 1u);
945 denied_patterns_len = LESS_BY(denied_patterns_len, 1u);
947 len = allowed_patterns_len + 1 + denied_patterns_len;
948 patterns = new(char, len);
949 if (!patterns)
950 return log_oom_debug();
952 last = mempcpy_safe(patterns, allowed_patterns, allowed_patterns_len);
953 *(last++) = '\xff';
954 memcpy_safe(last, denied_patterns, denied_patterns_len);
956 unit_set_xattr_graceful(u, "user.journald_log_filter_patterns", patterns, len);
958 return 0;
961 static void cgroup_invocation_id_xattr_apply(Unit *u) {
962 bool b;
964 assert(u);
966 b = !sd_id128_is_null(u->invocation_id);
967 FOREACH_STRING(xn, "trusted.invocation_id", "user.invocation_id") {
968 if (b)
969 unit_set_xattr_graceful(u, xn, SD_ID128_TO_STRING(u->invocation_id), 32);
970 else
971 unit_remove_xattr_graceful(u, xn);
975 static void cgroup_coredump_xattr_apply(Unit *u) {
976 CGroupContext *c;
978 assert(u);
980 c = unit_get_cgroup_context(u);
981 if (!c)
982 return;
984 if (unit_cgroup_delegate(u) && c->coredump_receive)
985 unit_set_xattr_graceful(u, "user.coredump_receive", "1", 1);
986 else
987 unit_remove_xattr_graceful(u, "user.coredump_receive");
990 static void cgroup_delegate_xattr_apply(Unit *u) {
991 bool b;
993 assert(u);
995 /* Indicate on the cgroup whether delegation is on, via an xattr. This is best-effort, as old kernels
996 * didn't support xattrs on cgroups at all. Later they got support for setting 'trusted.*' xattrs,
997 * and even later 'user.*' xattrs. We started setting this field when 'trusted.*' was added, and
998 * given this is now pretty much API, let's continue to support that. But also set 'user.*' as well,
999 * since it is readable by any user, not just CAP_SYS_ADMIN. This hence comes with slightly weaker
1000 * security (as users who got delegated cgroups could turn it off if they like), but this shouldn't
1001 * be a big problem given this communicates delegation state to clients, but the manager never reads
1002 * it. */
1003 b = unit_cgroup_delegate(u);
1004 FOREACH_STRING(xn, "trusted.delegate", "user.delegate") {
1005 if (b)
1006 unit_set_xattr_graceful(u, xn, "1", 1);
1007 else
1008 unit_remove_xattr_graceful(u, xn);
1012 static void cgroup_survive_xattr_apply(Unit *u) {
1013 int r;
1015 assert(u);
1017 if (u->survive_final_kill_signal) {
1018 r = cg_set_xattr(
1019 u->cgroup_path,
1020 "user.survive_final_kill_signal",
1021 "1",
1023 /* flags= */ 0);
1024 /* user xattr support was added in kernel v5.7 */
1025 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
1026 r = cg_set_xattr(
1027 u->cgroup_path,
1028 "trusted.survive_final_kill_signal",
1029 "1",
1031 /* flags= */ 0);
1032 if (r < 0)
1033 log_unit_debug_errno(u,
1035 "Failed to set 'survive_final_kill_signal' xattr on control "
1036 "group %s, ignoring: %m",
1037 empty_to_root(u->cgroup_path));
1038 } else {
1039 unit_remove_xattr_graceful(u, "user.survive_final_kill_signal");
1040 unit_remove_xattr_graceful(u, "trusted.survive_final_kill_signal");
1044 static void cgroup_xattr_apply(Unit *u) {
1045 assert(u);
1047 /* The 'user.*' xattrs can be set from a user manager. */
1048 cgroup_oomd_xattr_apply(u);
1049 cgroup_log_xattr_apply(u);
1050 cgroup_coredump_xattr_apply(u);
1052 if (!MANAGER_IS_SYSTEM(u->manager))
1053 return;
1055 cgroup_invocation_id_xattr_apply(u);
1056 cgroup_delegate_xattr_apply(u);
1057 cgroup_survive_xattr_apply(u);
1060 static int lookup_block_device(const char *p, dev_t *ret) {
1061 dev_t rdev, dev = 0;
1062 mode_t mode;
1063 int r;
1065 assert(p);
1066 assert(ret);
1068 r = device_path_parse_major_minor(p, &mode, &rdev);
1069 if (r == -ENODEV) { /* not a parsable device node, need to go to disk */
1070 struct stat st;
1072 if (stat(p, &st) < 0)
1073 return log_warning_errno(errno, "Couldn't stat device '%s': %m", p);
1075 mode = st.st_mode;
1076 rdev = st.st_rdev;
1077 dev = st.st_dev;
1078 } else if (r < 0)
1079 return log_warning_errno(r, "Failed to parse major/minor from path '%s': %m", p);
1081 if (S_ISCHR(mode))
1082 return log_warning_errno(SYNTHETIC_ERRNO(ENOTBLK),
1083 "Device node '%s' is a character device, but block device needed.", p);
1084 if (S_ISBLK(mode))
1085 *ret = rdev;
1086 else if (major(dev) != 0)
1087 *ret = dev; /* If this is not a device node then use the block device this file is stored on */
1088 else {
1089 /* If this is btrfs, getting the backing block device is a bit harder */
1090 r = btrfs_get_block_device(p, ret);
1091 if (r == -ENOTTY)
1092 return log_warning_errno(SYNTHETIC_ERRNO(ENODEV),
1093 "'%s' is not a block device node, and file system block device cannot be determined or is not local.", p);
1094 if (r < 0)
1095 return log_warning_errno(r, "Failed to determine block device backing btrfs file system '%s': %m", p);
1098 /* If this is a LUKS/DM device, recursively try to get the originating block device */
1099 while (block_get_originating(*ret, ret) > 0);
1101 /* If this is a partition, try to get the originating block device */
1102 (void) block_get_whole_disk(*ret, ret);
1103 return 0;
1106 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
1107 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
1108 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
1111 static bool cgroup_context_has_cpu_shares(CGroupContext *c) {
1112 return c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
1113 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID;
1116 static bool cgroup_context_has_allowed_cpus(CGroupContext *c) {
1117 return c->cpuset_cpus.set || c->startup_cpuset_cpus.set;
1120 static bool cgroup_context_has_allowed_mems(CGroupContext *c) {
1121 return c->cpuset_mems.set || c->startup_cpuset_mems.set;
1124 uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
1125 assert(c);
1127 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1128 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
1129 return c->startup_cpu_weight;
1130 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
1131 return c->cpu_weight;
1132 else
1133 return CGROUP_WEIGHT_DEFAULT;
1136 static uint64_t cgroup_context_cpu_shares(CGroupContext *c, ManagerState state) {
1137 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1138 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID)
1139 return c->startup_cpu_shares;
1140 else if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID)
1141 return c->cpu_shares;
1142 else
1143 return CGROUP_CPU_SHARES_DEFAULT;
1146 static CPUSet *cgroup_context_allowed_cpus(CGroupContext *c, ManagerState state) {
1147 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1148 c->startup_cpuset_cpus.set)
1149 return &c->startup_cpuset_cpus;
1150 else
1151 return &c->cpuset_cpus;
1154 static CPUSet *cgroup_context_allowed_mems(CGroupContext *c, ManagerState state) {
1155 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1156 c->startup_cpuset_mems.set)
1157 return &c->startup_cpuset_mems;
1158 else
1159 return &c->cpuset_mems;
1162 usec_t cgroup_cpu_adjust_period(usec_t period, usec_t quota, usec_t resolution, usec_t max_period) {
1163 /* kernel uses a minimum resolution of 1ms, so both period and (quota * period)
1164 * need to be higher than that boundary. quota is specified in USecPerSec.
1165 * Additionally, period must be at most max_period. */
1166 assert(quota > 0);
1168 return MIN(MAX3(period, resolution, resolution * USEC_PER_SEC / quota), max_period);
1171 static usec_t cgroup_cpu_adjust_period_and_log(Unit *u, usec_t period, usec_t quota) {
1172 usec_t new_period;
1174 if (quota == USEC_INFINITY)
1175 /* Always use default period for infinity quota. */
1176 return CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
1178 if (period == USEC_INFINITY)
1179 /* Default period was requested. */
1180 period = CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
1182 /* Clamp to interval [1ms, 1s] */
1183 new_period = cgroup_cpu_adjust_period(period, quota, USEC_PER_MSEC, USEC_PER_SEC);
1185 if (new_period != period) {
1186 log_unit_full(u, u->warned_clamping_cpu_quota_period ? LOG_DEBUG : LOG_WARNING,
1187 "Clamping CPU interval for cpu.max: period is now %s",
1188 FORMAT_TIMESPAN(new_period, 1));
1189 u->warned_clamping_cpu_quota_period = true;
1192 return new_period;
1195 static void cgroup_apply_unified_cpu_weight(Unit *u, uint64_t weight) {
1196 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1198 if (weight == CGROUP_WEIGHT_IDLE)
1199 return;
1200 xsprintf(buf, "%" PRIu64 "\n", weight);
1201 (void) set_attribute_and_warn(u, "cpu", "cpu.weight", buf);
1204 static void cgroup_apply_unified_cpu_idle(Unit *u, uint64_t weight) {
1205 int r;
1206 bool is_idle;
1207 const char *idle_val;
1209 is_idle = weight == CGROUP_WEIGHT_IDLE;
1210 idle_val = one_zero(is_idle);
1211 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.idle", idle_val);
1212 if (r < 0 && (r != -ENOENT || is_idle))
1213 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to set '%s' attribute on '%s' to '%s': %m",
1214 "cpu.idle", empty_to_root(u->cgroup_path), idle_val);
1217 static void cgroup_apply_unified_cpu_quota(Unit *u, usec_t quota, usec_t period) {
1218 char buf[(DECIMAL_STR_MAX(usec_t) + 1) * 2 + 1];
1220 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
1221 if (quota != USEC_INFINITY)
1222 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
1223 MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC), period);
1224 else
1225 xsprintf(buf, "max " USEC_FMT "\n", period);
1226 (void) set_attribute_and_warn(u, "cpu", "cpu.max", buf);
1229 static void cgroup_apply_legacy_cpu_shares(Unit *u, uint64_t shares) {
1230 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1232 xsprintf(buf, "%" PRIu64 "\n", shares);
1233 (void) set_attribute_and_warn(u, "cpu", "cpu.shares", buf);
1236 static void cgroup_apply_legacy_cpu_quota(Unit *u, usec_t quota, usec_t period) {
1237 char buf[DECIMAL_STR_MAX(usec_t) + 2];
1239 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
1241 xsprintf(buf, USEC_FMT "\n", period);
1242 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_period_us", buf);
1244 if (quota != USEC_INFINITY) {
1245 xsprintf(buf, USEC_FMT "\n", MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC));
1246 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", buf);
1247 } else
1248 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", "-1\n");
1251 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares) {
1252 return CLAMP(shares * CGROUP_WEIGHT_DEFAULT / CGROUP_CPU_SHARES_DEFAULT,
1253 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
1256 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight) {
1257 /* we don't support idle in cgroupv1 */
1258 if (weight == CGROUP_WEIGHT_IDLE)
1259 return CGROUP_CPU_SHARES_MIN;
1261 return CLAMP(weight * CGROUP_CPU_SHARES_DEFAULT / CGROUP_WEIGHT_DEFAULT,
1262 CGROUP_CPU_SHARES_MIN, CGROUP_CPU_SHARES_MAX);
1265 static void cgroup_apply_unified_cpuset(Unit *u, const CPUSet *cpus, const char *name) {
1266 _cleanup_free_ char *buf = NULL;
1268 buf = cpu_set_to_range_string(cpus);
1269 if (!buf) {
1270 log_oom();
1271 return;
1274 (void) set_attribute_and_warn(u, "cpuset", name, buf);
1277 static bool cgroup_context_has_io_config(CGroupContext *c) {
1278 return c->io_accounting ||
1279 c->io_weight != CGROUP_WEIGHT_INVALID ||
1280 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
1281 c->io_device_weights ||
1282 c->io_device_latencies ||
1283 c->io_device_limits;
1286 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
1287 return c->blockio_accounting ||
1288 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
1289 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
1290 c->blockio_device_weights ||
1291 c->blockio_device_bandwidths;
1294 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
1295 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1296 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
1297 return c->startup_io_weight;
1298 if (c->io_weight != CGROUP_WEIGHT_INVALID)
1299 return c->io_weight;
1300 return CGROUP_WEIGHT_DEFAULT;
1303 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
1304 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1305 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
1306 return c->startup_blockio_weight;
1307 if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
1308 return c->blockio_weight;
1309 return CGROUP_BLKIO_WEIGHT_DEFAULT;
1312 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
1313 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
1314 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
1317 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
1318 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
1319 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
1322 static int set_bfq_weight(Unit *u, const char *controller, dev_t dev, uint64_t io_weight) {
1323 static const char * const prop_names[] = {
1324 "IOWeight",
1325 "BlockIOWeight",
1326 "IODeviceWeight",
1327 "BlockIODeviceWeight",
1329 static bool warned = false;
1330 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+STRLEN("\n")];
1331 const char *p;
1332 uint64_t bfq_weight;
1333 int r;
1335 /* FIXME: drop this function when distro kernels properly support BFQ through "io.weight"
1336 * See also: https://github.com/systemd/systemd/pull/13335 and
1337 * https://github.com/torvalds/linux/commit/65752aef0a407e1ef17ec78a7fc31ba4e0b360f9. */
1338 p = strjoina(controller, ".bfq.weight");
1339 /* Adjust to kernel range is 1..1000, the default is 100. */
1340 bfq_weight = BFQ_WEIGHT(io_weight);
1342 if (major(dev) > 0)
1343 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), bfq_weight);
1344 else
1345 xsprintf(buf, "%" PRIu64 "\n", bfq_weight);
1347 r = cg_set_attribute(controller, u->cgroup_path, p, buf);
1349 /* FIXME: drop this when kernels prior
1350 * 795fe54c2a82 ("bfq: Add per-device weight") v5.4
1351 * are not interesting anymore. Old kernels will fail with EINVAL, while new kernels won't return
1352 * EINVAL on properly formatted input by us. Treat EINVAL accordingly. */
1353 if (r == -EINVAL && major(dev) > 0) {
1354 if (!warned) {
1355 log_unit_warning(u, "Kernel version does not accept per-device setting in %s.", p);
1356 warned = true;
1358 r = -EOPNOTSUPP; /* mask as unconfigured device */
1359 } else if (r >= 0 && io_weight != bfq_weight)
1360 log_unit_debug(u, "%s=%" PRIu64 " scaled to %s=%" PRIu64,
1361 prop_names[2*(major(dev) > 0) + streq(controller, "blkio")],
1362 io_weight, p, bfq_weight);
1363 return r;
1366 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
1367 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1368 dev_t dev;
1369 int r, r1, r2;
1371 if (lookup_block_device(dev_path, &dev) < 0)
1372 return;
1374 r1 = set_bfq_weight(u, "io", dev, io_weight);
1376 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), io_weight);
1377 r2 = cg_set_attribute("io", u->cgroup_path, "io.weight", buf);
1379 /* Look at the configured device, when both fail, prefer io.weight errno. */
1380 r = r2 == -EOPNOTSUPP ? r1 : r2;
1382 if (r < 0)
1383 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r),
1384 r, "Failed to set 'io[.bfq].weight' attribute on '%s' to '%.*s': %m",
1385 empty_to_root(u->cgroup_path), (int) strcspn(buf, NEWLINE), buf);
1388 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
1389 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1390 dev_t dev;
1391 int r;
1393 r = lookup_block_device(dev_path, &dev);
1394 if (r < 0)
1395 return;
1397 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), blkio_weight);
1398 (void) set_attribute_and_warn(u, "blkio", "blkio.weight_device", buf);
1401 static void cgroup_apply_io_device_latency(Unit *u, const char *dev_path, usec_t target) {
1402 char buf[DECIMAL_STR_MAX(dev_t)*2+2+7+DECIMAL_STR_MAX(uint64_t)+1];
1403 dev_t dev;
1404 int r;
1406 r = lookup_block_device(dev_path, &dev);
1407 if (r < 0)
1408 return;
1410 if (target != USEC_INFINITY)
1411 xsprintf(buf, DEVNUM_FORMAT_STR " target=%" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), target);
1412 else
1413 xsprintf(buf, DEVNUM_FORMAT_STR " target=max\n", DEVNUM_FORMAT_VAL(dev));
1415 (void) set_attribute_and_warn(u, "io", "io.latency", buf);
1418 static void cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
1419 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)],
1420 buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
1421 dev_t dev;
1423 if (lookup_block_device(dev_path, &dev) < 0)
1424 return;
1426 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
1427 if (limits[type] != cgroup_io_limit_defaults[type])
1428 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
1429 else
1430 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
1432 xsprintf(buf, DEVNUM_FORMAT_STR " rbps=%s wbps=%s riops=%s wiops=%s\n", DEVNUM_FORMAT_VAL(dev),
1433 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
1434 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
1435 (void) set_attribute_and_warn(u, "io", "io.max", buf);
1438 static void cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
1439 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1440 dev_t dev;
1442 if (lookup_block_device(dev_path, &dev) < 0)
1443 return;
1445 sprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), rbps);
1446 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.read_bps_device", buf);
1448 sprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), wbps);
1449 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.write_bps_device", buf);
1452 static bool unit_has_unified_memory_config(Unit *u) {
1453 CGroupContext *c;
1455 assert(u);
1457 assert_se(c = unit_get_cgroup_context(u));
1459 return unit_get_ancestor_memory_min(u) > 0 ||
1460 unit_get_ancestor_memory_low(u) > 0 || unit_get_ancestor_startup_memory_low(u) > 0 ||
1461 c->memory_high != CGROUP_LIMIT_MAX || c->startup_memory_high_set ||
1462 c->memory_max != CGROUP_LIMIT_MAX || c->startup_memory_max_set ||
1463 c->memory_swap_max != CGROUP_LIMIT_MAX || c->startup_memory_swap_max_set ||
1464 c->memory_zswap_max != CGROUP_LIMIT_MAX || c->startup_memory_zswap_max_set;
1467 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
1468 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max\n";
1470 if (v != CGROUP_LIMIT_MAX)
1471 xsprintf(buf, "%" PRIu64 "\n", v);
1473 (void) set_attribute_and_warn(u, "memory", file, buf);
1476 static void cgroup_apply_firewall(Unit *u) {
1477 assert(u);
1479 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
1481 if (bpf_firewall_compile(u) < 0)
1482 return;
1484 (void) bpf_firewall_load_custom(u);
1485 (void) bpf_firewall_install(u);
1488 void unit_modify_nft_set(Unit *u, bool add) {
1489 int r;
1491 assert(u);
1493 if (!MANAGER_IS_SYSTEM(u->manager))
1494 return;
1496 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1497 return;
1499 if (cg_all_unified() <= 0)
1500 return;
1502 if (u->cgroup_id == 0)
1503 return;
1505 if (!u->manager->fw_ctx) {
1506 r = fw_ctx_new_full(&u->manager->fw_ctx, /* init_tables= */ false);
1507 if (r < 0)
1508 return;
1510 assert(u->manager->fw_ctx);
1513 CGroupContext *c = ASSERT_PTR(unit_get_cgroup_context(u));
1515 FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets) {
1516 if (nft_set->source != NFT_SET_SOURCE_CGROUP)
1517 continue;
1519 uint64_t element = u->cgroup_id;
1521 r = nft_set_element_modify_any(u->manager->fw_ctx, add, nft_set->nfproto, nft_set->table, nft_set->set, &element, sizeof(element));
1522 if (r < 0)
1523 log_warning_errno(r, "Failed to %s NFT set: family %s, table %s, set %s, cgroup %" PRIu64 ", ignoring: %m",
1524 add? "add" : "delete", nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set, u->cgroup_id);
1525 else
1526 log_debug("%s NFT set: family %s, table %s, set %s, cgroup %" PRIu64,
1527 add? "Added" : "Deleted", nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set, u->cgroup_id);
1531 static void cgroup_apply_socket_bind(Unit *u) {
1532 assert(u);
1534 (void) bpf_socket_bind_install(u);
1537 static void cgroup_apply_restrict_network_interfaces(Unit *u) {
1538 assert(u);
1540 (void) restrict_network_interfaces_install(u);
1543 static int cgroup_apply_devices(Unit *u) {
1544 _cleanup_(bpf_program_freep) BPFProgram *prog = NULL;
1545 const char *path;
1546 CGroupContext *c;
1547 CGroupDevicePolicy policy;
1548 int r;
1550 assert_se(c = unit_get_cgroup_context(u));
1551 assert_se(path = u->cgroup_path);
1553 policy = c->device_policy;
1555 if (cg_all_unified() > 0) {
1556 r = bpf_devices_cgroup_init(&prog, policy, c->device_allow);
1557 if (r < 0)
1558 return log_unit_warning_errno(u, r, "Failed to initialize device control bpf program: %m");
1560 } else {
1561 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore
1562 * EINVAL here. */
1564 if (c->device_allow || policy != CGROUP_DEVICE_POLICY_AUTO)
1565 r = cg_set_attribute("devices", path, "devices.deny", "a");
1566 else
1567 r = cg_set_attribute("devices", path, "devices.allow", "a");
1568 if (r < 0)
1569 log_unit_full_errno(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING, r,
1570 "Failed to reset devices.allow/devices.deny: %m");
1573 bool allow_list_static = policy == CGROUP_DEVICE_POLICY_CLOSED ||
1574 (policy == CGROUP_DEVICE_POLICY_AUTO && c->device_allow);
1575 if (allow_list_static)
1576 (void) bpf_devices_allow_list_static(prog, path);
1578 bool any = allow_list_static;
1579 LIST_FOREACH(device_allow, a, c->device_allow) {
1580 const char *val;
1582 if (a->permissions == 0)
1583 continue;
1585 if (path_startswith(a->path, "/dev/"))
1586 r = bpf_devices_allow_list_device(prog, path, a->path, a->permissions);
1587 else if ((val = startswith(a->path, "block-")))
1588 r = bpf_devices_allow_list_major(prog, path, val, 'b', a->permissions);
1589 else if ((val = startswith(a->path, "char-")))
1590 r = bpf_devices_allow_list_major(prog, path, val, 'c', a->permissions);
1591 else {
1592 log_unit_debug(u, "Ignoring device '%s' while writing cgroup attribute.", a->path);
1593 continue;
1596 if (r >= 0)
1597 any = true;
1600 if (prog && !any) {
1601 log_unit_warning_errno(u, SYNTHETIC_ERRNO(ENODEV), "No devices matched by device filter.");
1603 /* The kernel verifier would reject a program we would build with the normal intro and outro
1604 but no allow-listing rules (outro would contain an unreachable instruction for successful
1605 return). */
1606 policy = CGROUP_DEVICE_POLICY_STRICT;
1609 r = bpf_devices_apply_policy(&prog, policy, any, path, &u->bpf_device_control_installed);
1610 if (r < 0) {
1611 static bool warned = false;
1613 log_full_errno(warned ? LOG_DEBUG : LOG_WARNING, r,
1614 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1615 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1616 "(This warning is only shown for the first loaded unit using device ACL.)", u->id);
1618 warned = true;
1620 return r;
1623 static void set_io_weight(Unit *u, uint64_t weight) {
1624 char buf[STRLEN("default \n")+DECIMAL_STR_MAX(uint64_t)];
1626 assert(u);
1628 (void) set_bfq_weight(u, "io", makedev(0, 0), weight);
1630 xsprintf(buf, "default %" PRIu64 "\n", weight);
1631 (void) set_attribute_and_warn(u, "io", "io.weight", buf);
1634 static void set_blkio_weight(Unit *u, uint64_t weight) {
1635 char buf[STRLEN("\n")+DECIMAL_STR_MAX(uint64_t)];
1637 assert(u);
1639 (void) set_bfq_weight(u, "blkio", makedev(0, 0), weight);
1641 xsprintf(buf, "%" PRIu64 "\n", weight);
1642 (void) set_attribute_and_warn(u, "blkio", "blkio.weight", buf);
1645 static void cgroup_apply_bpf_foreign_program(Unit *u) {
1646 assert(u);
1648 (void) bpf_foreign_install(u);
1651 static void cgroup_context_apply(
1652 Unit *u,
1653 CGroupMask apply_mask,
1654 ManagerState state) {
1656 const char *path;
1657 CGroupContext *c;
1658 bool is_host_root, is_local_root;
1659 int r;
1661 assert(u);
1663 /* Nothing to do? Exit early! */
1664 if (apply_mask == 0)
1665 return;
1667 /* Some cgroup attributes are not supported on the host root cgroup, hence silently ignore them here. And other
1668 * attributes should only be managed for cgroups further down the tree. */
1669 is_local_root = unit_has_name(u, SPECIAL_ROOT_SLICE);
1670 is_host_root = unit_has_host_root_cgroup(u);
1672 assert_se(c = unit_get_cgroup_context(u));
1673 assert_se(path = u->cgroup_path);
1675 if (is_local_root) /* Make sure we don't try to display messages with an empty path. */
1676 path = "/";
1678 /* We generally ignore errors caused by read-only mounted cgroup trees (assuming we are running in a container
1679 * then), and missing cgroups, i.e. EROFS and ENOENT. */
1681 /* In fully unified mode these attributes don't exist on the host cgroup root. On legacy the weights exist, but
1682 * setting the weight makes very little sense on the host root cgroup, as there are no other cgroups at this
1683 * level. The quota exists there too, but any attempt to write to it is refused with EINVAL. Inside of
1684 * containers we want to leave control of these to the container manager (and if cgroup v2 delegation is used
1685 * we couldn't even write to them if we wanted to). */
1686 if ((apply_mask & CGROUP_MASK_CPU) && !is_local_root) {
1688 if (cg_all_unified() > 0) {
1689 uint64_t weight;
1691 if (cgroup_context_has_cpu_weight(c))
1692 weight = cgroup_context_cpu_weight(c, state);
1693 else if (cgroup_context_has_cpu_shares(c)) {
1694 uint64_t shares;
1696 shares = cgroup_context_cpu_shares(c, state);
1697 weight = cgroup_cpu_shares_to_weight(shares);
1699 log_cgroup_compat(u, "Applying [Startup]CPUShares=%" PRIu64 " as [Startup]CPUWeight=%" PRIu64 " on %s",
1700 shares, weight, path);
1701 } else
1702 weight = CGROUP_WEIGHT_DEFAULT;
1704 cgroup_apply_unified_cpu_idle(u, weight);
1705 cgroup_apply_unified_cpu_weight(u, weight);
1706 cgroup_apply_unified_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
1708 } else {
1709 uint64_t shares;
1711 if (cgroup_context_has_cpu_weight(c)) {
1712 uint64_t weight;
1714 weight = cgroup_context_cpu_weight(c, state);
1715 shares = cgroup_cpu_weight_to_shares(weight);
1717 log_cgroup_compat(u, "Applying [Startup]CPUWeight=%" PRIu64 " as [Startup]CPUShares=%" PRIu64 " on %s",
1718 weight, shares, path);
1719 } else if (cgroup_context_has_cpu_shares(c))
1720 shares = cgroup_context_cpu_shares(c, state);
1721 else
1722 shares = CGROUP_CPU_SHARES_DEFAULT;
1724 cgroup_apply_legacy_cpu_shares(u, shares);
1725 cgroup_apply_legacy_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
1729 if ((apply_mask & CGROUP_MASK_CPUSET) && !is_local_root) {
1730 cgroup_apply_unified_cpuset(u, cgroup_context_allowed_cpus(c, state), "cpuset.cpus");
1731 cgroup_apply_unified_cpuset(u, cgroup_context_allowed_mems(c, state), "cpuset.mems");
1734 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroup v2
1735 * controller), and in case of containers we want to leave control of these attributes to the container manager
1736 * (and we couldn't access that stuff anyway, even if we tried if proper delegation is used). */
1737 if ((apply_mask & CGROUP_MASK_IO) && !is_local_root) {
1738 bool has_io, has_blockio;
1739 uint64_t weight;
1741 has_io = cgroup_context_has_io_config(c);
1742 has_blockio = cgroup_context_has_blockio_config(c);
1744 if (has_io)
1745 weight = cgroup_context_io_weight(c, state);
1746 else if (has_blockio) {
1747 uint64_t blkio_weight;
1749 blkio_weight = cgroup_context_blkio_weight(c, state);
1750 weight = cgroup_weight_blkio_to_io(blkio_weight);
1752 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight=%" PRIu64 " as [Startup]IOWeight=%" PRIu64,
1753 blkio_weight, weight);
1754 } else
1755 weight = CGROUP_WEIGHT_DEFAULT;
1757 set_io_weight(u, weight);
1759 if (has_io) {
1760 LIST_FOREACH(device_weights, w, c->io_device_weights)
1761 cgroup_apply_io_device_weight(u, w->path, w->weight);
1763 LIST_FOREACH(device_limits, limit, c->io_device_limits)
1764 cgroup_apply_io_device_limit(u, limit->path, limit->limits);
1766 LIST_FOREACH(device_latencies, latency, c->io_device_latencies)
1767 cgroup_apply_io_device_latency(u, latency->path, latency->target_usec);
1769 } else if (has_blockio) {
1770 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
1771 weight = cgroup_weight_blkio_to_io(w->weight);
1773 log_cgroup_compat(u, "Applying BlockIODeviceWeight=%" PRIu64 " as IODeviceWeight=%" PRIu64 " for %s",
1774 w->weight, weight, w->path);
1776 cgroup_apply_io_device_weight(u, w->path, weight);
1779 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
1780 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
1782 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
1783 limits[type] = cgroup_io_limit_defaults[type];
1785 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
1786 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
1788 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax= for %s",
1789 b->rbps, b->wbps, b->path);
1791 cgroup_apply_io_device_limit(u, b->path, limits);
1796 if (apply_mask & CGROUP_MASK_BLKIO) {
1797 bool has_io, has_blockio;
1799 has_io = cgroup_context_has_io_config(c);
1800 has_blockio = cgroup_context_has_blockio_config(c);
1802 /* Applying a 'weight' never makes sense for the host root cgroup, and for containers this should be
1803 * left to our container manager, too. */
1804 if (!is_local_root) {
1805 uint64_t weight;
1807 if (has_io) {
1808 uint64_t io_weight;
1810 io_weight = cgroup_context_io_weight(c, state);
1811 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
1813 log_cgroup_compat(u, "Applying [Startup]IOWeight=%" PRIu64 " as [Startup]BlockIOWeight=%" PRIu64,
1814 io_weight, weight);
1815 } else if (has_blockio)
1816 weight = cgroup_context_blkio_weight(c, state);
1817 else
1818 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
1820 set_blkio_weight(u, weight);
1822 if (has_io)
1823 LIST_FOREACH(device_weights, w, c->io_device_weights) {
1824 weight = cgroup_weight_io_to_blkio(w->weight);
1826 log_cgroup_compat(u, "Applying IODeviceWeight=%" PRIu64 " as BlockIODeviceWeight=%" PRIu64 " for %s",
1827 w->weight, weight, w->path);
1829 cgroup_apply_blkio_device_weight(u, w->path, weight);
1831 else if (has_blockio)
1832 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
1833 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
1836 /* The bandwidth limits are something that make sense to be applied to the host's root but not container
1837 * roots, as there we want the container manager to handle it */
1838 if (is_host_root || !is_local_root) {
1839 if (has_io)
1840 LIST_FOREACH(device_limits, l, c->io_device_limits) {
1841 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax= for %s",
1842 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
1844 cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]);
1846 else if (has_blockio)
1847 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
1848 cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps);
1852 /* In unified mode 'memory' attributes do not exist on the root cgroup. In legacy mode 'memory.limit_in_bytes'
1853 * exists on the root cgroup, but any writes to it are refused with EINVAL. And if we run in a container we
1854 * want to leave control to the container manager (and if proper cgroup v2 delegation is used we couldn't even
1855 * write to this if we wanted to.) */
1856 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_local_root) {
1858 if (cg_all_unified() > 0) {
1859 uint64_t max, swap_max = CGROUP_LIMIT_MAX, zswap_max = CGROUP_LIMIT_MAX, high = CGROUP_LIMIT_MAX;
1861 if (unit_has_unified_memory_config(u)) {
1862 bool startup = IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING);
1864 high = startup && c->startup_memory_high_set ? c->startup_memory_high : c->memory_high;
1865 max = startup && c->startup_memory_max_set ? c->startup_memory_max : c->memory_max;
1866 swap_max = startup && c->startup_memory_swap_max_set ? c->startup_memory_swap_max : c->memory_swap_max;
1867 zswap_max = startup && c->startup_memory_zswap_max_set ? c->startup_memory_zswap_max : c->memory_zswap_max;
1868 } else {
1869 max = c->memory_limit;
1871 if (max != CGROUP_LIMIT_MAX)
1872 log_cgroup_compat(u, "Applying MemoryLimit=%" PRIu64 " as MemoryMax=", max);
1875 cgroup_apply_unified_memory_limit(u, "memory.min", unit_get_ancestor_memory_min(u));
1876 cgroup_apply_unified_memory_limit(u, "memory.low", unit_get_ancestor_memory_low(u));
1877 cgroup_apply_unified_memory_limit(u, "memory.high", high);
1878 cgroup_apply_unified_memory_limit(u, "memory.max", max);
1879 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
1880 cgroup_apply_unified_memory_limit(u, "memory.zswap.max", zswap_max);
1882 (void) set_attribute_and_warn(u, "memory", "memory.oom.group", one_zero(c->memory_oom_group));
1884 } else {
1885 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
1886 uint64_t val;
1888 if (unit_has_unified_memory_config(u)) {
1889 val = c->memory_max;
1890 if (val != CGROUP_LIMIT_MAX)
1891 log_cgroup_compat(u, "Applying MemoryMax=%" PRIu64 " as MemoryLimit=", val);
1892 } else
1893 val = c->memory_limit;
1895 if (val == CGROUP_LIMIT_MAX)
1896 strncpy(buf, "-1\n", sizeof(buf));
1897 else
1898 xsprintf(buf, "%" PRIu64 "\n", val);
1900 (void) set_attribute_and_warn(u, "memory", "memory.limit_in_bytes", buf);
1904 /* On cgroup v2 we can apply BPF everywhere. On cgroup v1 we apply it everywhere except for the root of
1905 * containers, where we leave this to the manager */
1906 if ((apply_mask & (CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES)) &&
1907 (is_host_root || cg_all_unified() > 0 || !is_local_root))
1908 (void) cgroup_apply_devices(u);
1910 if (apply_mask & CGROUP_MASK_PIDS) {
1912 if (is_host_root) {
1913 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1914 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1915 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1916 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1917 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1918 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1919 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1920 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1921 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1922 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1923 * which is desirable so that there's an official way to release control of the sysctl from
1924 * systemd: set the limit to unbounded and reload. */
1926 if (cgroup_tasks_max_isset(&c->tasks_max)) {
1927 u->manager->sysctl_pid_max_changed = true;
1928 r = procfs_tasks_set_limit(cgroup_tasks_max_resolve(&c->tasks_max));
1929 } else if (u->manager->sysctl_pid_max_changed)
1930 r = procfs_tasks_set_limit(TASKS_MAX);
1931 else
1932 r = 0;
1933 if (r < 0)
1934 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r,
1935 "Failed to write to tasks limit sysctls: %m");
1938 /* The attribute itself is not available on the host root cgroup, and in the container case we want to
1939 * leave it for the container manager. */
1940 if (!is_local_root) {
1941 if (cgroup_tasks_max_isset(&c->tasks_max)) {
1942 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
1944 xsprintf(buf, "%" PRIu64 "\n", cgroup_tasks_max_resolve(&c->tasks_max));
1945 (void) set_attribute_and_warn(u, "pids", "pids.max", buf);
1946 } else
1947 (void) set_attribute_and_warn(u, "pids", "pids.max", "max\n");
1951 if (apply_mask & CGROUP_MASK_BPF_FIREWALL)
1952 cgroup_apply_firewall(u);
1954 if (apply_mask & CGROUP_MASK_BPF_FOREIGN)
1955 cgroup_apply_bpf_foreign_program(u);
1957 if (apply_mask & CGROUP_MASK_BPF_SOCKET_BIND)
1958 cgroup_apply_socket_bind(u);
1960 if (apply_mask & CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES)
1961 cgroup_apply_restrict_network_interfaces(u);
1963 unit_modify_nft_set(u, /* add = */ true);
1966 static bool unit_get_needs_bpf_firewall(Unit *u) {
1967 CGroupContext *c;
1968 assert(u);
1970 c = unit_get_cgroup_context(u);
1971 if (!c)
1972 return false;
1974 if (c->ip_accounting ||
1975 !set_isempty(c->ip_address_allow) ||
1976 !set_isempty(c->ip_address_deny) ||
1977 c->ip_filters_ingress ||
1978 c->ip_filters_egress)
1979 return true;
1981 /* If any parent slice has an IP access list defined, it applies too */
1982 for (Unit *p = UNIT_GET_SLICE(u); p; p = UNIT_GET_SLICE(p)) {
1983 c = unit_get_cgroup_context(p);
1984 if (!c)
1985 return false;
1987 if (!set_isempty(c->ip_address_allow) ||
1988 !set_isempty(c->ip_address_deny))
1989 return true;
1992 return false;
1995 static bool unit_get_needs_bpf_foreign_program(Unit *u) {
1996 CGroupContext *c;
1997 assert(u);
1999 c = unit_get_cgroup_context(u);
2000 if (!c)
2001 return false;
2003 return !!c->bpf_foreign_programs;
2006 static bool unit_get_needs_socket_bind(Unit *u) {
2007 CGroupContext *c;
2008 assert(u);
2010 c = unit_get_cgroup_context(u);
2011 if (!c)
2012 return false;
2014 return c->socket_bind_allow || c->socket_bind_deny;
2017 static bool unit_get_needs_restrict_network_interfaces(Unit *u) {
2018 CGroupContext *c;
2019 assert(u);
2021 c = unit_get_cgroup_context(u);
2022 if (!c)
2023 return false;
2025 return !set_isempty(c->restrict_network_interfaces);
2028 static CGroupMask unit_get_cgroup_mask(Unit *u) {
2029 CGroupMask mask = 0;
2030 CGroupContext *c;
2032 assert(u);
2034 assert_se(c = unit_get_cgroup_context(u));
2036 /* Figure out which controllers we need, based on the cgroup context object */
2038 if (c->cpu_accounting)
2039 mask |= get_cpu_accounting_mask();
2041 if (cgroup_context_has_cpu_weight(c) ||
2042 cgroup_context_has_cpu_shares(c) ||
2043 c->cpu_quota_per_sec_usec != USEC_INFINITY)
2044 mask |= CGROUP_MASK_CPU;
2046 if (cgroup_context_has_allowed_cpus(c) || cgroup_context_has_allowed_mems(c))
2047 mask |= CGROUP_MASK_CPUSET;
2049 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
2050 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
2052 if (c->memory_accounting ||
2053 c->memory_limit != CGROUP_LIMIT_MAX ||
2054 unit_has_unified_memory_config(u))
2055 mask |= CGROUP_MASK_MEMORY;
2057 if (c->device_allow ||
2058 c->device_policy != CGROUP_DEVICE_POLICY_AUTO)
2059 mask |= CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES;
2061 if (c->tasks_accounting ||
2062 cgroup_tasks_max_isset(&c->tasks_max))
2063 mask |= CGROUP_MASK_PIDS;
2065 return CGROUP_MASK_EXTEND_JOINED(mask);
2068 static CGroupMask unit_get_bpf_mask(Unit *u) {
2069 CGroupMask mask = 0;
2071 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
2072 * too. */
2074 if (unit_get_needs_bpf_firewall(u))
2075 mask |= CGROUP_MASK_BPF_FIREWALL;
2077 if (unit_get_needs_bpf_foreign_program(u))
2078 mask |= CGROUP_MASK_BPF_FOREIGN;
2080 if (unit_get_needs_socket_bind(u))
2081 mask |= CGROUP_MASK_BPF_SOCKET_BIND;
2083 if (unit_get_needs_restrict_network_interfaces(u))
2084 mask |= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES;
2086 return mask;
2089 CGroupMask unit_get_own_mask(Unit *u) {
2090 CGroupContext *c;
2092 /* Returns the mask of controllers the unit needs for itself. If a unit is not properly loaded, return an empty
2093 * mask, as we shouldn't reflect it in the cgroup hierarchy then. */
2095 if (u->load_state != UNIT_LOADED)
2096 return 0;
2098 c = unit_get_cgroup_context(u);
2099 if (!c)
2100 return 0;
2102 return unit_get_cgroup_mask(u) | unit_get_bpf_mask(u) | unit_get_delegate_mask(u);
2105 CGroupMask unit_get_delegate_mask(Unit *u) {
2106 CGroupContext *c;
2108 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
2109 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
2111 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
2113 if (!unit_cgroup_delegate(u))
2114 return 0;
2116 if (cg_all_unified() <= 0) {
2117 ExecContext *e;
2119 e = unit_get_exec_context(u);
2120 if (e && !exec_context_maintains_privileges(e))
2121 return 0;
2124 assert_se(c = unit_get_cgroup_context(u));
2125 return CGROUP_MASK_EXTEND_JOINED(c->delegate_controllers);
2128 static CGroupMask unit_get_subtree_mask(Unit *u) {
2130 /* Returns the mask of this subtree, meaning of the group
2131 * itself and its children. */
2133 return unit_get_own_mask(u) | unit_get_members_mask(u);
2136 CGroupMask unit_get_members_mask(Unit *u) {
2137 assert(u);
2139 /* Returns the mask of controllers all of the unit's children require, merged */
2141 if (u->cgroup_members_mask_valid)
2142 return u->cgroup_members_mask; /* Use cached value if possible */
2144 u->cgroup_members_mask = 0;
2146 if (u->type == UNIT_SLICE) {
2147 Unit *member;
2149 UNIT_FOREACH_DEPENDENCY(member, u, UNIT_ATOM_SLICE_OF)
2150 u->cgroup_members_mask |= unit_get_subtree_mask(member); /* note that this calls ourselves again, for the children */
2153 u->cgroup_members_mask_valid = true;
2154 return u->cgroup_members_mask;
2157 CGroupMask unit_get_siblings_mask(Unit *u) {
2158 Unit *slice;
2159 assert(u);
2161 /* Returns the mask of controllers all of the unit's siblings
2162 * require, i.e. the members mask of the unit's parent slice
2163 * if there is one. */
2165 slice = UNIT_GET_SLICE(u);
2166 if (slice)
2167 return unit_get_members_mask(slice);
2169 return unit_get_subtree_mask(u); /* we are the top-level slice */
2172 static CGroupMask unit_get_disable_mask(Unit *u) {
2173 CGroupContext *c;
2175 c = unit_get_cgroup_context(u);
2176 if (!c)
2177 return 0;
2179 return c->disable_controllers;
2182 CGroupMask unit_get_ancestor_disable_mask(Unit *u) {
2183 CGroupMask mask;
2184 Unit *slice;
2186 assert(u);
2187 mask = unit_get_disable_mask(u);
2189 /* Returns the mask of controllers which are marked as forcibly
2190 * disabled in any ancestor unit or the unit in question. */
2192 slice = UNIT_GET_SLICE(u);
2193 if (slice)
2194 mask |= unit_get_ancestor_disable_mask(slice);
2196 return mask;
2199 CGroupMask unit_get_target_mask(Unit *u) {
2200 CGroupMask own_mask, mask;
2202 /* This returns the cgroup mask of all controllers to enable for a specific cgroup, i.e. everything
2203 * it needs itself, plus all that its children need, plus all that its siblings need. This is
2204 * primarily useful on the legacy cgroup hierarchy, where we need to duplicate each cgroup in each
2205 * hierarchy that shall be enabled for it. */
2207 own_mask = unit_get_own_mask(u);
2209 if (own_mask & CGROUP_MASK_BPF_FIREWALL & ~u->manager->cgroup_supported)
2210 emit_bpf_firewall_warning(u);
2212 mask = own_mask | unit_get_members_mask(u) | unit_get_siblings_mask(u);
2214 mask &= u->manager->cgroup_supported;
2215 mask &= ~unit_get_ancestor_disable_mask(u);
2217 return mask;
2220 CGroupMask unit_get_enable_mask(Unit *u) {
2221 CGroupMask mask;
2223 /* This returns the cgroup mask of all controllers to enable
2224 * for the children of a specific cgroup. This is primarily
2225 * useful for the unified cgroup hierarchy, where each cgroup
2226 * controls which controllers are enabled for its children. */
2228 mask = unit_get_members_mask(u);
2229 mask &= u->manager->cgroup_supported;
2230 mask &= ~unit_get_ancestor_disable_mask(u);
2232 return mask;
2235 void unit_invalidate_cgroup_members_masks(Unit *u) {
2236 Unit *slice;
2238 assert(u);
2240 /* Recurse invalidate the member masks cache all the way up the tree */
2241 u->cgroup_members_mask_valid = false;
2243 slice = UNIT_GET_SLICE(u);
2244 if (slice)
2245 unit_invalidate_cgroup_members_masks(slice);
2248 const char *unit_get_realized_cgroup_path(Unit *u, CGroupMask mask) {
2250 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
2252 while (u) {
2254 if (u->cgroup_path &&
2255 u->cgroup_realized &&
2256 FLAGS_SET(u->cgroup_realized_mask, mask))
2257 return u->cgroup_path;
2259 u = UNIT_GET_SLICE(u);
2262 return NULL;
2265 static const char *migrate_callback(CGroupMask mask, void *userdata) {
2266 /* If not realized at all, migrate to root ("").
2267 * It may happen if we're upgrading from older version that didn't clean up.
2269 return strempty(unit_get_realized_cgroup_path(userdata, mask));
2272 int unit_default_cgroup_path(const Unit *u, char **ret) {
2273 _cleanup_free_ char *p = NULL;
2274 int r;
2276 assert(u);
2277 assert(ret);
2279 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
2280 p = strdup(u->manager->cgroup_root);
2281 else {
2282 _cleanup_free_ char *escaped = NULL, *slice_path = NULL;
2283 Unit *slice;
2285 slice = UNIT_GET_SLICE(u);
2286 if (slice && !unit_has_name(slice, SPECIAL_ROOT_SLICE)) {
2287 r = cg_slice_to_path(slice->id, &slice_path);
2288 if (r < 0)
2289 return r;
2292 r = cg_escape(u->id, &escaped);
2293 if (r < 0)
2294 return r;
2296 p = path_join(empty_to_root(u->manager->cgroup_root), slice_path, escaped);
2298 if (!p)
2299 return -ENOMEM;
2301 *ret = TAKE_PTR(p);
2302 return 0;
2305 int unit_set_cgroup_path(Unit *u, const char *path) {
2306 _cleanup_free_ char *p = NULL;
2307 int r;
2309 assert(u);
2311 if (streq_ptr(u->cgroup_path, path))
2312 return 0;
2314 if (path) {
2315 p = strdup(path);
2316 if (!p)
2317 return -ENOMEM;
2320 if (p) {
2321 r = hashmap_put(u->manager->cgroup_unit, p, u);
2322 if (r < 0)
2323 return r;
2326 unit_release_cgroup(u);
2327 u->cgroup_path = TAKE_PTR(p);
2329 return 1;
2332 int unit_watch_cgroup(Unit *u) {
2333 _cleanup_free_ char *events = NULL;
2334 int r;
2336 assert(u);
2338 /* Watches the "cgroups.events" attribute of this unit's cgroup for "empty" events, but only if
2339 * cgroupv2 is available. */
2341 if (!u->cgroup_path)
2342 return 0;
2344 if (u->cgroup_control_inotify_wd >= 0)
2345 return 0;
2347 /* Only applies to the unified hierarchy */
2348 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2349 if (r < 0)
2350 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
2351 if (r == 0)
2352 return 0;
2354 /* No point in watch the top-level slice, it's never going to run empty. */
2355 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
2356 return 0;
2358 r = hashmap_ensure_allocated(&u->manager->cgroup_control_inotify_wd_unit, &trivial_hash_ops);
2359 if (r < 0)
2360 return log_oom();
2362 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
2363 if (r < 0)
2364 return log_oom();
2366 u->cgroup_control_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
2367 if (u->cgroup_control_inotify_wd < 0) {
2369 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
2370 * is not an error */
2371 return 0;
2373 return log_unit_error_errno(u, errno, "Failed to add control inotify watch descriptor for control group %s: %m", empty_to_root(u->cgroup_path));
2376 r = hashmap_put(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd), u);
2377 if (r < 0)
2378 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(u->cgroup_path));
2380 return 0;
2383 int unit_watch_cgroup_memory(Unit *u) {
2384 _cleanup_free_ char *events = NULL;
2385 CGroupContext *c;
2386 int r;
2388 assert(u);
2390 /* Watches the "memory.events" attribute of this unit's cgroup for "oom_kill" events, but only if
2391 * cgroupv2 is available. */
2393 if (!u->cgroup_path)
2394 return 0;
2396 c = unit_get_cgroup_context(u);
2397 if (!c)
2398 return 0;
2400 /* The "memory.events" attribute is only available if the memory controller is on. Let's hence tie
2401 * this to memory accounting, in a way watching for OOM kills is a form of memory accounting after
2402 * all. */
2403 if (!c->memory_accounting)
2404 return 0;
2406 /* Don't watch inner nodes, as the kernel doesn't report oom_kill events recursively currently, and
2407 * we also don't want to generate a log message for each parent cgroup of a process. */
2408 if (u->type == UNIT_SLICE)
2409 return 0;
2411 if (u->cgroup_memory_inotify_wd >= 0)
2412 return 0;
2414 /* Only applies to the unified hierarchy */
2415 r = cg_all_unified();
2416 if (r < 0)
2417 return log_error_errno(r, "Failed to determine whether the memory controller is unified: %m");
2418 if (r == 0)
2419 return 0;
2421 r = hashmap_ensure_allocated(&u->manager->cgroup_memory_inotify_wd_unit, &trivial_hash_ops);
2422 if (r < 0)
2423 return log_oom();
2425 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "memory.events", &events);
2426 if (r < 0)
2427 return log_oom();
2429 u->cgroup_memory_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
2430 if (u->cgroup_memory_inotify_wd < 0) {
2432 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
2433 * is not an error */
2434 return 0;
2436 return log_unit_error_errno(u, errno, "Failed to add memory inotify watch descriptor for control group %s: %m", empty_to_root(u->cgroup_path));
2439 r = hashmap_put(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd), u);
2440 if (r < 0)
2441 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(u->cgroup_path));
2443 return 0;
2446 int unit_pick_cgroup_path(Unit *u) {
2447 _cleanup_free_ char *path = NULL;
2448 int r;
2450 assert(u);
2452 if (u->cgroup_path)
2453 return 0;
2455 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2456 return -EINVAL;
2458 r = unit_default_cgroup_path(u, &path);
2459 if (r < 0)
2460 return log_unit_error_errno(u, r, "Failed to generate default cgroup path: %m");
2462 r = unit_set_cgroup_path(u, path);
2463 if (r == -EEXIST)
2464 return log_unit_error_errno(u, r, "Control group %s exists already.", empty_to_root(path));
2465 if (r < 0)
2466 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", empty_to_root(path));
2468 return 0;
2471 static int unit_update_cgroup(
2472 Unit *u,
2473 CGroupMask target_mask,
2474 CGroupMask enable_mask,
2475 ManagerState state) {
2477 bool created, is_root_slice;
2478 CGroupMask migrate_mask = 0;
2479 _cleanup_free_ char *cgroup_full_path = NULL;
2480 int r;
2482 assert(u);
2484 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2485 return 0;
2487 /* Figure out our cgroup path */
2488 r = unit_pick_cgroup_path(u);
2489 if (r < 0)
2490 return r;
2492 /* First, create our own group */
2493 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
2494 if (r < 0)
2495 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", empty_to_root(u->cgroup_path));
2496 created = r;
2498 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
2499 uint64_t cgroup_id = 0;
2501 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, NULL, &cgroup_full_path);
2502 if (r == 0) {
2503 r = cg_path_get_cgroupid(cgroup_full_path, &cgroup_id);
2504 if (r < 0)
2505 log_unit_full_errno(u, ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
2506 "Failed to get cgroup ID of cgroup %s, ignoring: %m", cgroup_full_path);
2507 } else
2508 log_unit_warning_errno(u, r, "Failed to get full cgroup path on cgroup %s, ignoring: %m", empty_to_root(u->cgroup_path));
2510 u->cgroup_id = cgroup_id;
2513 /* Start watching it */
2514 (void) unit_watch_cgroup(u);
2515 (void) unit_watch_cgroup_memory(u);
2517 /* For v2 we preserve enabled controllers in delegated units, adjust others,
2518 * for v1 we figure out which controller hierarchies need migration. */
2519 if (created || !u->cgroup_realized || !unit_cgroup_delegate(u)) {
2520 CGroupMask result_mask = 0;
2522 /* Enable all controllers we need */
2523 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path, &result_mask);
2524 if (r < 0)
2525 log_unit_warning_errno(u, r, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", empty_to_root(u->cgroup_path));
2527 /* Remember what's actually enabled now */
2528 u->cgroup_enabled_mask = result_mask;
2530 migrate_mask = u->cgroup_realized_mask ^ target_mask;
2533 /* Keep track that this is now realized */
2534 u->cgroup_realized = true;
2535 u->cgroup_realized_mask = target_mask;
2537 /* Migrate processes in controller hierarchies both downwards (enabling) and upwards (disabling).
2539 * Unnecessary controller cgroups are trimmed (after emptied by upward migration).
2540 * We perform migration also with whole slices for cases when users don't care about leave
2541 * granularity. Since delegated_mask is subset of target mask, we won't trim slice subtree containing
2542 * delegated units.
2544 if (cg_all_unified() == 0) {
2545 r = cg_migrate_v1_controllers(u->manager->cgroup_supported, migrate_mask, u->cgroup_path, migrate_callback, u);
2546 if (r < 0)
2547 log_unit_warning_errno(u, r, "Failed to migrate controller cgroups from %s, ignoring: %m", empty_to_root(u->cgroup_path));
2549 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
2550 r = cg_trim_v1_controllers(u->manager->cgroup_supported, ~target_mask, u->cgroup_path, !is_root_slice);
2551 if (r < 0)
2552 log_unit_warning_errno(u, r, "Failed to delete controller cgroups %s, ignoring: %m", empty_to_root(u->cgroup_path));
2555 /* Set attributes */
2556 cgroup_context_apply(u, target_mask, state);
2557 cgroup_xattr_apply(u);
2559 /* For most units we expect that memory monitoring is set up before the unit is started and we won't
2560 * touch it after. For PID 1 this is different though, because we couldn't possibly do that given
2561 * that PID 1 runs before init.scope is even set up. Hence, whenever init.scope is realized, let's
2562 * try to open the memory pressure interface anew. */
2563 if (unit_has_name(u, SPECIAL_INIT_SCOPE))
2564 (void) manager_setup_memory_pressure_event_source(u->manager);
2566 return 0;
2569 static int unit_attach_pid_to_cgroup_via_bus(Unit *u, pid_t pid, const char *suffix_path) {
2570 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2571 char *pp;
2572 int r;
2574 assert(u);
2576 if (MANAGER_IS_SYSTEM(u->manager))
2577 return -EINVAL;
2579 if (!u->manager->system_bus)
2580 return -EIO;
2582 if (!u->cgroup_path)
2583 return -EINVAL;
2585 /* Determine this unit's cgroup path relative to our cgroup root */
2586 pp = path_startswith(u->cgroup_path, u->manager->cgroup_root);
2587 if (!pp)
2588 return -EINVAL;
2590 pp = strjoina("/", pp, suffix_path);
2591 path_simplify(pp);
2593 r = bus_call_method(u->manager->system_bus,
2594 bus_systemd_mgr,
2595 "AttachProcessesToUnit",
2596 &error, NULL,
2597 "ssau",
2598 NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
2599 if (r < 0)
2600 return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
2602 return 0;
2605 int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
2606 _cleanup_free_ char *joined = NULL;
2607 CGroupMask delegated_mask;
2608 const char *p;
2609 PidRef *pid;
2610 int ret, r;
2612 assert(u);
2614 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2615 return -EINVAL;
2617 if (set_isempty(pids))
2618 return 0;
2620 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
2621 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
2622 r = bpf_firewall_load_custom(u);
2623 if (r < 0)
2624 return r;
2626 r = unit_realize_cgroup(u);
2627 if (r < 0)
2628 return r;
2630 if (isempty(suffix_path))
2631 p = u->cgroup_path;
2632 else {
2633 joined = path_join(u->cgroup_path, suffix_path);
2634 if (!joined)
2635 return -ENOMEM;
2637 p = joined;
2640 delegated_mask = unit_get_delegate_mask(u);
2642 ret = 0;
2643 SET_FOREACH(pid, pids) {
2645 /* Unfortunately we cannot add pids by pidfd to a cgroup. Hence we have to use PIDs instead,
2646 * which of course is racy. Let's shorten the race a bit though, and re-validate the PID
2647 * before we use it */
2648 r = pidref_verify(pid);
2649 if (r < 0) {
2650 log_unit_info_errno(u, r, "PID " PID_FMT " vanished before we could move it to target cgroup '%s', skipping: %m", pid->pid, empty_to_root(p));
2651 continue;
2654 /* First, attach the PID to the main cgroup hierarchy */
2655 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, p, pid->pid);
2656 if (r < 0) {
2657 bool again = MANAGER_IS_USER(u->manager) && ERRNO_IS_PRIVILEGE(r);
2659 log_unit_full_errno(u, again ? LOG_DEBUG : LOG_INFO, r,
2660 "Couldn't move process "PID_FMT" to%s requested cgroup '%s': %m",
2661 pid->pid, again ? " directly" : "", empty_to_root(p));
2663 if (again) {
2664 int z;
2666 /* If we are in a user instance, and we can't move the process ourselves due
2667 * to permission problems, let's ask the system instance about it instead.
2668 * Since it's more privileged it might be able to move the process across the
2669 * leaves of a subtree whose top node is not owned by us. */
2671 z = unit_attach_pid_to_cgroup_via_bus(u, pid->pid, suffix_path);
2672 if (z < 0)
2673 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, empty_to_root(p));
2674 else {
2675 if (ret >= 0)
2676 ret++; /* Count successful additions */
2677 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
2681 if (ret >= 0)
2682 ret = r; /* Remember first error */
2684 continue;
2685 } else if (ret >= 0)
2686 ret++; /* Count successful additions */
2688 r = cg_all_unified();
2689 if (r < 0)
2690 return r;
2691 if (r > 0)
2692 continue;
2694 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
2695 * innermost realized one */
2697 for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2698 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2699 const char *realized;
2701 if (!(u->manager->cgroup_supported & bit))
2702 continue;
2704 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
2705 if (delegated_mask & u->cgroup_realized_mask & bit) {
2706 r = cg_attach(cgroup_controller_to_string(c), p, pid->pid);
2707 if (r >= 0)
2708 continue; /* Success! */
2710 log_unit_debug_errno(u, r, "Failed to attach PID " PID_FMT " to requested cgroup %s in controller %s, falling back to unit's cgroup: %m",
2711 pid->pid, empty_to_root(p), cgroup_controller_to_string(c));
2714 /* So this controller is either not delegate or realized, or something else weird happened. In
2715 * that case let's attach the PID at least to the closest cgroup up the tree that is
2716 * realized. */
2717 realized = unit_get_realized_cgroup_path(u, bit);
2718 if (!realized)
2719 continue; /* Not even realized in the root slice? Then let's not bother */
2721 r = cg_attach(cgroup_controller_to_string(c), realized, pid->pid);
2722 if (r < 0)
2723 log_unit_debug_errno(u, r, "Failed to attach PID " PID_FMT " to realized cgroup %s in controller %s, ignoring: %m",
2724 pid->pid, realized, cgroup_controller_to_string(c));
2728 return ret;
2731 static bool unit_has_mask_realized(
2732 Unit *u,
2733 CGroupMask target_mask,
2734 CGroupMask enable_mask) {
2736 assert(u);
2738 /* Returns true if this unit is fully realized. We check four things:
2740 * 1. Whether the cgroup was created at all
2741 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
2742 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
2743 * 4. Whether the invalidation mask is currently zero
2745 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
2746 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
2747 * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
2748 * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
2749 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
2750 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
2751 * simply don't matter. */
2753 return u->cgroup_realized &&
2754 ((u->cgroup_realized_mask ^ target_mask) & CGROUP_MASK_V1) == 0 &&
2755 ((u->cgroup_enabled_mask ^ enable_mask) & CGROUP_MASK_V2) == 0 &&
2756 u->cgroup_invalidated_mask == 0;
2759 static bool unit_has_mask_disables_realized(
2760 Unit *u,
2761 CGroupMask target_mask,
2762 CGroupMask enable_mask) {
2764 assert(u);
2766 /* Returns true if all controllers which should be disabled are indeed disabled.
2768 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
2769 * already removed. */
2771 return !u->cgroup_realized ||
2772 (FLAGS_SET(u->cgroup_realized_mask, target_mask & CGROUP_MASK_V1) &&
2773 FLAGS_SET(u->cgroup_enabled_mask, enable_mask & CGROUP_MASK_V2));
2776 static bool unit_has_mask_enables_realized(
2777 Unit *u,
2778 CGroupMask target_mask,
2779 CGroupMask enable_mask) {
2781 assert(u);
2783 /* Returns true if all controllers which should be enabled are indeed enabled.
2785 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
2786 * we want to add is already added. */
2788 return u->cgroup_realized &&
2789 ((u->cgroup_realized_mask | target_mask) & CGROUP_MASK_V1) == (u->cgroup_realized_mask & CGROUP_MASK_V1) &&
2790 ((u->cgroup_enabled_mask | enable_mask) & CGROUP_MASK_V2) == (u->cgroup_enabled_mask & CGROUP_MASK_V2);
2793 void unit_add_to_cgroup_realize_queue(Unit *u) {
2794 assert(u);
2796 if (u->in_cgroup_realize_queue)
2797 return;
2799 LIST_APPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2800 u->in_cgroup_realize_queue = true;
2803 static void unit_remove_from_cgroup_realize_queue(Unit *u) {
2804 assert(u);
2806 if (!u->in_cgroup_realize_queue)
2807 return;
2809 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2810 u->in_cgroup_realize_queue = false;
2813 /* Controllers can only be enabled breadth-first, from the root of the
2814 * hierarchy downwards to the unit in question. */
2815 static int unit_realize_cgroup_now_enable(Unit *u, ManagerState state) {
2816 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2817 Unit *slice;
2818 int r;
2820 assert(u);
2822 /* First go deal with this unit's parent, or we won't be able to enable
2823 * any new controllers at this layer. */
2824 slice = UNIT_GET_SLICE(u);
2825 if (slice) {
2826 r = unit_realize_cgroup_now_enable(slice, state);
2827 if (r < 0)
2828 return r;
2831 target_mask = unit_get_target_mask(u);
2832 enable_mask = unit_get_enable_mask(u);
2834 /* We can only enable in this direction, don't try to disable anything.
2836 if (unit_has_mask_enables_realized(u, target_mask, enable_mask))
2837 return 0;
2839 new_target_mask = u->cgroup_realized_mask | target_mask;
2840 new_enable_mask = u->cgroup_enabled_mask | enable_mask;
2842 return unit_update_cgroup(u, new_target_mask, new_enable_mask, state);
2845 /* Controllers can only be disabled depth-first, from the leaves of the
2846 * hierarchy upwards to the unit in question. */
2847 static int unit_realize_cgroup_now_disable(Unit *u, ManagerState state) {
2848 Unit *m;
2850 assert(u);
2852 if (u->type != UNIT_SLICE)
2853 return 0;
2855 UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
2856 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2857 int r;
2859 /* The cgroup for this unit might not actually be fully realised yet, in which case it isn't
2860 * holding any controllers open anyway. */
2861 if (!m->cgroup_realized)
2862 continue;
2864 /* We must disable those below us first in order to release the controller. */
2865 if (m->type == UNIT_SLICE)
2866 (void) unit_realize_cgroup_now_disable(m, state);
2868 target_mask = unit_get_target_mask(m);
2869 enable_mask = unit_get_enable_mask(m);
2871 /* We can only disable in this direction, don't try to enable anything. */
2872 if (unit_has_mask_disables_realized(m, target_mask, enable_mask))
2873 continue;
2875 new_target_mask = m->cgroup_realized_mask & target_mask;
2876 new_enable_mask = m->cgroup_enabled_mask & enable_mask;
2878 r = unit_update_cgroup(m, new_target_mask, new_enable_mask, state);
2879 if (r < 0)
2880 return r;
2883 return 0;
2886 /* Check if necessary controllers and attributes for a unit are in place.
2888 * - If so, do nothing.
2889 * - If not, create paths, move processes over, and set attributes.
2891 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
2892 * a depth-first way. As such the process looks like this:
2894 * Suppose we have a cgroup hierarchy which looks like this:
2896 * root
2897 * / \
2898 * / \
2899 * / \
2900 * a b
2901 * / \ / \
2902 * / \ / \
2903 * c d e f
2904 * / \ / \ / \ / \
2905 * h i j k l m n o
2907 * 1. We want to realise cgroup "d" now.
2908 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
2909 * 3. cgroup "k" just started requesting the memory controller.
2911 * To make this work we must do the following in order:
2913 * 1. Disable CPU controller in k, j
2914 * 2. Disable CPU controller in d
2915 * 3. Enable memory controller in root
2916 * 4. Enable memory controller in a
2917 * 5. Enable memory controller in d
2918 * 6. Enable memory controller in k
2920 * Notice that we need to touch j in one direction, but not the other. We also
2921 * don't go beyond d when disabling -- it's up to "a" to get realized if it
2922 * wants to disable further. The basic rules are therefore:
2924 * - If you're disabling something, you need to realise all of the cgroups from
2925 * your recursive descendants to the root. This starts from the leaves.
2926 * - If you're enabling something, you need to realise from the root cgroup
2927 * downwards, but you don't need to iterate your recursive descendants.
2929 * Returns 0 on success and < 0 on failure. */
2930 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
2931 CGroupMask target_mask, enable_mask;
2932 Unit *slice;
2933 int r;
2935 assert(u);
2937 unit_remove_from_cgroup_realize_queue(u);
2939 target_mask = unit_get_target_mask(u);
2940 enable_mask = unit_get_enable_mask(u);
2942 if (unit_has_mask_realized(u, target_mask, enable_mask))
2943 return 0;
2945 /* Disable controllers below us, if there are any */
2946 r = unit_realize_cgroup_now_disable(u, state);
2947 if (r < 0)
2948 return r;
2950 /* Enable controllers above us, if there are any */
2951 slice = UNIT_GET_SLICE(u);
2952 if (slice) {
2953 r = unit_realize_cgroup_now_enable(slice, state);
2954 if (r < 0)
2955 return r;
2958 /* Now actually deal with the cgroup we were trying to realise and set attributes */
2959 r = unit_update_cgroup(u, target_mask, enable_mask, state);
2960 if (r < 0)
2961 return r;
2963 /* Now, reset the invalidation mask */
2964 u->cgroup_invalidated_mask = 0;
2965 return 0;
2968 unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
2969 ManagerState state;
2970 unsigned n = 0;
2971 Unit *i;
2972 int r;
2974 assert(m);
2976 state = manager_state(m);
2978 while ((i = m->cgroup_realize_queue)) {
2979 assert(i->in_cgroup_realize_queue);
2981 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
2982 /* Maybe things changed, and the unit is not actually active anymore? */
2983 unit_remove_from_cgroup_realize_queue(i);
2984 continue;
2987 r = unit_realize_cgroup_now(i, state);
2988 if (r < 0)
2989 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
2991 n++;
2994 return n;
2997 void unit_add_family_to_cgroup_realize_queue(Unit *u) {
2998 assert(u);
2999 assert(u->type == UNIT_SLICE);
3001 /* Family of a unit for is defined as (immediate) children of the unit and immediate children of all
3002 * its ancestors.
3004 * Ideally we would enqueue ancestor path only (bottom up). However, on cgroup-v1 scheduling becomes
3005 * very weird if two units that own processes reside in the same slice, but one is realized in the
3006 * "cpu" hierarchy and one is not (for example because one has CPUWeight= set and the other does
3007 * not), because that means individual processes need to be scheduled against whole cgroups. Let's
3008 * avoid this asymmetry by always ensuring that siblings of a unit are always realized in their v1
3009 * controller hierarchies too (if unit requires the controller to be realized).
3011 * The function must invalidate cgroup_members_mask of all ancestors in order to calculate up to date
3012 * masks. */
3014 do {
3015 Unit *m;
3017 /* Children of u likely changed when we're called */
3018 u->cgroup_members_mask_valid = false;
3020 UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
3022 /* No point in doing cgroup application for units without active processes. */
3023 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
3024 continue;
3026 /* We only enqueue siblings if they were realized once at least, in the main
3027 * hierarchy. */
3028 if (!m->cgroup_realized)
3029 continue;
3031 /* If the unit doesn't need any new controllers and has current ones
3032 * realized, it doesn't need any changes. */
3033 if (unit_has_mask_realized(m,
3034 unit_get_target_mask(m),
3035 unit_get_enable_mask(m)))
3036 continue;
3038 unit_add_to_cgroup_realize_queue(m);
3041 /* Parent comes after children */
3042 unit_add_to_cgroup_realize_queue(u);
3044 u = UNIT_GET_SLICE(u);
3045 } while (u);
3048 int unit_realize_cgroup(Unit *u) {
3049 Unit *slice;
3051 assert(u);
3053 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3054 return 0;
3056 /* So, here's the deal: when realizing the cgroups for this unit, we need to first create all
3057 * parents, but there's more actually: for the weight-based controllers we also need to make sure
3058 * that all our siblings (i.e. units that are in the same slice as we are) have cgroups, too. On the
3059 * other hand, when a controller is removed from realized set, it may become unnecessary in siblings
3060 * and ancestors and they should be (de)realized too.
3062 * This call will defer work on the siblings and derealized ancestors to the next event loop
3063 * iteration and synchronously creates the parent cgroups (unit_realize_cgroup_now). */
3065 slice = UNIT_GET_SLICE(u);
3066 if (slice)
3067 unit_add_family_to_cgroup_realize_queue(slice);
3069 /* And realize this one now (and apply the values) */
3070 return unit_realize_cgroup_now(u, manager_state(u->manager));
3073 void unit_release_cgroup(Unit *u) {
3074 assert(u);
3076 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
3077 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
3079 if (u->cgroup_path) {
3080 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
3081 u->cgroup_path = mfree(u->cgroup_path);
3084 if (u->cgroup_control_inotify_wd >= 0) {
3085 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_control_inotify_wd) < 0)
3086 log_unit_debug_errno(u, errno, "Failed to remove cgroup control inotify watch %i for %s, ignoring: %m", u->cgroup_control_inotify_wd, u->id);
3088 (void) hashmap_remove(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd));
3089 u->cgroup_control_inotify_wd = -1;
3092 if (u->cgroup_memory_inotify_wd >= 0) {
3093 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_memory_inotify_wd) < 0)
3094 log_unit_debug_errno(u, errno, "Failed to remove cgroup memory inotify watch %i for %s, ignoring: %m", u->cgroup_memory_inotify_wd, u->id);
3096 (void) hashmap_remove(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd));
3097 u->cgroup_memory_inotify_wd = -1;
3101 bool unit_maybe_release_cgroup(Unit *u) {
3102 int r;
3104 assert(u);
3106 if (!u->cgroup_path)
3107 return true;
3109 /* Don't release the cgroup if there are still processes under it. If we get notified later when all the
3110 * processes exit (e.g. the processes were in D-state and exited after the unit was marked as failed)
3111 * we need the cgroup paths to continue to be tracked by the manager so they can be looked up and cleaned
3112 * up later. */
3113 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
3114 if (r < 0)
3115 log_unit_debug_errno(u, r, "Error checking if the cgroup is recursively empty, ignoring: %m");
3116 else if (r == 1) {
3117 unit_release_cgroup(u);
3118 return true;
3121 return false;
3124 void unit_prune_cgroup(Unit *u) {
3125 int r;
3126 bool is_root_slice;
3128 assert(u);
3130 /* Removes the cgroup, if empty and possible, and stops watching it. */
3132 if (!u->cgroup_path)
3133 return;
3135 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
3137 #if BPF_FRAMEWORK
3138 (void) lsm_bpf_cleanup(u); /* Remove cgroup from the global LSM BPF map */
3139 #endif
3141 unit_modify_nft_set(u, /* add = */ false);
3143 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
3145 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
3146 if (r < 0)
3147 /* One reason we could have failed here is, that the cgroup still contains a process.
3148 * However, if the cgroup becomes removable at a later time, it might be removed when
3149 * the containing slice is stopped. So even if we failed now, this unit shouldn't assume
3150 * that the cgroup is still realized the next time it is started. Do not return early
3151 * on error, continue cleanup. */
3152 log_unit_full_errno(u, r == -EBUSY ? LOG_DEBUG : LOG_WARNING, r, "Failed to destroy cgroup %s, ignoring: %m", empty_to_root(u->cgroup_path));
3154 if (is_root_slice)
3155 return;
3157 if (!unit_maybe_release_cgroup(u)) /* Returns true if the cgroup was released */
3158 return;
3160 u->cgroup_realized = false;
3161 u->cgroup_realized_mask = 0;
3162 u->cgroup_enabled_mask = 0;
3164 u->bpf_device_control_installed = bpf_program_free(u->bpf_device_control_installed);
3167 int unit_search_main_pid(Unit *u, PidRef *ret) {
3168 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
3169 _cleanup_fclose_ FILE *f = NULL;
3170 int r;
3172 assert(u);
3173 assert(ret);
3175 if (!u->cgroup_path)
3176 return -ENXIO;
3178 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
3179 if (r < 0)
3180 return r;
3182 for (;;) {
3183 _cleanup_(pidref_done) PidRef npidref = PIDREF_NULL;
3185 /* cg_read_pidref() will return an error on unmapped PIDs.
3186 * We can't reasonably deal with units that contain those. */
3187 r = cg_read_pidref(f, &npidref, CGROUP_DONT_SKIP_UNMAPPED);
3188 if (r < 0)
3189 return r;
3190 if (r == 0)
3191 break;
3193 if (pidref_equal(&pidref, &npidref)) /* seen already, cgroupfs reports duplicates! */
3194 continue;
3196 if (pidref_is_my_child(&npidref) <= 0) /* ignore processes further down the tree */
3197 continue;
3199 if (pidref_is_set(&pidref) != 0)
3200 /* Dang, there's more than one daemonized PID in this group, so we don't know what
3201 * process is the main process. */
3202 return -ENODATA;
3204 pidref = TAKE_PIDREF(npidref);
3207 if (!pidref_is_set(&pidref))
3208 return -ENODATA;
3210 *ret = TAKE_PIDREF(pidref);
3211 return 0;
3214 static int unit_watch_pids_in_path(Unit *u, const char *path) {
3215 _cleanup_closedir_ DIR *d = NULL;
3216 _cleanup_fclose_ FILE *f = NULL;
3217 int ret = 0, r;
3219 assert(u);
3220 assert(path);
3222 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
3223 if (r < 0)
3224 RET_GATHER(ret, r);
3225 else {
3226 for (;;) {
3227 _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
3229 r = cg_read_pidref(f, &pid, /* flags = */ 0);
3230 if (r == 0)
3231 break;
3232 if (r < 0) {
3233 RET_GATHER(ret, r);
3234 break;
3237 RET_GATHER(ret, unit_watch_pidref(u, &pid, /* exclusive= */ false));
3241 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
3242 if (r < 0)
3243 RET_GATHER(ret, r);
3244 else {
3245 for (;;) {
3246 _cleanup_free_ char *fn = NULL, *p = NULL;
3248 r = cg_read_subgroup(d, &fn);
3249 if (r == 0)
3250 break;
3251 if (r < 0) {
3252 RET_GATHER(ret, r);
3253 break;
3256 p = path_join(empty_to_root(path), fn);
3257 if (!p)
3258 return -ENOMEM;
3260 RET_GATHER(ret, unit_watch_pids_in_path(u, p));
3264 return ret;
3267 int unit_synthesize_cgroup_empty_event(Unit *u) {
3268 int r;
3270 assert(u);
3272 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
3273 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
3274 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
3276 if (!u->cgroup_path)
3277 return -ENOENT;
3279 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
3280 if (r < 0)
3281 return r;
3282 if (r > 0) /* On unified we have reliable notifications, and don't need this */
3283 return 0;
3285 if (!set_isempty(u->pids))
3286 return 0;
3288 unit_add_to_cgroup_empty_queue(u);
3289 return 0;
3292 int unit_watch_all_pids(Unit *u) {
3293 int r;
3295 assert(u);
3297 /* Adds all PIDs from our cgroup to the set of PIDs we
3298 * watch. This is a fallback logic for cases where we do not
3299 * get reliable cgroup empty notifications: we try to use
3300 * SIGCHLD as replacement. */
3302 if (!u->cgroup_path)
3303 return -ENOENT;
3305 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
3306 if (r < 0)
3307 return r;
3308 if (r > 0) /* On unified we can use proper notifications */
3309 return 0;
3311 return unit_watch_pids_in_path(u, u->cgroup_path);
3314 static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
3315 Manager *m = ASSERT_PTR(userdata);
3316 Unit *u;
3317 int r;
3319 assert(s);
3321 u = m->cgroup_empty_queue;
3322 if (!u)
3323 return 0;
3325 assert(u->in_cgroup_empty_queue);
3326 u->in_cgroup_empty_queue = false;
3327 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
3329 if (m->cgroup_empty_queue) {
3330 /* More stuff queued, let's make sure we remain enabled */
3331 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
3332 if (r < 0)
3333 log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
3336 /* Update state based on OOM kills before we notify about cgroup empty event */
3337 (void) unit_check_oom(u);
3338 (void) unit_check_oomd_kill(u);
3340 unit_add_to_gc_queue(u);
3342 if (IN_SET(unit_active_state(u), UNIT_INACTIVE, UNIT_FAILED))
3343 unit_prune_cgroup(u);
3344 else if (UNIT_VTABLE(u)->notify_cgroup_empty)
3345 UNIT_VTABLE(u)->notify_cgroup_empty(u);
3347 return 0;
3350 void unit_add_to_cgroup_empty_queue(Unit *u) {
3351 int r;
3353 assert(u);
3355 /* Note that there are four different ways how cgroup empty events reach us:
3357 * 1. On the unified hierarchy we get an inotify event on the cgroup
3359 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
3361 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
3363 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
3364 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
3366 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
3367 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
3368 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
3369 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
3370 * case for scope units). */
3372 if (u->in_cgroup_empty_queue)
3373 return;
3375 /* Let's verify that the cgroup is really empty */
3376 if (!u->cgroup_path)
3377 return;
3379 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
3380 if (r < 0) {
3381 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", empty_to_root(u->cgroup_path));
3382 return;
3384 if (r == 0)
3385 return;
3387 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
3388 u->in_cgroup_empty_queue = true;
3390 /* Trigger the defer event */
3391 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
3392 if (r < 0)
3393 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
3396 static void unit_remove_from_cgroup_empty_queue(Unit *u) {
3397 assert(u);
3399 if (!u->in_cgroup_empty_queue)
3400 return;
3402 LIST_REMOVE(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
3403 u->in_cgroup_empty_queue = false;
3406 int unit_check_oomd_kill(Unit *u) {
3407 _cleanup_free_ char *value = NULL;
3408 bool increased;
3409 uint64_t n = 0;
3410 int r;
3412 if (!u->cgroup_path)
3413 return 0;
3415 r = cg_all_unified();
3416 if (r < 0)
3417 return log_unit_debug_errno(u, r, "Couldn't determine whether we are in all unified mode: %m");
3418 else if (r == 0)
3419 return 0;
3421 r = cg_get_xattr_malloc(u->cgroup_path, "user.oomd_ooms", &value);
3422 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
3423 return r;
3425 if (!isempty(value)) {
3426 r = safe_atou64(value, &n);
3427 if (r < 0)
3428 return r;
3431 increased = n > u->managed_oom_kill_last;
3432 u->managed_oom_kill_last = n;
3434 if (!increased)
3435 return 0;
3437 n = 0;
3438 value = mfree(value);
3439 r = cg_get_xattr_malloc(u->cgroup_path, "user.oomd_kill", &value);
3440 if (r >= 0 && !isempty(value))
3441 (void) safe_atou64(value, &n);
3443 if (n > 0)
3444 log_unit_struct(u, LOG_NOTICE,
3445 "MESSAGE_ID=" SD_MESSAGE_UNIT_OOMD_KILL_STR,
3446 LOG_UNIT_INVOCATION_ID(u),
3447 LOG_UNIT_MESSAGE(u, "systemd-oomd killed %"PRIu64" process(es) in this unit.", n),
3448 "N_PROCESSES=%" PRIu64, n);
3449 else
3450 log_unit_struct(u, LOG_NOTICE,
3451 "MESSAGE_ID=" SD_MESSAGE_UNIT_OOMD_KILL_STR,
3452 LOG_UNIT_INVOCATION_ID(u),
3453 LOG_UNIT_MESSAGE(u, "systemd-oomd killed some process(es) in this unit."));
3455 unit_notify_cgroup_oom(u, /* ManagedOOM= */ true);
3457 return 1;
3460 int unit_check_oom(Unit *u) {
3461 _cleanup_free_ char *oom_kill = NULL;
3462 bool increased;
3463 uint64_t c;
3464 int r;
3466 if (!u->cgroup_path)
3467 return 0;
3469 r = cg_get_keyed_attribute("memory", u->cgroup_path, "memory.events", STRV_MAKE("oom_kill"), &oom_kill);
3470 if (IN_SET(r, -ENOENT, -ENXIO)) /* Handle gracefully if cgroup or oom_kill attribute don't exist */
3471 c = 0;
3472 else if (r < 0)
3473 return log_unit_debug_errno(u, r, "Failed to read oom_kill field of memory.events cgroup attribute: %m");
3474 else {
3475 r = safe_atou64(oom_kill, &c);
3476 if (r < 0)
3477 return log_unit_debug_errno(u, r, "Failed to parse oom_kill field: %m");
3480 increased = c > u->oom_kill_last;
3481 u->oom_kill_last = c;
3483 if (!increased)
3484 return 0;
3486 log_unit_struct(u, LOG_NOTICE,
3487 "MESSAGE_ID=" SD_MESSAGE_UNIT_OUT_OF_MEMORY_STR,
3488 LOG_UNIT_INVOCATION_ID(u),
3489 LOG_UNIT_MESSAGE(u, "A process of this unit has been killed by the OOM killer."));
3491 unit_notify_cgroup_oom(u, /* ManagedOOM= */ false);
3493 return 1;
3496 static int on_cgroup_oom_event(sd_event_source *s, void *userdata) {
3497 Manager *m = ASSERT_PTR(userdata);
3498 Unit *u;
3499 int r;
3501 assert(s);
3503 u = m->cgroup_oom_queue;
3504 if (!u)
3505 return 0;
3507 assert(u->in_cgroup_oom_queue);
3508 u->in_cgroup_oom_queue = false;
3509 LIST_REMOVE(cgroup_oom_queue, m->cgroup_oom_queue, u);
3511 if (m->cgroup_oom_queue) {
3512 /* More stuff queued, let's make sure we remain enabled */
3513 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
3514 if (r < 0)
3515 log_debug_errno(r, "Failed to reenable cgroup oom event source, ignoring: %m");
3518 (void) unit_check_oom(u);
3519 unit_add_to_gc_queue(u);
3521 return 0;
3524 static void unit_add_to_cgroup_oom_queue(Unit *u) {
3525 int r;
3527 assert(u);
3529 if (u->in_cgroup_oom_queue)
3530 return;
3531 if (!u->cgroup_path)
3532 return;
3534 LIST_PREPEND(cgroup_oom_queue, u->manager->cgroup_oom_queue, u);
3535 u->in_cgroup_oom_queue = true;
3537 /* Trigger the defer event */
3538 if (!u->manager->cgroup_oom_event_source) {
3539 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
3541 r = sd_event_add_defer(u->manager->event, &s, on_cgroup_oom_event, u->manager);
3542 if (r < 0) {
3543 log_error_errno(r, "Failed to create cgroup oom event source: %m");
3544 return;
3547 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_NORMAL-8);
3548 if (r < 0) {
3549 log_error_errno(r, "Failed to set priority of cgroup oom event source: %m");
3550 return;
3553 (void) sd_event_source_set_description(s, "cgroup-oom");
3554 u->manager->cgroup_oom_event_source = TAKE_PTR(s);
3557 r = sd_event_source_set_enabled(u->manager->cgroup_oom_event_source, SD_EVENT_ONESHOT);
3558 if (r < 0)
3559 log_error_errno(r, "Failed to enable cgroup oom event source: %m");
3562 static int unit_check_cgroup_events(Unit *u) {
3563 char *values[2] = {};
3564 int r;
3566 assert(u);
3568 if (!u->cgroup_path)
3569 return 0;
3571 r = cg_get_keyed_attribute_graceful(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events",
3572 STRV_MAKE("populated", "frozen"), values);
3573 if (r < 0)
3574 return r;
3576 /* The cgroup.events notifications can be merged together so act as we saw the given state for the
3577 * first time. The functions we call to handle given state are idempotent, which makes them
3578 * effectively remember the previous state. */
3579 if (values[0]) {
3580 if (streq(values[0], "1"))
3581 unit_remove_from_cgroup_empty_queue(u);
3582 else
3583 unit_add_to_cgroup_empty_queue(u);
3586 /* Disregard freezer state changes due to operations not initiated by us */
3587 if (values[1] && IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_THAWING)) {
3588 if (streq(values[1], "0"))
3589 unit_thawed(u);
3590 else
3591 unit_frozen(u);
3594 free(values[0]);
3595 free(values[1]);
3597 return 0;
3600 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
3601 Manager *m = ASSERT_PTR(userdata);
3603 assert(s);
3604 assert(fd >= 0);
3606 for (;;) {
3607 union inotify_event_buffer buffer;
3608 ssize_t l;
3610 l = read(fd, &buffer, sizeof(buffer));
3611 if (l < 0) {
3612 if (ERRNO_IS_TRANSIENT(errno))
3613 return 0;
3615 return log_error_errno(errno, "Failed to read control group inotify events: %m");
3618 FOREACH_INOTIFY_EVENT_WARN(e, buffer, l) {
3619 Unit *u;
3621 if (e->wd < 0)
3622 /* Queue overflow has no watch descriptor */
3623 continue;
3625 if (e->mask & IN_IGNORED)
3626 /* The watch was just removed */
3627 continue;
3629 /* Note that inotify might deliver events for a watch even after it was removed,
3630 * because it was queued before the removal. Let's ignore this here safely. */
3632 u = hashmap_get(m->cgroup_control_inotify_wd_unit, INT_TO_PTR(e->wd));
3633 if (u)
3634 unit_check_cgroup_events(u);
3636 u = hashmap_get(m->cgroup_memory_inotify_wd_unit, INT_TO_PTR(e->wd));
3637 if (u)
3638 unit_add_to_cgroup_oom_queue(u);
3643 static int cg_bpf_mask_supported(CGroupMask *ret) {
3644 CGroupMask mask = 0;
3645 int r;
3647 /* BPF-based firewall */
3648 r = bpf_firewall_supported();
3649 if (r < 0)
3650 return r;
3651 if (r > 0)
3652 mask |= CGROUP_MASK_BPF_FIREWALL;
3654 /* BPF-based device access control */
3655 r = bpf_devices_supported();
3656 if (r < 0)
3657 return r;
3658 if (r > 0)
3659 mask |= CGROUP_MASK_BPF_DEVICES;
3661 /* BPF pinned prog */
3662 r = bpf_foreign_supported();
3663 if (r < 0)
3664 return r;
3665 if (r > 0)
3666 mask |= CGROUP_MASK_BPF_FOREIGN;
3668 /* BPF-based bind{4|6} hooks */
3669 r = bpf_socket_bind_supported();
3670 if (r < 0)
3671 return r;
3672 if (r > 0)
3673 mask |= CGROUP_MASK_BPF_SOCKET_BIND;
3675 /* BPF-based cgroup_skb/{egress|ingress} hooks */
3676 r = restrict_network_interfaces_supported();
3677 if (r < 0)
3678 return r;
3679 if (r > 0)
3680 mask |= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES;
3682 *ret = mask;
3683 return 0;
3686 int manager_setup_cgroup(Manager *m) {
3687 _cleanup_free_ char *path = NULL;
3688 const char *scope_path;
3689 int r, all_unified;
3690 CGroupMask mask;
3691 char *e;
3693 assert(m);
3695 /* 1. Determine hierarchy */
3696 m->cgroup_root = mfree(m->cgroup_root);
3697 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
3698 if (r < 0)
3699 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
3701 /* Chop off the init scope, if we are already located in it */
3702 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
3704 /* LEGACY: Also chop off the system slice if we are in
3705 * it. This is to support live upgrades from older systemd
3706 * versions where PID 1 was moved there. Also see
3707 * cg_get_root_path(). */
3708 if (!e && MANAGER_IS_SYSTEM(m)) {
3709 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
3710 if (!e)
3711 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
3713 if (e)
3714 *e = 0;
3716 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
3717 * easily prepend it everywhere. */
3718 delete_trailing_chars(m->cgroup_root, "/");
3720 /* 2. Show data */
3721 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
3722 if (r < 0)
3723 return log_error_errno(r, "Cannot find cgroup mount point: %m");
3725 r = cg_unified();
3726 if (r < 0)
3727 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
3729 all_unified = cg_all_unified();
3730 if (all_unified < 0)
3731 return log_error_errno(all_unified, "Couldn't determine whether we are in all unified mode: %m");
3732 if (all_unified > 0)
3733 log_debug("Unified cgroup hierarchy is located at %s.", path);
3734 else {
3735 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
3736 if (r < 0)
3737 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
3738 if (r > 0)
3739 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
3740 else
3741 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
3744 /* 3. Allocate cgroup empty defer event source */
3745 m->cgroup_empty_event_source = sd_event_source_disable_unref(m->cgroup_empty_event_source);
3746 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
3747 if (r < 0)
3748 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
3750 /* Schedule cgroup empty checks early, but after having processed service notification messages or
3751 * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of
3752 * notification, and we collected the metadata the notification and SIGCHLD stuff offers first. */
3753 r = sd_event_source_set_priority(m->cgroup_empty_event_source, SD_EVENT_PRIORITY_NORMAL-5);
3754 if (r < 0)
3755 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
3757 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
3758 if (r < 0)
3759 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
3761 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
3763 /* 4. Install notifier inotify object, or agent */
3764 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
3766 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
3768 m->cgroup_inotify_event_source = sd_event_source_disable_unref(m->cgroup_inotify_event_source);
3769 safe_close(m->cgroup_inotify_fd);
3771 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
3772 if (m->cgroup_inotify_fd < 0)
3773 return log_error_errno(errno, "Failed to create control group inotify object: %m");
3775 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
3776 if (r < 0)
3777 return log_error_errno(r, "Failed to watch control group inotify object: %m");
3779 /* Process cgroup empty notifications early. Note that when this event is dispatched it'll
3780 * just add the unit to a cgroup empty queue, hence let's run earlier than that. Also see
3781 * handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
3782 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-9);
3783 if (r < 0)
3784 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
3786 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
3788 } else if (MANAGER_IS_SYSTEM(m) && manager_owns_host_root_cgroup(m) && !MANAGER_IS_TEST_RUN(m)) {
3790 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
3791 * since it does not generate events when control groups with children run empty. */
3793 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUPS_AGENT_PATH);
3794 if (r < 0)
3795 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
3796 else if (r > 0)
3797 log_debug("Installed release agent.");
3798 else if (r == 0)
3799 log_debug("Release agent already installed.");
3802 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
3803 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
3804 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
3805 if (r >= 0) {
3806 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
3807 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
3808 if (r < 0)
3809 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
3811 /* 6. And pin it, so that it cannot be unmounted */
3812 safe_close(m->pin_cgroupfs_fd);
3813 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
3814 if (m->pin_cgroupfs_fd < 0)
3815 return log_error_errno(errno, "Failed to open pin file: %m");
3817 } else if (!MANAGER_IS_TEST_RUN(m))
3818 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
3820 /* 7. Always enable hierarchical support if it exists... */
3821 if (!all_unified && !MANAGER_IS_TEST_RUN(m))
3822 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
3824 /* 8. Figure out which controllers are supported */
3825 r = cg_mask_supported_subtree(m->cgroup_root, &m->cgroup_supported);
3826 if (r < 0)
3827 return log_error_errno(r, "Failed to determine supported controllers: %m");
3829 /* 9. Figure out which bpf-based pseudo-controllers are supported */
3830 r = cg_bpf_mask_supported(&mask);
3831 if (r < 0)
3832 return log_error_errno(r, "Failed to determine supported bpf-based pseudo-controllers: %m");
3833 m->cgroup_supported |= mask;
3835 /* 10. Log which controllers are supported */
3836 for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
3837 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c),
3838 yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
3840 return 0;
3843 void manager_shutdown_cgroup(Manager *m, bool delete) {
3844 assert(m);
3846 /* We can't really delete the group, since we are in it. But
3847 * let's trim it. */
3848 if (delete && m->cgroup_root && !FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
3849 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
3851 m->cgroup_empty_event_source = sd_event_source_disable_unref(m->cgroup_empty_event_source);
3853 m->cgroup_control_inotify_wd_unit = hashmap_free(m->cgroup_control_inotify_wd_unit);
3854 m->cgroup_memory_inotify_wd_unit = hashmap_free(m->cgroup_memory_inotify_wd_unit);
3856 m->cgroup_inotify_event_source = sd_event_source_disable_unref(m->cgroup_inotify_event_source);
3857 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
3859 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
3861 m->cgroup_root = mfree(m->cgroup_root);
3864 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
3865 char *p;
3866 Unit *u;
3868 assert(m);
3869 assert(cgroup);
3871 u = hashmap_get(m->cgroup_unit, cgroup);
3872 if (u)
3873 return u;
3875 p = strdupa_safe(cgroup);
3876 for (;;) {
3877 char *e;
3879 e = strrchr(p, '/');
3880 if (!e || e == p)
3881 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
3883 *e = 0;
3885 u = hashmap_get(m->cgroup_unit, p);
3886 if (u)
3887 return u;
3891 Unit *manager_get_unit_by_pidref_cgroup(Manager *m, PidRef *pid) {
3892 _cleanup_free_ char *cgroup = NULL;
3894 assert(m);
3896 if (cg_pidref_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup) < 0)
3897 return NULL;
3899 return manager_get_unit_by_cgroup(m, cgroup);
3902 Unit *manager_get_unit_by_pidref_watching(Manager *m, PidRef *pid) {
3903 Unit *u, **array;
3905 assert(m);
3907 if (!pidref_is_set(pid))
3908 return NULL;
3910 u = hashmap_get(m->watch_pids, pid);
3911 if (u)
3912 return u;
3914 array = hashmap_get(m->watch_pids_more, pid);
3915 if (array)
3916 return array[0];
3918 return NULL;
3921 Unit *manager_get_unit_by_pidref(Manager *m, PidRef *pid) {
3922 Unit *u;
3924 assert(m);
3926 /* Note that a process might be owned by multiple units, we return only one here, which is good
3927 * enough for most cases, though not strictly correct. We prefer the one reported by cgroup
3928 * membership, as that's the most relevant one as children of the process will be assigned to that
3929 * one, too, before all else. */
3931 if (!pidref_is_set(pid))
3932 return NULL;
3934 if (pidref_is_self(pid))
3935 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
3936 if (pid->pid == 1)
3937 return NULL;
3939 u = manager_get_unit_by_pidref_cgroup(m, pid);
3940 if (u)
3941 return u;
3943 u = manager_get_unit_by_pidref_watching(m, pid);
3944 if (u)
3945 return u;
3947 return NULL;
3950 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
3951 assert(m);
3953 if (!pid_is_valid(pid))
3954 return NULL;
3956 return manager_get_unit_by_pidref(m, &PIDREF_MAKE_FROM_PID(pid));
3959 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
3960 Unit *u;
3962 assert(m);
3963 assert(cgroup);
3965 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
3966 * or from the --system instance */
3968 log_debug("Got cgroup empty notification for: %s", cgroup);
3970 u = manager_get_unit_by_cgroup(m, cgroup);
3971 if (!u)
3972 return 0;
3974 unit_add_to_cgroup_empty_queue(u);
3975 return 1;
3978 int unit_get_memory_available(Unit *u, uint64_t *ret) {
3979 uint64_t available = UINT64_MAX, current = 0;
3981 assert(u);
3982 assert(ret);
3984 /* If data from cgroups can be accessed, try to find out how much more memory a unit can
3985 * claim before hitting the configured cgroup limits (if any). Consider both MemoryHigh
3986 * and MemoryMax, and also any slice the unit might be nested below. */
3988 do {
3989 uint64_t unit_available, unit_limit = UINT64_MAX;
3990 CGroupContext *unit_context;
3992 /* No point in continuing if we can't go any lower */
3993 if (available == 0)
3994 break;
3996 unit_context = unit_get_cgroup_context(u);
3997 if (!unit_context)
3998 return -ENODATA;
4000 if (!u->cgroup_path)
4001 continue;
4003 (void) unit_get_memory_current(u, &current);
4004 /* in case of error, previous current propagates as lower bound */
4006 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
4007 unit_limit = physical_memory();
4008 else if (unit_context->memory_max == UINT64_MAX && unit_context->memory_high == UINT64_MAX)
4009 continue;
4010 unit_limit = MIN3(unit_limit, unit_context->memory_max, unit_context->memory_high);
4012 unit_available = LESS_BY(unit_limit, current);
4013 available = MIN(unit_available, available);
4014 } while ((u = UNIT_GET_SLICE(u)));
4016 *ret = available;
4018 return 0;
4021 int unit_get_memory_current(Unit *u, uint64_t *ret) {
4022 int r;
4024 // FIXME: Merge this into unit_get_memory_accounting after support for cgroup v1 is dropped
4026 assert(u);
4027 assert(ret);
4029 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
4030 return -ENODATA;
4032 if (!u->cgroup_path)
4033 return -ENODATA;
4035 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
4036 if (unit_has_host_root_cgroup(u))
4037 return procfs_memory_get_used(ret);
4039 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
4040 return -ENODATA;
4042 r = cg_all_unified();
4043 if (r < 0)
4044 return r;
4046 return cg_get_attribute_as_uint64("memory", u->cgroup_path, r > 0 ? "memory.current" : "memory.usage_in_bytes", ret);
4049 int unit_get_memory_accounting(Unit *u, CGroupMemoryAccountingMetric metric, uint64_t *ret) {
4051 static const char* const attributes_table[_CGROUP_MEMORY_ACCOUNTING_METRIC_MAX] = {
4052 [CGROUP_MEMORY_PEAK] = "memory.peak",
4053 [CGROUP_MEMORY_SWAP_CURRENT] = "memory.swap.current",
4054 [CGROUP_MEMORY_SWAP_PEAK] = "memory.swap.peak",
4055 [CGROUP_MEMORY_ZSWAP_CURRENT] = "memory.zswap.current",
4058 uint64_t bytes;
4059 bool updated = false;
4060 int r;
4062 assert(u);
4063 assert(metric >= 0);
4064 assert(metric < _CGROUP_MEMORY_ACCOUNTING_METRIC_MAX);
4066 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
4067 return -ENODATA;
4069 if (!u->cgroup_path)
4070 /* If the cgroup is already gone, we try to find the last cached value. */
4071 goto finish;
4073 /* The root cgroup doesn't expose this information. */
4074 if (unit_has_host_root_cgroup(u))
4075 return -ENODATA;
4077 if (!FLAGS_SET(u->cgroup_realized_mask, CGROUP_MASK_MEMORY))
4078 return -ENODATA;
4080 r = cg_all_unified();
4081 if (r < 0)
4082 return r;
4083 if (r == 0)
4084 return -ENODATA;
4086 r = cg_get_attribute_as_uint64("memory", u->cgroup_path, attributes_table[metric], &bytes);
4087 if (r < 0 && r != -ENODATA)
4088 return r;
4089 updated = r >= 0;
4091 finish:
4092 if (metric <= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST) {
4093 uint64_t *last = &u->memory_accounting_last[metric];
4095 if (updated)
4096 *last = bytes;
4097 else if (*last != UINT64_MAX)
4098 bytes = *last;
4099 else
4100 return -ENODATA;
4102 } else if (!updated)
4103 return -ENODATA;
4105 if (ret)
4106 *ret = bytes;
4108 return 0;
4111 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
4112 assert(u);
4113 assert(ret);
4115 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
4116 return -ENODATA;
4118 if (!u->cgroup_path)
4119 return -ENODATA;
4121 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
4122 if (unit_has_host_root_cgroup(u))
4123 return procfs_tasks_get_current(ret);
4125 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
4126 return -ENODATA;
4128 return cg_get_attribute_as_uint64("pids", u->cgroup_path, "pids.current", ret);
4131 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
4132 uint64_t ns;
4133 int r;
4135 assert(u);
4136 assert(ret);
4138 if (!u->cgroup_path)
4139 return -ENODATA;
4141 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
4142 if (unit_has_host_root_cgroup(u))
4143 return procfs_cpu_get_usage(ret);
4145 /* Requisite controllers for CPU accounting are not enabled */
4146 if ((get_cpu_accounting_mask() & ~u->cgroup_realized_mask) != 0)
4147 return -ENODATA;
4149 r = cg_all_unified();
4150 if (r < 0)
4151 return r;
4152 if (r > 0) {
4153 _cleanup_free_ char *val = NULL;
4154 uint64_t us;
4156 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
4157 if (IN_SET(r, -ENOENT, -ENXIO))
4158 return -ENODATA;
4159 if (r < 0)
4160 return r;
4162 r = safe_atou64(val, &us);
4163 if (r < 0)
4164 return r;
4166 ns = us * NSEC_PER_USEC;
4167 } else
4168 return cg_get_attribute_as_uint64("cpuacct", u->cgroup_path, "cpuacct.usage", ret);
4170 *ret = ns;
4171 return 0;
4174 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
4175 nsec_t ns;
4176 int r;
4178 assert(u);
4180 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
4181 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
4182 * call this function with a NULL return value. */
4184 if (!UNIT_CGROUP_BOOL(u, cpu_accounting))
4185 return -ENODATA;
4187 r = unit_get_cpu_usage_raw(u, &ns);
4188 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
4189 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
4190 * cached value. */
4192 if (ret)
4193 *ret = u->cpu_usage_last;
4194 return 0;
4196 if (r < 0)
4197 return r;
4199 if (ns > u->cpu_usage_base)
4200 ns -= u->cpu_usage_base;
4201 else
4202 ns = 0;
4204 u->cpu_usage_last = ns;
4205 if (ret)
4206 *ret = ns;
4208 return 0;
4211 int unit_get_ip_accounting(
4212 Unit *u,
4213 CGroupIPAccountingMetric metric,
4214 uint64_t *ret) {
4216 uint64_t value;
4217 int fd, r;
4219 assert(u);
4220 assert(metric >= 0);
4221 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
4222 assert(ret);
4224 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
4225 return -ENODATA;
4227 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
4228 u->ip_accounting_ingress_map_fd :
4229 u->ip_accounting_egress_map_fd;
4230 if (fd < 0)
4231 return -ENODATA;
4233 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
4234 r = bpf_firewall_read_accounting(fd, &value, NULL);
4235 else
4236 r = bpf_firewall_read_accounting(fd, NULL, &value);
4237 if (r < 0)
4238 return r;
4240 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
4241 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
4242 * ip_accounting_extra[] field, and add them in here transparently. */
4244 *ret = value + u->ip_accounting_extra[metric];
4246 return r;
4249 static int unit_get_io_accounting_raw(Unit *u, uint64_t ret[static _CGROUP_IO_ACCOUNTING_METRIC_MAX]) {
4250 static const char *const field_names[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
4251 [CGROUP_IO_READ_BYTES] = "rbytes=",
4252 [CGROUP_IO_WRITE_BYTES] = "wbytes=",
4253 [CGROUP_IO_READ_OPERATIONS] = "rios=",
4254 [CGROUP_IO_WRITE_OPERATIONS] = "wios=",
4256 uint64_t acc[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {};
4257 _cleanup_free_ char *path = NULL;
4258 _cleanup_fclose_ FILE *f = NULL;
4259 int r;
4261 assert(u);
4263 if (!u->cgroup_path)
4264 return -ENODATA;
4266 if (unit_has_host_root_cgroup(u))
4267 return -ENODATA; /* TODO: return useful data for the top-level cgroup */
4269 r = cg_all_unified();
4270 if (r < 0)
4271 return r;
4272 if (r == 0) /* TODO: support cgroupv1 */
4273 return -ENODATA;
4275 if (!FLAGS_SET(u->cgroup_realized_mask, CGROUP_MASK_IO))
4276 return -ENODATA;
4278 r = cg_get_path("io", u->cgroup_path, "io.stat", &path);
4279 if (r < 0)
4280 return r;
4282 f = fopen(path, "re");
4283 if (!f)
4284 return -errno;
4286 for (;;) {
4287 _cleanup_free_ char *line = NULL;
4288 const char *p;
4290 r = read_line(f, LONG_LINE_MAX, &line);
4291 if (r < 0)
4292 return r;
4293 if (r == 0)
4294 break;
4296 p = line;
4297 p += strcspn(p, WHITESPACE); /* Skip over device major/minor */
4298 p += strspn(p, WHITESPACE); /* Skip over following whitespace */
4300 for (;;) {
4301 _cleanup_free_ char *word = NULL;
4303 r = extract_first_word(&p, &word, NULL, EXTRACT_RETAIN_ESCAPE);
4304 if (r < 0)
4305 return r;
4306 if (r == 0)
4307 break;
4309 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
4310 const char *x;
4312 x = startswith(word, field_names[i]);
4313 if (x) {
4314 uint64_t w;
4316 r = safe_atou64(x, &w);
4317 if (r < 0)
4318 return r;
4320 /* Sum up the stats of all devices */
4321 acc[i] += w;
4322 break;
4328 memcpy(ret, acc, sizeof(acc));
4329 return 0;
4332 int unit_get_io_accounting(
4333 Unit *u,
4334 CGroupIOAccountingMetric metric,
4335 bool allow_cache,
4336 uint64_t *ret) {
4338 uint64_t raw[_CGROUP_IO_ACCOUNTING_METRIC_MAX];
4339 int r;
4341 /* Retrieve an IO account parameter. This will subtract the counter when the unit was started. */
4343 if (!UNIT_CGROUP_BOOL(u, io_accounting))
4344 return -ENODATA;
4346 if (allow_cache && u->io_accounting_last[metric] != UINT64_MAX)
4347 goto done;
4349 r = unit_get_io_accounting_raw(u, raw);
4350 if (r == -ENODATA && u->io_accounting_last[metric] != UINT64_MAX)
4351 goto done;
4352 if (r < 0)
4353 return r;
4355 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
4356 /* Saturated subtraction */
4357 if (raw[i] > u->io_accounting_base[i])
4358 u->io_accounting_last[i] = raw[i] - u->io_accounting_base[i];
4359 else
4360 u->io_accounting_last[i] = 0;
4363 done:
4364 if (ret)
4365 *ret = u->io_accounting_last[metric];
4367 return 0;
4370 int unit_reset_cpu_accounting(Unit *u) {
4371 int r;
4373 assert(u);
4375 u->cpu_usage_last = NSEC_INFINITY;
4377 r = unit_get_cpu_usage_raw(u, &u->cpu_usage_base);
4378 if (r < 0) {
4379 u->cpu_usage_base = 0;
4380 return r;
4383 return 0;
4386 void unit_reset_memory_accounting_last(Unit *u) {
4387 assert(u);
4389 FOREACH_ARRAY(i, u->memory_accounting_last, ELEMENTSOF(u->memory_accounting_last))
4390 *i = UINT64_MAX;
4393 int unit_reset_ip_accounting(Unit *u) {
4394 int r = 0;
4396 assert(u);
4398 if (u->ip_accounting_ingress_map_fd >= 0)
4399 RET_GATHER(r, bpf_firewall_reset_accounting(u->ip_accounting_ingress_map_fd));
4401 if (u->ip_accounting_egress_map_fd >= 0)
4402 RET_GATHER(r, bpf_firewall_reset_accounting(u->ip_accounting_egress_map_fd));
4404 zero(u->ip_accounting_extra);
4406 return r;
4409 void unit_reset_io_accounting_last(Unit *u) {
4410 assert(u);
4412 FOREACH_ARRAY(i, u->io_accounting_last, _CGROUP_IO_ACCOUNTING_METRIC_MAX)
4413 *i = UINT64_MAX;
4416 int unit_reset_io_accounting(Unit *u) {
4417 int r;
4419 assert(u);
4421 unit_reset_io_accounting_last(u);
4423 r = unit_get_io_accounting_raw(u, u->io_accounting_base);
4424 if (r < 0) {
4425 zero(u->io_accounting_base);
4426 return r;
4429 return 0;
4432 int unit_reset_accounting(Unit *u) {
4433 int r = 0;
4435 assert(u);
4437 RET_GATHER(r, unit_reset_cpu_accounting(u));
4438 RET_GATHER(r, unit_reset_io_accounting(u));
4439 RET_GATHER(r, unit_reset_ip_accounting(u));
4440 unit_reset_memory_accounting_last(u);
4442 return r;
4445 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
4446 assert(u);
4448 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4449 return;
4451 if (m == 0)
4452 return;
4454 /* always invalidate compat pairs together */
4455 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
4456 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
4458 if (m & (CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT))
4459 m |= CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT;
4461 if (FLAGS_SET(u->cgroup_invalidated_mask, m)) /* NOP? */
4462 return;
4464 u->cgroup_invalidated_mask |= m;
4465 unit_add_to_cgroup_realize_queue(u);
4468 void unit_invalidate_cgroup_bpf(Unit *u) {
4469 assert(u);
4471 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4472 return;
4474 if (u->cgroup_invalidated_mask & CGROUP_MASK_BPF_FIREWALL) /* NOP? */
4475 return;
4477 u->cgroup_invalidated_mask |= CGROUP_MASK_BPF_FIREWALL;
4478 unit_add_to_cgroup_realize_queue(u);
4480 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
4481 * list of our children includes our own. */
4482 if (u->type == UNIT_SLICE) {
4483 Unit *member;
4485 UNIT_FOREACH_DEPENDENCY(member, u, UNIT_ATOM_SLICE_OF)
4486 unit_invalidate_cgroup_bpf(member);
4490 void unit_cgroup_catchup(Unit *u) {
4491 assert(u);
4493 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4494 return;
4496 /* We dropped the inotify watch during reexec/reload, so we need to
4497 * check these as they may have changed.
4498 * Note that (currently) the kernel doesn't actually update cgroup
4499 * file modification times, so we can't just serialize and then check
4500 * the mtime for file(s) we are interested in. */
4501 (void) unit_check_cgroup_events(u);
4502 unit_add_to_cgroup_oom_queue(u);
4505 bool unit_cgroup_delegate(Unit *u) {
4506 CGroupContext *c;
4508 assert(u);
4510 if (!UNIT_VTABLE(u)->can_delegate)
4511 return false;
4513 c = unit_get_cgroup_context(u);
4514 if (!c)
4515 return false;
4517 return c->delegate;
4520 void manager_invalidate_startup_units(Manager *m) {
4521 Unit *u;
4523 assert(m);
4525 SET_FOREACH(u, m->startup_units)
4526 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO|CGROUP_MASK_CPUSET);
4529 int unit_cgroup_freezer_action(Unit *u, FreezerAction action) {
4530 _cleanup_free_ char *path = NULL;
4531 FreezerState target, kernel = _FREEZER_STATE_INVALID;
4532 int r, ret;
4534 assert(u);
4535 assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
4537 if (!cg_freezer_supported())
4538 return 0;
4540 /* Ignore all requests to thaw init.scope or -.slice and reject all requests to freeze them */
4541 if (unit_has_name(u, SPECIAL_ROOT_SLICE) || unit_has_name(u, SPECIAL_INIT_SCOPE))
4542 return action == FREEZER_FREEZE ? -EPERM : 0;
4544 if (!u->cgroup_realized)
4545 return -EBUSY;
4547 if (action == FREEZER_THAW) {
4548 Unit *slice = UNIT_GET_SLICE(u);
4550 if (slice) {
4551 r = unit_cgroup_freezer_action(slice, FREEZER_THAW);
4552 if (r < 0)
4553 return log_unit_error_errno(u, r, "Failed to thaw slice %s of unit: %m", slice->id);
4557 target = action == FREEZER_FREEZE ? FREEZER_FROZEN : FREEZER_RUNNING;
4559 r = unit_freezer_state_kernel(u, &kernel);
4560 if (r < 0)
4561 log_unit_debug_errno(u, r, "Failed to obtain cgroup freezer state: %m");
4563 if (target == kernel) {
4564 u->freezer_state = target;
4565 if (action == FREEZER_FREEZE)
4566 return 0;
4567 ret = 0;
4568 } else
4569 ret = 1;
4571 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.freeze", &path);
4572 if (r < 0)
4573 return r;
4575 log_unit_debug(u, "%s unit.", action == FREEZER_FREEZE ? "Freezing" : "Thawing");
4577 if (target != kernel) {
4578 if (action == FREEZER_FREEZE)
4579 u->freezer_state = FREEZER_FREEZING;
4580 else
4581 u->freezer_state = FREEZER_THAWING;
4584 r = write_string_file(path, one_zero(action == FREEZER_FREEZE), WRITE_STRING_FILE_DISABLE_BUFFER);
4585 if (r < 0)
4586 return r;
4588 return ret;
4591 int unit_get_cpuset(Unit *u, CPUSet *cpus, const char *name) {
4592 _cleanup_free_ char *v = NULL;
4593 int r;
4595 assert(u);
4596 assert(cpus);
4598 if (!u->cgroup_path)
4599 return -ENODATA;
4601 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUSET) == 0)
4602 return -ENODATA;
4604 r = cg_all_unified();
4605 if (r < 0)
4606 return r;
4607 if (r == 0)
4608 return -ENODATA;
4610 r = cg_get_attribute("cpuset", u->cgroup_path, name, &v);
4611 if (r == -ENOENT)
4612 return -ENODATA;
4613 if (r < 0)
4614 return r;
4616 return parse_cpu_set_full(v, cpus, false, NULL, NULL, 0, NULL);
4619 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
4620 [CGROUP_DEVICE_POLICY_AUTO] = "auto",
4621 [CGROUP_DEVICE_POLICY_CLOSED] = "closed",
4622 [CGROUP_DEVICE_POLICY_STRICT] = "strict",
4625 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);
4627 static const char* const freezer_action_table[_FREEZER_ACTION_MAX] = {
4628 [FREEZER_FREEZE] = "freeze",
4629 [FREEZER_THAW] = "thaw",
4632 DEFINE_STRING_TABLE_LOOKUP(freezer_action, FreezerAction);
4634 static const char* const cgroup_pressure_watch_table[_CGROUP_PRESSURE_WATCH_MAX] = {
4635 [CGROUP_PRESSURE_WATCH_OFF] = "off",
4636 [CGROUP_PRESSURE_WATCH_AUTO] = "auto",
4637 [CGROUP_PRESSURE_WATCH_ON] = "on",
4638 [CGROUP_PRESSURE_WATCH_SKIP] = "skip",
4641 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(cgroup_pressure_watch, CGroupPressureWatch, CGROUP_PRESSURE_WATCH_ON);
4643 static const char* const cgroup_ip_accounting_metric_table[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
4644 [CGROUP_IP_INGRESS_BYTES] = "IPIngressBytes",
4645 [CGROUP_IP_EGRESS_BYTES] = "IPEgressBytes",
4646 [CGROUP_IP_INGRESS_PACKETS] = "IPIngressPackets",
4647 [CGROUP_IP_EGRESS_PACKETS] = "IPEgressPackets",
4650 DEFINE_STRING_TABLE_LOOKUP(cgroup_ip_accounting_metric, CGroupIPAccountingMetric);
4652 static const char* const cgroup_io_accounting_metric_table[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
4653 [CGROUP_IO_READ_BYTES] = "IOReadBytes",
4654 [CGROUP_IO_WRITE_BYTES] = "IOWriteBytes",
4655 [CGROUP_IO_READ_OPERATIONS] = "IOReadOperations",
4656 [CGROUP_IO_WRITE_OPERATIONS] = "IOWriteOperations",
4659 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_accounting_metric, CGroupIOAccountingMetric);
4661 static const char* const cgroup_memory_accounting_metric_table[_CGROUP_MEMORY_ACCOUNTING_METRIC_MAX] = {
4662 [CGROUP_MEMORY_PEAK] = "MemoryPeak",
4663 [CGROUP_MEMORY_SWAP_CURRENT] = "MemorySwapCurrent",
4664 [CGROUP_MEMORY_SWAP_PEAK] = "MemorySwapPeak",
4665 [CGROUP_MEMORY_ZSWAP_CURRENT] = "MemoryZSwapCurrent",
4668 DEFINE_STRING_TABLE_LOOKUP(cgroup_memory_accounting_metric, CGroupMemoryAccountingMetric);