udev: String substitutions can be done in ENV, too
[systemd_ALT.git] / src / core / cgroup.c
blob8a3059b042947c061fc7faabf528bcad56342af1
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 "in-addr-prefix-util.h"
24 #include "inotify-util.h"
25 #include "io-util.h"
26 #include "ip-protocol-list.h"
27 #include "limits-util.h"
28 #include "nulstr-util.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "percent-util.h"
32 #include "process-util.h"
33 #include "procfs-util.h"
34 #include "restrict-ifaces.h"
35 #include "special.h"
36 #include "stdio-util.h"
37 #include "string-table.h"
38 #include "string-util.h"
39 #include "virt.h"
41 #if BPF_FRAMEWORK
42 #include "bpf-dlopen.h"
43 #include "bpf-link.h"
44 #include "bpf/restrict_fs/restrict-fs-skel.h"
45 #endif
47 #define CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
49 /* Returns the log level to use when cgroup attribute writes fail. When an attribute is missing or we have access
50 * problems we downgrade to LOG_DEBUG. This is supposed to be nice to container managers and kernels which want to mask
51 * out specific attributes from us. */
52 #define LOG_LEVEL_CGROUP_WRITE(r) (IN_SET(abs(r), ENOENT, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING)
54 uint64_t tasks_max_resolve(const TasksMax *tasks_max) {
55 if (tasks_max->scale == 0)
56 return tasks_max->value;
58 return system_tasks_max_scale(tasks_max->value, tasks_max->scale);
61 bool manager_owns_host_root_cgroup(Manager *m) {
62 assert(m);
64 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
65 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
66 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
67 * we run in any kind of container virtualization. */
69 if (MANAGER_IS_USER(m))
70 return false;
72 if (detect_container() > 0)
73 return false;
75 return empty_or_root(m->cgroup_root);
78 bool unit_has_startup_cgroup_constraints(Unit *u) {
79 assert(u);
81 /* Returns true if this unit has any directives which apply during
82 * startup/shutdown phases. */
84 CGroupContext *c;
86 c = unit_get_cgroup_context(u);
87 if (!c)
88 return false;
90 return c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID ||
91 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
92 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
93 c->startup_cpuset_cpus.set ||
94 c->startup_cpuset_mems.set ||
95 c->startup_memory_high_set ||
96 c->startup_memory_max_set ||
97 c->startup_memory_swap_max_set||
98 c->startup_memory_zswap_max_set ||
99 c->startup_memory_low_set;
102 bool unit_has_host_root_cgroup(Unit *u) {
103 assert(u);
105 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
106 * the manager manages the root cgroup. */
108 if (!manager_owns_host_root_cgroup(u->manager))
109 return false;
111 return unit_has_name(u, SPECIAL_ROOT_SLICE);
114 static int set_attribute_and_warn(Unit *u, const char *controller, const char *attribute, const char *value) {
115 int r;
117 r = cg_set_attribute(controller, u->cgroup_path, attribute, value);
118 if (r < 0)
119 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to set '%s' attribute on '%s' to '%.*s': %m",
120 strna(attribute), empty_to_root(u->cgroup_path), (int) strcspn(value, NEWLINE), value);
122 return r;
125 static void cgroup_compat_warn(void) {
126 static bool cgroup_compat_warned = false;
128 if (cgroup_compat_warned)
129 return;
131 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
132 "See cgroup-compat debug messages for details.");
134 cgroup_compat_warned = true;
137 #define log_cgroup_compat(unit, fmt, ...) do { \
138 cgroup_compat_warn(); \
139 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
140 } while (false)
142 void cgroup_context_init(CGroupContext *c) {
143 assert(c);
145 /* Initialize everything to the kernel defaults. */
147 *c = (CGroupContext) {
148 .cpu_weight = CGROUP_WEIGHT_INVALID,
149 .startup_cpu_weight = CGROUP_WEIGHT_INVALID,
150 .cpu_quota_per_sec_usec = USEC_INFINITY,
151 .cpu_quota_period_usec = USEC_INFINITY,
153 .cpu_shares = CGROUP_CPU_SHARES_INVALID,
154 .startup_cpu_shares = CGROUP_CPU_SHARES_INVALID,
156 .memory_high = CGROUP_LIMIT_MAX,
157 .startup_memory_high = CGROUP_LIMIT_MAX,
158 .memory_max = CGROUP_LIMIT_MAX,
159 .startup_memory_max = CGROUP_LIMIT_MAX,
160 .memory_swap_max = CGROUP_LIMIT_MAX,
161 .startup_memory_swap_max = CGROUP_LIMIT_MAX,
162 .memory_zswap_max = CGROUP_LIMIT_MAX,
163 .startup_memory_zswap_max = CGROUP_LIMIT_MAX,
165 .memory_limit = CGROUP_LIMIT_MAX,
167 .io_weight = CGROUP_WEIGHT_INVALID,
168 .startup_io_weight = CGROUP_WEIGHT_INVALID,
170 .blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
171 .startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
173 .tasks_max = TASKS_MAX_UNSET,
175 .moom_swap = MANAGED_OOM_AUTO,
176 .moom_mem_pressure = MANAGED_OOM_AUTO,
177 .moom_preference = MANAGED_OOM_PREFERENCE_NONE,
179 .memory_pressure_watch = _CGROUP_PRESSURE_WATCH_INVALID,
180 .memory_pressure_threshold_usec = USEC_INFINITY,
184 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
185 assert(c);
186 assert(a);
188 LIST_REMOVE(device_allow, c->device_allow, a);
189 free(a->path);
190 free(a);
193 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
194 assert(c);
195 assert(w);
197 LIST_REMOVE(device_weights, c->io_device_weights, w);
198 free(w->path);
199 free(w);
202 void cgroup_context_free_io_device_latency(CGroupContext *c, CGroupIODeviceLatency *l) {
203 assert(c);
204 assert(l);
206 LIST_REMOVE(device_latencies, c->io_device_latencies, l);
207 free(l->path);
208 free(l);
211 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
212 assert(c);
213 assert(l);
215 LIST_REMOVE(device_limits, c->io_device_limits, l);
216 free(l->path);
217 free(l);
220 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
221 assert(c);
222 assert(w);
224 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
225 free(w->path);
226 free(w);
229 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
230 assert(c);
231 assert(b);
233 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
234 free(b->path);
235 free(b);
238 void cgroup_context_remove_bpf_foreign_program(CGroupContext *c, CGroupBPFForeignProgram *p) {
239 assert(c);
240 assert(p);
242 LIST_REMOVE(programs, c->bpf_foreign_programs, p);
243 free(p->bpffs_path);
244 free(p);
247 void cgroup_context_remove_socket_bind(CGroupSocketBindItem **head) {
248 assert(head);
250 while (*head) {
251 CGroupSocketBindItem *h = *head;
252 LIST_REMOVE(socket_bind_items, *head, h);
253 free(h);
257 void cgroup_context_done(CGroupContext *c) {
258 assert(c);
260 while (c->io_device_weights)
261 cgroup_context_free_io_device_weight(c, c->io_device_weights);
263 while (c->io_device_latencies)
264 cgroup_context_free_io_device_latency(c, c->io_device_latencies);
266 while (c->io_device_limits)
267 cgroup_context_free_io_device_limit(c, c->io_device_limits);
269 while (c->blockio_device_weights)
270 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
272 while (c->blockio_device_bandwidths)
273 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
275 while (c->device_allow)
276 cgroup_context_free_device_allow(c, c->device_allow);
278 cgroup_context_remove_socket_bind(&c->socket_bind_allow);
279 cgroup_context_remove_socket_bind(&c->socket_bind_deny);
281 c->ip_address_allow = set_free(c->ip_address_allow);
282 c->ip_address_deny = set_free(c->ip_address_deny);
284 c->ip_filters_ingress = strv_free(c->ip_filters_ingress);
285 c->ip_filters_egress = strv_free(c->ip_filters_egress);
287 while (c->bpf_foreign_programs)
288 cgroup_context_remove_bpf_foreign_program(c, c->bpf_foreign_programs);
290 c->restrict_network_interfaces = set_free_free(c->restrict_network_interfaces);
292 cpu_set_reset(&c->cpuset_cpus);
293 cpu_set_reset(&c->startup_cpuset_cpus);
294 cpu_set_reset(&c->cpuset_mems);
295 cpu_set_reset(&c->startup_cpuset_mems);
297 c->delegate_subgroup = mfree(c->delegate_subgroup);
300 static int unit_get_kernel_memory_limit(Unit *u, const char *file, uint64_t *ret) {
301 assert(u);
303 if (!u->cgroup_realized)
304 return -EOWNERDEAD;
306 return cg_get_attribute_as_uint64("memory", u->cgroup_path, file, ret);
309 static int unit_compare_memory_limit(Unit *u, const char *property_name, uint64_t *ret_unit_value, uint64_t *ret_kernel_value) {
310 CGroupContext *c;
311 CGroupMask m;
312 const char *file;
313 uint64_t unit_value;
314 int r;
316 /* Compare kernel memcg configuration against our internal systemd state. Unsupported (and will
317 * return -ENODATA) on cgroup v1.
319 * Returns:
321 * <0: On error.
322 * 0: If the kernel memory setting doesn't match our configuration.
323 * >0: If the kernel memory setting matches our configuration.
325 * The following values are only guaranteed to be populated on return >=0:
327 * - ret_unit_value will contain our internal expected value for the unit, page-aligned.
328 * - ret_kernel_value will contain the actual value presented by the kernel. */
330 assert(u);
332 r = cg_all_unified();
333 if (r < 0)
334 return log_debug_errno(r, "Failed to determine cgroup hierarchy version: %m");
336 /* Unsupported on v1.
338 * We don't return ENOENT, since that could actually mask a genuine problem where somebody else has
339 * silently masked the controller. */
340 if (r == 0)
341 return -ENODATA;
343 /* The root slice doesn't have any controller files, so we can't compare anything. */
344 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
345 return -ENODATA;
347 /* It's possible to have MemoryFoo set without systemd wanting to have the memory controller enabled,
348 * for example, in the case of DisableControllers= or cgroup_disable on the kernel command line. To
349 * avoid specious errors in these scenarios, check that we even expect the memory controller to be
350 * enabled at all. */
351 m = unit_get_target_mask(u);
352 if (!FLAGS_SET(m, CGROUP_MASK_MEMORY))
353 return -ENODATA;
355 assert_se(c = unit_get_cgroup_context(u));
357 bool startup = u->manager && IN_SET(manager_state(u->manager), MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING);
359 if (streq(property_name, "MemoryLow")) {
360 unit_value = unit_get_ancestor_memory_low(u);
361 file = "memory.low";
362 } else if (startup && streq(property_name, "StartupMemoryLow")) {
363 unit_value = unit_get_ancestor_startup_memory_low(u);
364 file = "memory.low";
365 } else if (streq(property_name, "MemoryMin")) {
366 unit_value = unit_get_ancestor_memory_min(u);
367 file = "memory.min";
368 } else if (streq(property_name, "MemoryHigh")) {
369 unit_value = c->memory_high;
370 file = "memory.high";
371 } else if (startup && streq(property_name, "StartupMemoryHigh")) {
372 unit_value = c->startup_memory_high;
373 file = "memory.high";
374 } else if (streq(property_name, "MemoryMax")) {
375 unit_value = c->memory_max;
376 file = "memory.max";
377 } else if (startup && streq(property_name, "StartupMemoryMax")) {
378 unit_value = c->startup_memory_max;
379 file = "memory.max";
380 } else if (streq(property_name, "MemorySwapMax")) {
381 unit_value = c->memory_swap_max;
382 file = "memory.swap.max";
383 } else if (startup && streq(property_name, "StartupMemorySwapMax")) {
384 unit_value = c->startup_memory_swap_max;
385 file = "memory.swap.max";
386 } else if (streq(property_name, "MemoryZSwapMax")) {
387 unit_value = c->memory_zswap_max;
388 file = "memory.zswap.max";
389 } else if (startup && streq(property_name, "StartupMemoryZSwapMax")) {
390 unit_value = c->startup_memory_zswap_max;
391 file = "memory.zswap.max";
392 } else
393 return -EINVAL;
395 r = unit_get_kernel_memory_limit(u, file, ret_kernel_value);
396 if (r < 0)
397 return log_unit_debug_errno(u, r, "Failed to parse %s: %m", file);
399 /* It's intended (soon) in a future kernel to not expose cgroup memory limits rounded to page
400 * boundaries, but instead separate the user-exposed limit, which is whatever userspace told us, from
401 * our internal page-counting. To support those future kernels, just check the value itself first
402 * without any page-alignment. */
403 if (*ret_kernel_value == unit_value) {
404 *ret_unit_value = unit_value;
405 return 1;
408 /* The current kernel behaviour, by comparison, is that even if you write a particular number of
409 * bytes into a cgroup memory file, it always returns that number page-aligned down (since the kernel
410 * internally stores cgroup limits in pages). As such, so long as it aligns properly, everything is
411 * cricket. */
412 if (unit_value != CGROUP_LIMIT_MAX)
413 unit_value = PAGE_ALIGN_DOWN(unit_value);
415 *ret_unit_value = unit_value;
417 return *ret_kernel_value == *ret_unit_value;
420 #define FORMAT_CGROUP_DIFF_MAX 128
422 static char *format_cgroup_memory_limit_comparison(char *buf, size_t l, Unit *u, const char *property_name) {
423 uint64_t kval, sval;
424 int r;
426 assert(u);
427 assert(buf);
428 assert(l > 0);
430 r = unit_compare_memory_limit(u, property_name, &sval, &kval);
432 /* memory.swap.max is special in that it relies on CONFIG_MEMCG_SWAP (and the default swapaccount=1).
433 * In the absence of reliably being able to detect whether memcg swap support is available or not,
434 * only complain if the error is not ENOENT. This is similarly the case for memory.zswap.max relying
435 * on CONFIG_ZSWAP. */
436 if (r > 0 || IN_SET(r, -ENODATA, -EOWNERDEAD) ||
437 (r == -ENOENT && STR_IN_SET(property_name,
438 "MemorySwapMax",
439 "StartupMemorySwapMax",
440 "MemoryZSwapMax",
441 "StartupMemoryZSwapMax")))
442 buf[0] = 0;
443 else if (r < 0) {
444 errno = -r;
445 (void) snprintf(buf, l, " (error getting kernel value: %m)");
446 } else
447 (void) snprintf(buf, l, " (different value in kernel: %" PRIu64 ")", kval);
449 return buf;
452 void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
453 _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;
454 CGroupContext *c;
455 struct in_addr_prefix *iaai;
457 char cda[FORMAT_CGROUP_DIFF_MAX];
458 char cdb[FORMAT_CGROUP_DIFF_MAX];
459 char cdc[FORMAT_CGROUP_DIFF_MAX];
460 char cdd[FORMAT_CGROUP_DIFF_MAX];
461 char cde[FORMAT_CGROUP_DIFF_MAX];
462 char cdf[FORMAT_CGROUP_DIFF_MAX];
463 char cdg[FORMAT_CGROUP_DIFF_MAX];
464 char cdh[FORMAT_CGROUP_DIFF_MAX];
465 char cdi[FORMAT_CGROUP_DIFF_MAX];
466 char cdj[FORMAT_CGROUP_DIFF_MAX];
467 char cdk[FORMAT_CGROUP_DIFF_MAX];
469 assert(u);
470 assert(f);
472 assert_se(c = unit_get_cgroup_context(u));
474 prefix = strempty(prefix);
476 (void) cg_mask_to_string(c->disable_controllers, &disable_controllers_str);
477 (void) cg_mask_to_string(c->delegate_controllers, &delegate_controllers_str);
479 /* "Delegate=" means "yes, but no controllers". Show this as "(none)". */
480 const char *delegate_str = delegate_controllers_str ?: c->delegate ? "(none)" : "no";
482 cpuset_cpus = cpu_set_to_range_string(&c->cpuset_cpus);
483 startup_cpuset_cpus = cpu_set_to_range_string(&c->startup_cpuset_cpus);
484 cpuset_mems = cpu_set_to_range_string(&c->cpuset_mems);
485 startup_cpuset_mems = cpu_set_to_range_string(&c->startup_cpuset_mems);
487 fprintf(f,
488 "%sCPUAccounting: %s\n"
489 "%sIOAccounting: %s\n"
490 "%sBlockIOAccounting: %s\n"
491 "%sMemoryAccounting: %s\n"
492 "%sTasksAccounting: %s\n"
493 "%sIPAccounting: %s\n"
494 "%sCPUWeight: %" PRIu64 "\n"
495 "%sStartupCPUWeight: %" PRIu64 "\n"
496 "%sCPUShares: %" PRIu64 "\n"
497 "%sStartupCPUShares: %" PRIu64 "\n"
498 "%sCPUQuotaPerSecSec: %s\n"
499 "%sCPUQuotaPeriodSec: %s\n"
500 "%sAllowedCPUs: %s\n"
501 "%sStartupAllowedCPUs: %s\n"
502 "%sAllowedMemoryNodes: %s\n"
503 "%sStartupAllowedMemoryNodes: %s\n"
504 "%sIOWeight: %" PRIu64 "\n"
505 "%sStartupIOWeight: %" PRIu64 "\n"
506 "%sBlockIOWeight: %" PRIu64 "\n"
507 "%sStartupBlockIOWeight: %" PRIu64 "\n"
508 "%sDefaultMemoryMin: %" PRIu64 "\n"
509 "%sDefaultMemoryLow: %" PRIu64 "\n"
510 "%sMemoryMin: %" PRIu64 "%s\n"
511 "%sMemoryLow: %" PRIu64 "%s\n"
512 "%sStartupMemoryLow: %" PRIu64 "%s\n"
513 "%sMemoryHigh: %" PRIu64 "%s\n"
514 "%sStartupMemoryHigh: %" PRIu64 "%s\n"
515 "%sMemoryMax: %" PRIu64 "%s\n"
516 "%sStartupMemoryMax: %" PRIu64 "%s\n"
517 "%sMemorySwapMax: %" PRIu64 "%s\n"
518 "%sStartupMemorySwapMax: %" PRIu64 "%s\n"
519 "%sMemoryZSwapMax: %" PRIu64 "%s\n"
520 "%sStartupMemoryZSwapMax: %" PRIu64 "%s\n"
521 "%sMemoryLimit: %" PRIu64 "\n"
522 "%sTasksMax: %" PRIu64 "\n"
523 "%sDevicePolicy: %s\n"
524 "%sDisableControllers: %s\n"
525 "%sDelegate: %s\n"
526 "%sManagedOOMSwap: %s\n"
527 "%sManagedOOMMemoryPressure: %s\n"
528 "%sManagedOOMMemoryPressureLimit: " PERMYRIAD_AS_PERCENT_FORMAT_STR "\n"
529 "%sManagedOOMPreference: %s\n"
530 "%sMemoryPressureWatch: %s\n",
531 prefix, yes_no(c->cpu_accounting),
532 prefix, yes_no(c->io_accounting),
533 prefix, yes_no(c->blockio_accounting),
534 prefix, yes_no(c->memory_accounting),
535 prefix, yes_no(c->tasks_accounting),
536 prefix, yes_no(c->ip_accounting),
537 prefix, c->cpu_weight,
538 prefix, c->startup_cpu_weight,
539 prefix, c->cpu_shares,
540 prefix, c->startup_cpu_shares,
541 prefix, FORMAT_TIMESPAN(c->cpu_quota_per_sec_usec, 1),
542 prefix, FORMAT_TIMESPAN(c->cpu_quota_period_usec, 1),
543 prefix, strempty(cpuset_cpus),
544 prefix, strempty(startup_cpuset_cpus),
545 prefix, strempty(cpuset_mems),
546 prefix, strempty(startup_cpuset_mems),
547 prefix, c->io_weight,
548 prefix, c->startup_io_weight,
549 prefix, c->blockio_weight,
550 prefix, c->startup_blockio_weight,
551 prefix, c->default_memory_min,
552 prefix, c->default_memory_low,
553 prefix, c->memory_min, format_cgroup_memory_limit_comparison(cda, sizeof(cda), u, "MemoryMin"),
554 prefix, c->memory_low, format_cgroup_memory_limit_comparison(cdb, sizeof(cdb), u, "MemoryLow"),
555 prefix, c->startup_memory_low, format_cgroup_memory_limit_comparison(cdc, sizeof(cdc), u, "StartupMemoryLow"),
556 prefix, c->memory_high, format_cgroup_memory_limit_comparison(cdd, sizeof(cdd), u, "MemoryHigh"),
557 prefix, c->startup_memory_high, format_cgroup_memory_limit_comparison(cde, sizeof(cde), u, "StartupMemoryHigh"),
558 prefix, c->memory_max, format_cgroup_memory_limit_comparison(cdf, sizeof(cdf), u, "MemoryMax"),
559 prefix, c->startup_memory_max, format_cgroup_memory_limit_comparison(cdg, sizeof(cdg), u, "StartupMemoryMax"),
560 prefix, c->memory_swap_max, format_cgroup_memory_limit_comparison(cdh, sizeof(cdh), u, "MemorySwapMax"),
561 prefix, c->startup_memory_swap_max, format_cgroup_memory_limit_comparison(cdi, sizeof(cdi), u, "StartupMemorySwapMax"),
562 prefix, c->memory_zswap_max, format_cgroup_memory_limit_comparison(cdj, sizeof(cdj), u, "MemoryZSwapMax"),
563 prefix, c->startup_memory_zswap_max, format_cgroup_memory_limit_comparison(cdk, sizeof(cdk), u, "StartupMemoryZSwapMax"),
564 prefix, c->memory_limit,
565 prefix, tasks_max_resolve(&c->tasks_max),
566 prefix, cgroup_device_policy_to_string(c->device_policy),
567 prefix, strempty(disable_controllers_str),
568 prefix, delegate_str,
569 prefix, managed_oom_mode_to_string(c->moom_swap),
570 prefix, managed_oom_mode_to_string(c->moom_mem_pressure),
571 prefix, PERMYRIAD_AS_PERCENT_FORMAT_VAL(UINT32_SCALE_TO_PERMYRIAD(c->moom_mem_pressure_limit)),
572 prefix, managed_oom_preference_to_string(c->moom_preference),
573 prefix, cgroup_pressure_watch_to_string(c->memory_pressure_watch));
575 if (c->delegate_subgroup)
576 fprintf(f, "%sDelegateSubgroup: %s\n",
577 prefix, c->delegate_subgroup);
579 if (c->memory_pressure_threshold_usec != USEC_INFINITY)
580 fprintf(f, "%sMemoryPressureThresholdSec: %s\n",
581 prefix, FORMAT_TIMESPAN(c->memory_pressure_threshold_usec, 1));
583 LIST_FOREACH(device_allow, a, c->device_allow)
584 fprintf(f,
585 "%sDeviceAllow: %s %s%s%s\n",
586 prefix,
587 a->path,
588 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
590 LIST_FOREACH(device_weights, iw, c->io_device_weights)
591 fprintf(f,
592 "%sIODeviceWeight: %s %" PRIu64 "\n",
593 prefix,
594 iw->path,
595 iw->weight);
597 LIST_FOREACH(device_latencies, l, c->io_device_latencies)
598 fprintf(f,
599 "%sIODeviceLatencyTargetSec: %s %s\n",
600 prefix,
601 l->path,
602 FORMAT_TIMESPAN(l->target_usec, 1));
604 LIST_FOREACH(device_limits, il, c->io_device_limits)
605 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
606 if (il->limits[type] != cgroup_io_limit_defaults[type])
607 fprintf(f,
608 "%s%s: %s %s\n",
609 prefix,
610 cgroup_io_limit_type_to_string(type),
611 il->path,
612 FORMAT_BYTES(il->limits[type]));
614 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
615 fprintf(f,
616 "%sBlockIODeviceWeight: %s %" PRIu64,
617 prefix,
618 w->path,
619 w->weight);
621 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
622 if (b->rbps != CGROUP_LIMIT_MAX)
623 fprintf(f,
624 "%sBlockIOReadBandwidth: %s %s\n",
625 prefix,
626 b->path,
627 FORMAT_BYTES(b->rbps));
628 if (b->wbps != CGROUP_LIMIT_MAX)
629 fprintf(f,
630 "%sBlockIOWriteBandwidth: %s %s\n",
631 prefix,
632 b->path,
633 FORMAT_BYTES(b->wbps));
636 SET_FOREACH(iaai, c->ip_address_allow)
637 fprintf(f, "%sIPAddressAllow: %s\n", prefix,
638 IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
639 SET_FOREACH(iaai, c->ip_address_deny)
640 fprintf(f, "%sIPAddressDeny: %s\n", prefix,
641 IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
643 STRV_FOREACH(path, c->ip_filters_ingress)
644 fprintf(f, "%sIPIngressFilterPath: %s\n", prefix, *path);
645 STRV_FOREACH(path, c->ip_filters_egress)
646 fprintf(f, "%sIPEgressFilterPath: %s\n", prefix, *path);
648 LIST_FOREACH(programs, p, c->bpf_foreign_programs)
649 fprintf(f, "%sBPFProgram: %s:%s",
650 prefix, bpf_cgroup_attach_type_to_string(p->attach_type), p->bpffs_path);
652 if (c->socket_bind_allow) {
653 fprintf(f, "%sSocketBindAllow: ", prefix);
654 cgroup_context_dump_socket_bind_items(c->socket_bind_allow, f);
655 fputc('\n', f);
658 if (c->socket_bind_deny) {
659 fprintf(f, "%sSocketBindDeny: ", prefix);
660 cgroup_context_dump_socket_bind_items(c->socket_bind_deny, f);
661 fputc('\n', f);
664 if (c->restrict_network_interfaces) {
665 char *iface;
666 SET_FOREACH(iface, c->restrict_network_interfaces)
667 fprintf(f, "%sRestrictNetworkInterfaces: %s\n", prefix, iface);
671 void cgroup_context_dump_socket_bind_item(const CGroupSocketBindItem *item, FILE *f) {
672 const char *family, *colon1, *protocol = "", *colon2 = "";
674 family = strempty(af_to_ipv4_ipv6(item->address_family));
675 colon1 = isempty(family) ? "" : ":";
677 if (item->ip_protocol != 0) {
678 protocol = ip_protocol_to_tcp_udp(item->ip_protocol);
679 colon2 = ":";
682 if (item->nr_ports == 0)
683 fprintf(f, "%s%s%s%sany", family, colon1, protocol, colon2);
684 else if (item->nr_ports == 1)
685 fprintf(f, "%s%s%s%s%" PRIu16, family, colon1, protocol, colon2, item->port_min);
686 else {
687 uint16_t port_max = item->port_min + item->nr_ports - 1;
688 fprintf(f, "%s%s%s%s%" PRIu16 "-%" PRIu16, family, colon1, protocol, colon2,
689 item->port_min, port_max);
693 void cgroup_context_dump_socket_bind_items(const CGroupSocketBindItem *items, FILE *f) {
694 bool first = true;
696 LIST_FOREACH(socket_bind_items, bi, items) {
697 if (first)
698 first = false;
699 else
700 fputc(' ', f);
702 cgroup_context_dump_socket_bind_item(bi, f);
706 int cgroup_add_device_allow(CGroupContext *c, const char *dev, const char *mode) {
707 _cleanup_free_ CGroupDeviceAllow *a = NULL;
708 _cleanup_free_ char *d = NULL;
710 assert(c);
711 assert(dev);
712 assert(isempty(mode) || in_charset(mode, "rwm"));
714 a = new(CGroupDeviceAllow, 1);
715 if (!a)
716 return -ENOMEM;
718 d = strdup(dev);
719 if (!d)
720 return -ENOMEM;
722 *a = (CGroupDeviceAllow) {
723 .path = TAKE_PTR(d),
724 .r = isempty(mode) || strchr(mode, 'r'),
725 .w = isempty(mode) || strchr(mode, 'w'),
726 .m = isempty(mode) || strchr(mode, 'm'),
729 LIST_PREPEND(device_allow, c->device_allow, a);
730 TAKE_PTR(a);
732 return 0;
735 int cgroup_add_bpf_foreign_program(CGroupContext *c, uint32_t attach_type, const char *bpffs_path) {
736 CGroupBPFForeignProgram *p;
737 _cleanup_free_ char *d = NULL;
739 assert(c);
740 assert(bpffs_path);
742 if (!path_is_normalized(bpffs_path) || !path_is_absolute(bpffs_path))
743 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not normalized: %m");
745 d = strdup(bpffs_path);
746 if (!d)
747 return log_oom();
749 p = new(CGroupBPFForeignProgram, 1);
750 if (!p)
751 return log_oom();
753 *p = (CGroupBPFForeignProgram) {
754 .attach_type = attach_type,
755 .bpffs_path = TAKE_PTR(d),
758 LIST_PREPEND(programs, c->bpf_foreign_programs, TAKE_PTR(p));
760 return 0;
763 #define UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(entry) \
764 uint64_t unit_get_ancestor_##entry(Unit *u) { \
765 CGroupContext *c; \
767 /* 1. Is entry set in this unit? If so, use that. \
768 * 2. Is the default for this entry set in any \
769 * ancestor? If so, use that. \
770 * 3. Otherwise, return CGROUP_LIMIT_MIN. */ \
772 assert(u); \
774 c = unit_get_cgroup_context(u); \
775 if (c && c->entry##_set) \
776 return c->entry; \
778 while ((u = UNIT_GET_SLICE(u))) { \
779 c = unit_get_cgroup_context(u); \
780 if (c && c->default_##entry##_set) \
781 return c->default_##entry; \
784 /* We've reached the root, but nobody had default for \
785 * this entry set, so set it to the kernel default. */ \
786 return CGROUP_LIMIT_MIN; \
789 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_low);
790 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(startup_memory_low);
791 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_min);
793 static void unit_set_xattr_graceful(Unit *u, const char *cgroup_path, const char *name, const void *data, size_t size) {
794 int r;
796 assert(u);
797 assert(name);
799 if (!cgroup_path) {
800 if (!u->cgroup_path)
801 return;
803 cgroup_path = u->cgroup_path;
806 r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, cgroup_path, name, data, size, 0);
807 if (r < 0)
808 log_unit_debug_errno(u, r, "Failed to set '%s' xattr on control group %s, ignoring: %m", name, empty_to_root(cgroup_path));
811 static void unit_remove_xattr_graceful(Unit *u, const char *cgroup_path, const char *name) {
812 int r;
814 assert(u);
815 assert(name);
817 if (!cgroup_path) {
818 if (!u->cgroup_path)
819 return;
821 cgroup_path = u->cgroup_path;
824 r = cg_remove_xattr(SYSTEMD_CGROUP_CONTROLLER, cgroup_path, name);
825 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
826 log_unit_debug_errno(u, r, "Failed to remove '%s' xattr flag on control group %s, ignoring: %m", name, empty_to_root(cgroup_path));
829 void cgroup_oomd_xattr_apply(Unit *u, const char *cgroup_path) {
830 CGroupContext *c;
832 assert(u);
834 c = unit_get_cgroup_context(u);
835 if (!c)
836 return;
838 if (c->moom_preference == MANAGED_OOM_PREFERENCE_OMIT)
839 unit_set_xattr_graceful(u, cgroup_path, "user.oomd_omit", "1", 1);
841 if (c->moom_preference == MANAGED_OOM_PREFERENCE_AVOID)
842 unit_set_xattr_graceful(u, cgroup_path, "user.oomd_avoid", "1", 1);
844 if (c->moom_preference != MANAGED_OOM_PREFERENCE_AVOID)
845 unit_remove_xattr_graceful(u, cgroup_path, "user.oomd_avoid");
847 if (c->moom_preference != MANAGED_OOM_PREFERENCE_OMIT)
848 unit_remove_xattr_graceful(u, cgroup_path, "user.oomd_omit");
851 int cgroup_log_xattr_apply(Unit *u, const char *cgroup_path) {
852 ExecContext *c;
853 size_t len, allowed_patterns_len, denied_patterns_len;
854 _cleanup_free_ char *patterns = NULL, *allowed_patterns = NULL, *denied_patterns = NULL;
855 char *last;
856 int r;
858 assert(u);
860 c = unit_get_exec_context(u);
861 if (!c)
862 /* Some unit types have a cgroup context but no exec context, so we do not log
863 * any error here to avoid confusion. */
864 return 0;
866 if (set_isempty(c->log_filter_allowed_patterns) && set_isempty(c->log_filter_denied_patterns)) {
867 unit_remove_xattr_graceful(u, cgroup_path, "user.journald_log_filter_patterns");
868 return 0;
871 r = set_make_nulstr(c->log_filter_allowed_patterns, &allowed_patterns, &allowed_patterns_len);
872 if (r < 0)
873 return log_debug_errno(r, "Failed to make nulstr from set: %m");
875 r = set_make_nulstr(c->log_filter_denied_patterns, &denied_patterns, &denied_patterns_len);
876 if (r < 0)
877 return log_debug_errno(r, "Failed to make nulstr from set: %m");
879 /* Use nul character separated strings without trailing nul */
880 allowed_patterns_len = LESS_BY(allowed_patterns_len, 1u);
881 denied_patterns_len = LESS_BY(denied_patterns_len, 1u);
883 len = allowed_patterns_len + 1 + denied_patterns_len;
884 patterns = new(char, len);
885 if (!patterns)
886 return log_oom_debug();
888 last = mempcpy_safe(patterns, allowed_patterns, allowed_patterns_len);
889 *(last++) = '\xff';
890 memcpy_safe(last, denied_patterns, denied_patterns_len);
892 unit_set_xattr_graceful(u, cgroup_path, "user.journald_log_filter_patterns", patterns, len);
894 return 0;
897 static void cgroup_xattr_apply(Unit *u) {
898 bool b;
900 assert(u);
902 /* The 'user.*' xattrs can be set from a user manager. */
903 cgroup_oomd_xattr_apply(u, u->cgroup_path);
904 cgroup_log_xattr_apply(u, u->cgroup_path);
906 if (!MANAGER_IS_SYSTEM(u->manager))
907 return;
909 b = !sd_id128_is_null(u->invocation_id);
910 FOREACH_STRING(xn, "trusted.invocation_id", "user.invocation_id") {
911 if (b)
912 unit_set_xattr_graceful(u, NULL, xn, SD_ID128_TO_STRING(u->invocation_id), 32);
913 else
914 unit_remove_xattr_graceful(u, NULL, xn);
917 /* Indicate on the cgroup whether delegation is on, via an xattr. This is best-effort, as old kernels
918 * didn't support xattrs on cgroups at all. Later they got support for setting 'trusted.*' xattrs,
919 * and even later 'user.*' xattrs. We started setting this field when 'trusted.*' was added, and
920 * given this is now pretty much API, let's continue to support that. But also set 'user.*' as well,
921 * since it is readable by any user, not just CAP_SYS_ADMIN. This hence comes with slightly weaker
922 * security (as users who got delegated cgroups could turn it off if they like), but this shouldn't
923 * be a big problem given this communicates delegation state to clients, but the manager never reads
924 * it. */
925 b = unit_cgroup_delegate(u);
926 FOREACH_STRING(xn, "trusted.delegate", "user.delegate") {
927 if (b)
928 unit_set_xattr_graceful(u, NULL, xn, "1", 1);
929 else
930 unit_remove_xattr_graceful(u, NULL, xn);
934 static int lookup_block_device(const char *p, dev_t *ret) {
935 dev_t rdev, dev = 0;
936 mode_t mode;
937 int r;
939 assert(p);
940 assert(ret);
942 r = device_path_parse_major_minor(p, &mode, &rdev);
943 if (r == -ENODEV) { /* not a parsable device node, need to go to disk */
944 struct stat st;
946 if (stat(p, &st) < 0)
947 return log_warning_errno(errno, "Couldn't stat device '%s': %m", p);
949 mode = st.st_mode;
950 rdev = st.st_rdev;
951 dev = st.st_dev;
952 } else if (r < 0)
953 return log_warning_errno(r, "Failed to parse major/minor from path '%s': %m", p);
955 if (S_ISCHR(mode))
956 return log_warning_errno(SYNTHETIC_ERRNO(ENOTBLK),
957 "Device node '%s' is a character device, but block device needed.", p);
958 if (S_ISBLK(mode))
959 *ret = rdev;
960 else if (major(dev) != 0)
961 *ret = dev; /* If this is not a device node then use the block device this file is stored on */
962 else {
963 /* If this is btrfs, getting the backing block device is a bit harder */
964 r = btrfs_get_block_device(p, ret);
965 if (r == -ENOTTY)
966 return log_warning_errno(SYNTHETIC_ERRNO(ENODEV),
967 "'%s' is not a block device node, and file system block device cannot be determined or is not local.", p);
968 if (r < 0)
969 return log_warning_errno(r, "Failed to determine block device backing btrfs file system '%s': %m", p);
972 /* If this is a LUKS/DM device, recursively try to get the originating block device */
973 while (block_get_originating(*ret, ret) > 0);
975 /* If this is a partition, try to get the originating block device */
976 (void) block_get_whole_disk(*ret, ret);
977 return 0;
980 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
981 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
982 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
985 static bool cgroup_context_has_cpu_shares(CGroupContext *c) {
986 return c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
987 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID;
990 static bool cgroup_context_has_allowed_cpus(CGroupContext *c) {
991 return c->cpuset_cpus.set || c->startup_cpuset_cpus.set;
994 static bool cgroup_context_has_allowed_mems(CGroupContext *c) {
995 return c->cpuset_mems.set || c->startup_cpuset_mems.set;
998 static uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
999 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1000 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
1001 return c->startup_cpu_weight;
1002 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
1003 return c->cpu_weight;
1004 else
1005 return CGROUP_WEIGHT_DEFAULT;
1008 static uint64_t cgroup_context_cpu_shares(CGroupContext *c, ManagerState state) {
1009 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1010 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID)
1011 return c->startup_cpu_shares;
1012 else if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID)
1013 return c->cpu_shares;
1014 else
1015 return CGROUP_CPU_SHARES_DEFAULT;
1018 static CPUSet *cgroup_context_allowed_cpus(CGroupContext *c, ManagerState state) {
1019 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1020 c->startup_cpuset_cpus.set)
1021 return &c->startup_cpuset_cpus;
1022 else
1023 return &c->cpuset_cpus;
1026 static CPUSet *cgroup_context_allowed_mems(CGroupContext *c, ManagerState state) {
1027 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1028 c->startup_cpuset_mems.set)
1029 return &c->startup_cpuset_mems;
1030 else
1031 return &c->cpuset_mems;
1034 usec_t cgroup_cpu_adjust_period(usec_t period, usec_t quota, usec_t resolution, usec_t max_period) {
1035 /* kernel uses a minimum resolution of 1ms, so both period and (quota * period)
1036 * need to be higher than that boundary. quota is specified in USecPerSec.
1037 * Additionally, period must be at most max_period. */
1038 assert(quota > 0);
1040 return MIN(MAX3(period, resolution, resolution * USEC_PER_SEC / quota), max_period);
1043 static usec_t cgroup_cpu_adjust_period_and_log(Unit *u, usec_t period, usec_t quota) {
1044 usec_t new_period;
1046 if (quota == USEC_INFINITY)
1047 /* Always use default period for infinity quota. */
1048 return CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
1050 if (period == USEC_INFINITY)
1051 /* Default period was requested. */
1052 period = CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
1054 /* Clamp to interval [1ms, 1s] */
1055 new_period = cgroup_cpu_adjust_period(period, quota, USEC_PER_MSEC, USEC_PER_SEC);
1057 if (new_period != period) {
1058 log_unit_full(u, u->warned_clamping_cpu_quota_period ? LOG_DEBUG : LOG_WARNING,
1059 "Clamping CPU interval for cpu.max: period is now %s",
1060 FORMAT_TIMESPAN(new_period, 1));
1061 u->warned_clamping_cpu_quota_period = true;
1064 return new_period;
1067 static void cgroup_apply_unified_cpu_weight(Unit *u, uint64_t weight) {
1068 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1070 if (weight == CGROUP_WEIGHT_IDLE)
1071 return;
1072 xsprintf(buf, "%" PRIu64 "\n", weight);
1073 (void) set_attribute_and_warn(u, "cpu", "cpu.weight", buf);
1076 static void cgroup_apply_unified_cpu_idle(Unit *u, uint64_t weight) {
1077 int r;
1078 bool is_idle;
1079 const char *idle_val;
1081 is_idle = weight == CGROUP_WEIGHT_IDLE;
1082 idle_val = one_zero(is_idle);
1083 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.idle", idle_val);
1084 if (r < 0 && (r != -ENOENT || is_idle))
1085 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to set '%s' attribute on '%s' to '%s': %m",
1086 "cpu.idle", empty_to_root(u->cgroup_path), idle_val);
1089 static void cgroup_apply_unified_cpu_quota(Unit *u, usec_t quota, usec_t period) {
1090 char buf[(DECIMAL_STR_MAX(usec_t) + 1) * 2 + 1];
1092 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
1093 if (quota != USEC_INFINITY)
1094 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
1095 MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC), period);
1096 else
1097 xsprintf(buf, "max " USEC_FMT "\n", period);
1098 (void) set_attribute_and_warn(u, "cpu", "cpu.max", buf);
1101 static void cgroup_apply_legacy_cpu_shares(Unit *u, uint64_t shares) {
1102 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1104 xsprintf(buf, "%" PRIu64 "\n", shares);
1105 (void) set_attribute_and_warn(u, "cpu", "cpu.shares", buf);
1108 static void cgroup_apply_legacy_cpu_quota(Unit *u, usec_t quota, usec_t period) {
1109 char buf[DECIMAL_STR_MAX(usec_t) + 2];
1111 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
1113 xsprintf(buf, USEC_FMT "\n", period);
1114 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_period_us", buf);
1116 if (quota != USEC_INFINITY) {
1117 xsprintf(buf, USEC_FMT "\n", MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC));
1118 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", buf);
1119 } else
1120 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", "-1\n");
1123 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares) {
1124 return CLAMP(shares * CGROUP_WEIGHT_DEFAULT / CGROUP_CPU_SHARES_DEFAULT,
1125 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
1128 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight) {
1129 /* we don't support idle in cgroupv1 */
1130 if (weight == CGROUP_WEIGHT_IDLE)
1131 return CGROUP_CPU_SHARES_MIN;
1133 return CLAMP(weight * CGROUP_CPU_SHARES_DEFAULT / CGROUP_WEIGHT_DEFAULT,
1134 CGROUP_CPU_SHARES_MIN, CGROUP_CPU_SHARES_MAX);
1137 static void cgroup_apply_unified_cpuset(Unit *u, const CPUSet *cpus, const char *name) {
1138 _cleanup_free_ char *buf = NULL;
1140 buf = cpu_set_to_range_string(cpus);
1141 if (!buf) {
1142 log_oom();
1143 return;
1146 (void) set_attribute_and_warn(u, "cpuset", name, buf);
1149 static bool cgroup_context_has_io_config(CGroupContext *c) {
1150 return c->io_accounting ||
1151 c->io_weight != CGROUP_WEIGHT_INVALID ||
1152 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
1153 c->io_device_weights ||
1154 c->io_device_latencies ||
1155 c->io_device_limits;
1158 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
1159 return c->blockio_accounting ||
1160 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
1161 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
1162 c->blockio_device_weights ||
1163 c->blockio_device_bandwidths;
1166 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
1167 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1168 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
1169 return c->startup_io_weight;
1170 if (c->io_weight != CGROUP_WEIGHT_INVALID)
1171 return c->io_weight;
1172 return CGROUP_WEIGHT_DEFAULT;
1175 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
1176 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1177 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
1178 return c->startup_blockio_weight;
1179 if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
1180 return c->blockio_weight;
1181 return CGROUP_BLKIO_WEIGHT_DEFAULT;
1184 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
1185 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
1186 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
1189 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
1190 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
1191 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
1194 static int set_bfq_weight(Unit *u, const char *controller, dev_t dev, uint64_t io_weight) {
1195 static const char * const prop_names[] = {
1196 "IOWeight",
1197 "BlockIOWeight",
1198 "IODeviceWeight",
1199 "BlockIODeviceWeight",
1201 static bool warned = false;
1202 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+STRLEN("\n")];
1203 const char *p;
1204 uint64_t bfq_weight;
1205 int r;
1207 /* FIXME: drop this function when distro kernels properly support BFQ through "io.weight"
1208 * See also: https://github.com/systemd/systemd/pull/13335 and
1209 * https://github.com/torvalds/linux/commit/65752aef0a407e1ef17ec78a7fc31ba4e0b360f9. */
1210 p = strjoina(controller, ".bfq.weight");
1211 /* Adjust to kernel range is 1..1000, the default is 100. */
1212 bfq_weight = BFQ_WEIGHT(io_weight);
1214 if (major(dev) > 0)
1215 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), bfq_weight);
1216 else
1217 xsprintf(buf, "%" PRIu64 "\n", bfq_weight);
1219 r = cg_set_attribute(controller, u->cgroup_path, p, buf);
1221 /* FIXME: drop this when kernels prior
1222 * 795fe54c2a82 ("bfq: Add per-device weight") v5.4
1223 * are not interesting anymore. Old kernels will fail with EINVAL, while new kernels won't return
1224 * EINVAL on properly formatted input by us. Treat EINVAL accordingly. */
1225 if (r == -EINVAL && major(dev) > 0) {
1226 if (!warned) {
1227 log_unit_warning(u, "Kernel version does not accept per-device setting in %s.", p);
1228 warned = true;
1230 r = -EOPNOTSUPP; /* mask as unconfigured device */
1231 } else if (r >= 0 && io_weight != bfq_weight)
1232 log_unit_debug(u, "%s=%" PRIu64 " scaled to %s=%" PRIu64,
1233 prop_names[2*(major(dev) > 0) + streq(controller, "blkio")],
1234 io_weight, p, bfq_weight);
1235 return r;
1238 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
1239 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1240 dev_t dev;
1241 int r, r1, r2;
1243 if (lookup_block_device(dev_path, &dev) < 0)
1244 return;
1246 r1 = set_bfq_weight(u, "io", dev, io_weight);
1248 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), io_weight);
1249 r2 = cg_set_attribute("io", u->cgroup_path, "io.weight", buf);
1251 /* Look at the configured device, when both fail, prefer io.weight errno. */
1252 r = r2 == -EOPNOTSUPP ? r1 : r2;
1254 if (r < 0)
1255 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r),
1256 r, "Failed to set 'io[.bfq].weight' attribute on '%s' to '%.*s': %m",
1257 empty_to_root(u->cgroup_path), (int) strcspn(buf, NEWLINE), buf);
1260 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
1261 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1262 dev_t dev;
1263 int r;
1265 r = lookup_block_device(dev_path, &dev);
1266 if (r < 0)
1267 return;
1269 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), blkio_weight);
1270 (void) set_attribute_and_warn(u, "blkio", "blkio.weight_device", buf);
1273 static void cgroup_apply_io_device_latency(Unit *u, const char *dev_path, usec_t target) {
1274 char buf[DECIMAL_STR_MAX(dev_t)*2+2+7+DECIMAL_STR_MAX(uint64_t)+1];
1275 dev_t dev;
1276 int r;
1278 r = lookup_block_device(dev_path, &dev);
1279 if (r < 0)
1280 return;
1282 if (target != USEC_INFINITY)
1283 xsprintf(buf, DEVNUM_FORMAT_STR " target=%" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), target);
1284 else
1285 xsprintf(buf, DEVNUM_FORMAT_STR " target=max\n", DEVNUM_FORMAT_VAL(dev));
1287 (void) set_attribute_and_warn(u, "io", "io.latency", buf);
1290 static void cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
1291 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)],
1292 buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
1293 dev_t dev;
1295 if (lookup_block_device(dev_path, &dev) < 0)
1296 return;
1298 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
1299 if (limits[type] != cgroup_io_limit_defaults[type])
1300 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
1301 else
1302 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
1304 xsprintf(buf, DEVNUM_FORMAT_STR " rbps=%s wbps=%s riops=%s wiops=%s\n", DEVNUM_FORMAT_VAL(dev),
1305 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
1306 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
1307 (void) set_attribute_and_warn(u, "io", "io.max", buf);
1310 static void cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
1311 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1312 dev_t dev;
1314 if (lookup_block_device(dev_path, &dev) < 0)
1315 return;
1317 sprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), rbps);
1318 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.read_bps_device", buf);
1320 sprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), wbps);
1321 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.write_bps_device", buf);
1324 static bool unit_has_unified_memory_config(Unit *u) {
1325 CGroupContext *c;
1327 assert(u);
1329 assert_se(c = unit_get_cgroup_context(u));
1331 return unit_get_ancestor_memory_min(u) > 0 ||
1332 unit_get_ancestor_memory_low(u) > 0 || unit_get_ancestor_startup_memory_low(u) > 0 ||
1333 c->memory_high != CGROUP_LIMIT_MAX || c->startup_memory_high_set ||
1334 c->memory_max != CGROUP_LIMIT_MAX || c->startup_memory_max_set ||
1335 c->memory_swap_max != CGROUP_LIMIT_MAX || c->startup_memory_swap_max_set ||
1336 c->memory_zswap_max != CGROUP_LIMIT_MAX || c->startup_memory_zswap_max_set;
1339 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
1340 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max\n";
1342 if (v != CGROUP_LIMIT_MAX)
1343 xsprintf(buf, "%" PRIu64 "\n", v);
1345 (void) set_attribute_and_warn(u, "memory", file, buf);
1348 static void cgroup_apply_firewall(Unit *u) {
1349 assert(u);
1351 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
1353 if (bpf_firewall_compile(u) < 0)
1354 return;
1356 (void) bpf_firewall_load_custom(u);
1357 (void) bpf_firewall_install(u);
1360 static void cgroup_apply_socket_bind(Unit *u) {
1361 assert(u);
1363 (void) bpf_socket_bind_install(u);
1366 static void cgroup_apply_restrict_network_interfaces(Unit *u) {
1367 assert(u);
1369 (void) restrict_network_interfaces_install(u);
1372 static int cgroup_apply_devices(Unit *u) {
1373 _cleanup_(bpf_program_freep) BPFProgram *prog = NULL;
1374 const char *path;
1375 CGroupContext *c;
1376 CGroupDevicePolicy policy;
1377 int r;
1379 assert_se(c = unit_get_cgroup_context(u));
1380 assert_se(path = u->cgroup_path);
1382 policy = c->device_policy;
1384 if (cg_all_unified() > 0) {
1385 r = bpf_devices_cgroup_init(&prog, policy, c->device_allow);
1386 if (r < 0)
1387 return log_unit_warning_errno(u, r, "Failed to initialize device control bpf program: %m");
1389 } else {
1390 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore
1391 * EINVAL here. */
1393 if (c->device_allow || policy != CGROUP_DEVICE_POLICY_AUTO)
1394 r = cg_set_attribute("devices", path, "devices.deny", "a");
1395 else
1396 r = cg_set_attribute("devices", path, "devices.allow", "a");
1397 if (r < 0)
1398 log_unit_full_errno(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING, r,
1399 "Failed to reset devices.allow/devices.deny: %m");
1402 bool allow_list_static = policy == CGROUP_DEVICE_POLICY_CLOSED ||
1403 (policy == CGROUP_DEVICE_POLICY_AUTO && c->device_allow);
1404 if (allow_list_static)
1405 (void) bpf_devices_allow_list_static(prog, path);
1407 bool any = allow_list_static;
1408 LIST_FOREACH(device_allow, a, c->device_allow) {
1409 char acc[4], *val;
1410 unsigned k = 0;
1412 if (a->r)
1413 acc[k++] = 'r';
1414 if (a->w)
1415 acc[k++] = 'w';
1416 if (a->m)
1417 acc[k++] = 'm';
1418 if (k == 0)
1419 continue;
1420 acc[k++] = 0;
1422 if (path_startswith(a->path, "/dev/"))
1423 r = bpf_devices_allow_list_device(prog, path, a->path, acc);
1424 else if ((val = startswith(a->path, "block-")))
1425 r = bpf_devices_allow_list_major(prog, path, val, 'b', acc);
1426 else if ((val = startswith(a->path, "char-")))
1427 r = bpf_devices_allow_list_major(prog, path, val, 'c', acc);
1428 else {
1429 log_unit_debug(u, "Ignoring device '%s' while writing cgroup attribute.", a->path);
1430 continue;
1433 if (r >= 0)
1434 any = true;
1437 if (prog && !any) {
1438 log_unit_warning_errno(u, SYNTHETIC_ERRNO(ENODEV), "No devices matched by device filter.");
1440 /* The kernel verifier would reject a program we would build with the normal intro and outro
1441 but no allow-listing rules (outro would contain an unreachable instruction for successful
1442 return). */
1443 policy = CGROUP_DEVICE_POLICY_STRICT;
1446 r = bpf_devices_apply_policy(&prog, policy, any, path, &u->bpf_device_control_installed);
1447 if (r < 0) {
1448 static bool warned = false;
1450 log_full_errno(warned ? LOG_DEBUG : LOG_WARNING, r,
1451 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1452 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1453 "(This warning is only shown for the first loaded unit using device ACL.)", u->id);
1455 warned = true;
1457 return r;
1460 static void set_io_weight(Unit *u, uint64_t weight) {
1461 char buf[STRLEN("default \n")+DECIMAL_STR_MAX(uint64_t)];
1463 assert(u);
1465 (void) set_bfq_weight(u, "io", makedev(0, 0), weight);
1467 xsprintf(buf, "default %" PRIu64 "\n", weight);
1468 (void) set_attribute_and_warn(u, "io", "io.weight", buf);
1471 static void set_blkio_weight(Unit *u, uint64_t weight) {
1472 char buf[STRLEN("\n")+DECIMAL_STR_MAX(uint64_t)];
1474 assert(u);
1476 (void) set_bfq_weight(u, "blkio", makedev(0, 0), weight);
1478 xsprintf(buf, "%" PRIu64 "\n", weight);
1479 (void) set_attribute_and_warn(u, "blkio", "blkio.weight", buf);
1482 static void cgroup_apply_bpf_foreign_program(Unit *u) {
1483 assert(u);
1485 (void) bpf_foreign_install(u);
1488 static void cgroup_context_apply(
1489 Unit *u,
1490 CGroupMask apply_mask,
1491 ManagerState state) {
1493 const char *path;
1494 CGroupContext *c;
1495 bool is_host_root, is_local_root;
1496 int r;
1498 assert(u);
1500 /* Nothing to do? Exit early! */
1501 if (apply_mask == 0)
1502 return;
1504 /* Some cgroup attributes are not supported on the host root cgroup, hence silently ignore them here. And other
1505 * attributes should only be managed for cgroups further down the tree. */
1506 is_local_root = unit_has_name(u, SPECIAL_ROOT_SLICE);
1507 is_host_root = unit_has_host_root_cgroup(u);
1509 assert_se(c = unit_get_cgroup_context(u));
1510 assert_se(path = u->cgroup_path);
1512 if (is_local_root) /* Make sure we don't try to display messages with an empty path. */
1513 path = "/";
1515 /* We generally ignore errors caused by read-only mounted cgroup trees (assuming we are running in a container
1516 * then), and missing cgroups, i.e. EROFS and ENOENT. */
1518 /* In fully unified mode these attributes don't exist on the host cgroup root. On legacy the weights exist, but
1519 * setting the weight makes very little sense on the host root cgroup, as there are no other cgroups at this
1520 * level. The quota exists there too, but any attempt to write to it is refused with EINVAL. Inside of
1521 * containers we want to leave control of these to the container manager (and if cgroup v2 delegation is used
1522 * we couldn't even write to them if we wanted to). */
1523 if ((apply_mask & CGROUP_MASK_CPU) && !is_local_root) {
1525 if (cg_all_unified() > 0) {
1526 uint64_t weight;
1528 if (cgroup_context_has_cpu_weight(c))
1529 weight = cgroup_context_cpu_weight(c, state);
1530 else if (cgroup_context_has_cpu_shares(c)) {
1531 uint64_t shares;
1533 shares = cgroup_context_cpu_shares(c, state);
1534 weight = cgroup_cpu_shares_to_weight(shares);
1536 log_cgroup_compat(u, "Applying [Startup]CPUShares=%" PRIu64 " as [Startup]CPUWeight=%" PRIu64 " on %s",
1537 shares, weight, path);
1538 } else
1539 weight = CGROUP_WEIGHT_DEFAULT;
1541 cgroup_apply_unified_cpu_idle(u, weight);
1542 cgroup_apply_unified_cpu_weight(u, weight);
1543 cgroup_apply_unified_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
1545 } else {
1546 uint64_t shares;
1548 if (cgroup_context_has_cpu_weight(c)) {
1549 uint64_t weight;
1551 weight = cgroup_context_cpu_weight(c, state);
1552 shares = cgroup_cpu_weight_to_shares(weight);
1554 log_cgroup_compat(u, "Applying [Startup]CPUWeight=%" PRIu64 " as [Startup]CPUShares=%" PRIu64 " on %s",
1555 weight, shares, path);
1556 } else if (cgroup_context_has_cpu_shares(c))
1557 shares = cgroup_context_cpu_shares(c, state);
1558 else
1559 shares = CGROUP_CPU_SHARES_DEFAULT;
1561 cgroup_apply_legacy_cpu_shares(u, shares);
1562 cgroup_apply_legacy_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
1566 if ((apply_mask & CGROUP_MASK_CPUSET) && !is_local_root) {
1567 cgroup_apply_unified_cpuset(u, cgroup_context_allowed_cpus(c, state), "cpuset.cpus");
1568 cgroup_apply_unified_cpuset(u, cgroup_context_allowed_mems(c, state), "cpuset.mems");
1571 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroup v2
1572 * controller), and in case of containers we want to leave control of these attributes to the container manager
1573 * (and we couldn't access that stuff anyway, even if we tried if proper delegation is used). */
1574 if ((apply_mask & CGROUP_MASK_IO) && !is_local_root) {
1575 bool has_io, has_blockio;
1576 uint64_t weight;
1578 has_io = cgroup_context_has_io_config(c);
1579 has_blockio = cgroup_context_has_blockio_config(c);
1581 if (has_io)
1582 weight = cgroup_context_io_weight(c, state);
1583 else if (has_blockio) {
1584 uint64_t blkio_weight;
1586 blkio_weight = cgroup_context_blkio_weight(c, state);
1587 weight = cgroup_weight_blkio_to_io(blkio_weight);
1589 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight=%" PRIu64 " as [Startup]IOWeight=%" PRIu64,
1590 blkio_weight, weight);
1591 } else
1592 weight = CGROUP_WEIGHT_DEFAULT;
1594 set_io_weight(u, weight);
1596 if (has_io) {
1597 LIST_FOREACH(device_weights, w, c->io_device_weights)
1598 cgroup_apply_io_device_weight(u, w->path, w->weight);
1600 LIST_FOREACH(device_limits, limit, c->io_device_limits)
1601 cgroup_apply_io_device_limit(u, limit->path, limit->limits);
1603 LIST_FOREACH(device_latencies, latency, c->io_device_latencies)
1604 cgroup_apply_io_device_latency(u, latency->path, latency->target_usec);
1606 } else if (has_blockio) {
1607 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
1608 weight = cgroup_weight_blkio_to_io(w->weight);
1610 log_cgroup_compat(u, "Applying BlockIODeviceWeight=%" PRIu64 " as IODeviceWeight=%" PRIu64 " for %s",
1611 w->weight, weight, w->path);
1613 cgroup_apply_io_device_weight(u, w->path, weight);
1616 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
1617 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
1619 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
1620 limits[type] = cgroup_io_limit_defaults[type];
1622 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
1623 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
1625 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax= for %s",
1626 b->rbps, b->wbps, b->path);
1628 cgroup_apply_io_device_limit(u, b->path, limits);
1633 if (apply_mask & CGROUP_MASK_BLKIO) {
1634 bool has_io, has_blockio;
1636 has_io = cgroup_context_has_io_config(c);
1637 has_blockio = cgroup_context_has_blockio_config(c);
1639 /* Applying a 'weight' never makes sense for the host root cgroup, and for containers this should be
1640 * left to our container manager, too. */
1641 if (!is_local_root) {
1642 uint64_t weight;
1644 if (has_io) {
1645 uint64_t io_weight;
1647 io_weight = cgroup_context_io_weight(c, state);
1648 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
1650 log_cgroup_compat(u, "Applying [Startup]IOWeight=%" PRIu64 " as [Startup]BlockIOWeight=%" PRIu64,
1651 io_weight, weight);
1652 } else if (has_blockio)
1653 weight = cgroup_context_blkio_weight(c, state);
1654 else
1655 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
1657 set_blkio_weight(u, weight);
1659 if (has_io)
1660 LIST_FOREACH(device_weights, w, c->io_device_weights) {
1661 weight = cgroup_weight_io_to_blkio(w->weight);
1663 log_cgroup_compat(u, "Applying IODeviceWeight=%" PRIu64 " as BlockIODeviceWeight=%" PRIu64 " for %s",
1664 w->weight, weight, w->path);
1666 cgroup_apply_blkio_device_weight(u, w->path, weight);
1668 else if (has_blockio)
1669 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
1670 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
1673 /* The bandwidth limits are something that make sense to be applied to the host's root but not container
1674 * roots, as there we want the container manager to handle it */
1675 if (is_host_root || !is_local_root) {
1676 if (has_io)
1677 LIST_FOREACH(device_limits, l, c->io_device_limits) {
1678 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax= for %s",
1679 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
1681 cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]);
1683 else if (has_blockio)
1684 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
1685 cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps);
1689 /* In unified mode 'memory' attributes do not exist on the root cgroup. In legacy mode 'memory.limit_in_bytes'
1690 * exists on the root cgroup, but any writes to it are refused with EINVAL. And if we run in a container we
1691 * want to leave control to the container manager (and if proper cgroup v2 delegation is used we couldn't even
1692 * write to this if we wanted to.) */
1693 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_local_root) {
1695 if (cg_all_unified() > 0) {
1696 uint64_t max, swap_max = CGROUP_LIMIT_MAX, zswap_max = CGROUP_LIMIT_MAX, high = CGROUP_LIMIT_MAX;
1698 if (unit_has_unified_memory_config(u)) {
1699 bool startup = IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING);
1701 high = startup && c->startup_memory_high_set ? c->startup_memory_high : c->memory_high;
1702 max = startup && c->startup_memory_max_set ? c->startup_memory_max : c->memory_max;
1703 swap_max = startup && c->startup_memory_swap_max_set ? c->startup_memory_swap_max : c->memory_swap_max;
1704 zswap_max = startup && c->startup_memory_zswap_max_set ? c->startup_memory_zswap_max : c->memory_zswap_max;
1705 } else {
1706 max = c->memory_limit;
1708 if (max != CGROUP_LIMIT_MAX)
1709 log_cgroup_compat(u, "Applying MemoryLimit=%" PRIu64 " as MemoryMax=", max);
1712 cgroup_apply_unified_memory_limit(u, "memory.min", unit_get_ancestor_memory_min(u));
1713 cgroup_apply_unified_memory_limit(u, "memory.low", unit_get_ancestor_memory_low(u));
1714 cgroup_apply_unified_memory_limit(u, "memory.high", high);
1715 cgroup_apply_unified_memory_limit(u, "memory.max", max);
1716 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
1717 cgroup_apply_unified_memory_limit(u, "memory.zswap.max", zswap_max);
1719 (void) set_attribute_and_warn(u, "memory", "memory.oom.group", one_zero(c->memory_oom_group));
1721 } else {
1722 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
1723 uint64_t val;
1725 if (unit_has_unified_memory_config(u)) {
1726 val = c->memory_max;
1727 if (val != CGROUP_LIMIT_MAX)
1728 log_cgroup_compat(u, "Applying MemoryMax=%" PRIu64 " as MemoryLimit=", val);
1729 } else
1730 val = c->memory_limit;
1732 if (val == CGROUP_LIMIT_MAX)
1733 strncpy(buf, "-1\n", sizeof(buf));
1734 else
1735 xsprintf(buf, "%" PRIu64 "\n", val);
1737 (void) set_attribute_and_warn(u, "memory", "memory.limit_in_bytes", buf);
1741 /* On cgroup v2 we can apply BPF everywhere. On cgroup v1 we apply it everywhere except for the root of
1742 * containers, where we leave this to the manager */
1743 if ((apply_mask & (CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES)) &&
1744 (is_host_root || cg_all_unified() > 0 || !is_local_root))
1745 (void) cgroup_apply_devices(u);
1747 if (apply_mask & CGROUP_MASK_PIDS) {
1749 if (is_host_root) {
1750 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1751 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1752 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1753 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1754 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1755 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1756 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1757 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1758 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1759 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1760 * which is desirable so that there's an official way to release control of the sysctl from
1761 * systemd: set the limit to unbounded and reload. */
1763 if (tasks_max_isset(&c->tasks_max)) {
1764 u->manager->sysctl_pid_max_changed = true;
1765 r = procfs_tasks_set_limit(tasks_max_resolve(&c->tasks_max));
1766 } else if (u->manager->sysctl_pid_max_changed)
1767 r = procfs_tasks_set_limit(TASKS_MAX);
1768 else
1769 r = 0;
1770 if (r < 0)
1771 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r,
1772 "Failed to write to tasks limit sysctls: %m");
1775 /* The attribute itself is not available on the host root cgroup, and in the container case we want to
1776 * leave it for the container manager. */
1777 if (!is_local_root) {
1778 if (tasks_max_isset(&c->tasks_max)) {
1779 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
1781 xsprintf(buf, "%" PRIu64 "\n", tasks_max_resolve(&c->tasks_max));
1782 (void) set_attribute_and_warn(u, "pids", "pids.max", buf);
1783 } else
1784 (void) set_attribute_and_warn(u, "pids", "pids.max", "max\n");
1788 if (apply_mask & CGROUP_MASK_BPF_FIREWALL)
1789 cgroup_apply_firewall(u);
1791 if (apply_mask & CGROUP_MASK_BPF_FOREIGN)
1792 cgroup_apply_bpf_foreign_program(u);
1794 if (apply_mask & CGROUP_MASK_BPF_SOCKET_BIND)
1795 cgroup_apply_socket_bind(u);
1797 if (apply_mask & CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES)
1798 cgroup_apply_restrict_network_interfaces(u);
1801 static bool unit_get_needs_bpf_firewall(Unit *u) {
1802 CGroupContext *c;
1803 assert(u);
1805 c = unit_get_cgroup_context(u);
1806 if (!c)
1807 return false;
1809 if (c->ip_accounting ||
1810 !set_isempty(c->ip_address_allow) ||
1811 !set_isempty(c->ip_address_deny) ||
1812 c->ip_filters_ingress ||
1813 c->ip_filters_egress)
1814 return true;
1816 /* If any parent slice has an IP access list defined, it applies too */
1817 for (Unit *p = UNIT_GET_SLICE(u); p; p = UNIT_GET_SLICE(p)) {
1818 c = unit_get_cgroup_context(p);
1819 if (!c)
1820 return false;
1822 if (!set_isempty(c->ip_address_allow) ||
1823 !set_isempty(c->ip_address_deny))
1824 return true;
1827 return false;
1830 static bool unit_get_needs_bpf_foreign_program(Unit *u) {
1831 CGroupContext *c;
1832 assert(u);
1834 c = unit_get_cgroup_context(u);
1835 if (!c)
1836 return false;
1838 return !!c->bpf_foreign_programs;
1841 static bool unit_get_needs_socket_bind(Unit *u) {
1842 CGroupContext *c;
1843 assert(u);
1845 c = unit_get_cgroup_context(u);
1846 if (!c)
1847 return false;
1849 return c->socket_bind_allow || c->socket_bind_deny;
1852 static bool unit_get_needs_restrict_network_interfaces(Unit *u) {
1853 CGroupContext *c;
1854 assert(u);
1856 c = unit_get_cgroup_context(u);
1857 if (!c)
1858 return false;
1860 return !set_isempty(c->restrict_network_interfaces);
1863 static CGroupMask unit_get_cgroup_mask(Unit *u) {
1864 CGroupMask mask = 0;
1865 CGroupContext *c;
1867 assert(u);
1869 assert_se(c = unit_get_cgroup_context(u));
1871 /* Figure out which controllers we need, based on the cgroup context object */
1873 if (c->cpu_accounting)
1874 mask |= get_cpu_accounting_mask();
1876 if (cgroup_context_has_cpu_weight(c) ||
1877 cgroup_context_has_cpu_shares(c) ||
1878 c->cpu_quota_per_sec_usec != USEC_INFINITY)
1879 mask |= CGROUP_MASK_CPU;
1881 if (cgroup_context_has_allowed_cpus(c) || cgroup_context_has_allowed_mems(c))
1882 mask |= CGROUP_MASK_CPUSET;
1884 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
1885 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
1887 if (c->memory_accounting ||
1888 c->memory_limit != CGROUP_LIMIT_MAX ||
1889 unit_has_unified_memory_config(u))
1890 mask |= CGROUP_MASK_MEMORY;
1892 if (c->device_allow ||
1893 c->device_policy != CGROUP_DEVICE_POLICY_AUTO)
1894 mask |= CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES;
1896 if (c->tasks_accounting ||
1897 tasks_max_isset(&c->tasks_max))
1898 mask |= CGROUP_MASK_PIDS;
1900 return CGROUP_MASK_EXTEND_JOINED(mask);
1903 static CGroupMask unit_get_bpf_mask(Unit *u) {
1904 CGroupMask mask = 0;
1906 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
1907 * too. */
1909 if (unit_get_needs_bpf_firewall(u))
1910 mask |= CGROUP_MASK_BPF_FIREWALL;
1912 if (unit_get_needs_bpf_foreign_program(u))
1913 mask |= CGROUP_MASK_BPF_FOREIGN;
1915 if (unit_get_needs_socket_bind(u))
1916 mask |= CGROUP_MASK_BPF_SOCKET_BIND;
1918 if (unit_get_needs_restrict_network_interfaces(u))
1919 mask |= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES;
1921 return mask;
1924 CGroupMask unit_get_own_mask(Unit *u) {
1925 CGroupContext *c;
1927 /* Returns the mask of controllers the unit needs for itself. If a unit is not properly loaded, return an empty
1928 * mask, as we shouldn't reflect it in the cgroup hierarchy then. */
1930 if (u->load_state != UNIT_LOADED)
1931 return 0;
1933 c = unit_get_cgroup_context(u);
1934 if (!c)
1935 return 0;
1937 return unit_get_cgroup_mask(u) | unit_get_bpf_mask(u) | unit_get_delegate_mask(u);
1940 CGroupMask unit_get_delegate_mask(Unit *u) {
1941 CGroupContext *c;
1943 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1944 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
1946 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1948 if (!unit_cgroup_delegate(u))
1949 return 0;
1951 if (cg_all_unified() <= 0) {
1952 ExecContext *e;
1954 e = unit_get_exec_context(u);
1955 if (e && !exec_context_maintains_privileges(e))
1956 return 0;
1959 assert_se(c = unit_get_cgroup_context(u));
1960 return CGROUP_MASK_EXTEND_JOINED(c->delegate_controllers);
1963 static CGroupMask unit_get_subtree_mask(Unit *u) {
1965 /* Returns the mask of this subtree, meaning of the group
1966 * itself and its children. */
1968 return unit_get_own_mask(u) | unit_get_members_mask(u);
1971 CGroupMask unit_get_members_mask(Unit *u) {
1972 assert(u);
1974 /* Returns the mask of controllers all of the unit's children require, merged */
1976 if (u->cgroup_members_mask_valid)
1977 return u->cgroup_members_mask; /* Use cached value if possible */
1979 u->cgroup_members_mask = 0;
1981 if (u->type == UNIT_SLICE) {
1982 Unit *member;
1984 UNIT_FOREACH_DEPENDENCY(member, u, UNIT_ATOM_SLICE_OF)
1985 u->cgroup_members_mask |= unit_get_subtree_mask(member); /* note that this calls ourselves again, for the children */
1988 u->cgroup_members_mask_valid = true;
1989 return u->cgroup_members_mask;
1992 CGroupMask unit_get_siblings_mask(Unit *u) {
1993 Unit *slice;
1994 assert(u);
1996 /* Returns the mask of controllers all of the unit's siblings
1997 * require, i.e. the members mask of the unit's parent slice
1998 * if there is one. */
2000 slice = UNIT_GET_SLICE(u);
2001 if (slice)
2002 return unit_get_members_mask(slice);
2004 return unit_get_subtree_mask(u); /* we are the top-level slice */
2007 static CGroupMask unit_get_disable_mask(Unit *u) {
2008 CGroupContext *c;
2010 c = unit_get_cgroup_context(u);
2011 if (!c)
2012 return 0;
2014 return c->disable_controllers;
2017 CGroupMask unit_get_ancestor_disable_mask(Unit *u) {
2018 CGroupMask mask;
2019 Unit *slice;
2021 assert(u);
2022 mask = unit_get_disable_mask(u);
2024 /* Returns the mask of controllers which are marked as forcibly
2025 * disabled in any ancestor unit or the unit in question. */
2027 slice = UNIT_GET_SLICE(u);
2028 if (slice)
2029 mask |= unit_get_ancestor_disable_mask(slice);
2031 return mask;
2034 CGroupMask unit_get_target_mask(Unit *u) {
2035 CGroupMask own_mask, mask;
2037 /* This returns the cgroup mask of all controllers to enable for a specific cgroup, i.e. everything
2038 * it needs itself, plus all that its children need, plus all that its siblings need. This is
2039 * primarily useful on the legacy cgroup hierarchy, where we need to duplicate each cgroup in each
2040 * hierarchy that shall be enabled for it. */
2042 own_mask = unit_get_own_mask(u);
2044 if (own_mask & CGROUP_MASK_BPF_FIREWALL & ~u->manager->cgroup_supported)
2045 emit_bpf_firewall_warning(u);
2047 mask = own_mask | unit_get_members_mask(u) | unit_get_siblings_mask(u);
2049 mask &= u->manager->cgroup_supported;
2050 mask &= ~unit_get_ancestor_disable_mask(u);
2052 return mask;
2055 CGroupMask unit_get_enable_mask(Unit *u) {
2056 CGroupMask mask;
2058 /* This returns the cgroup mask of all controllers to enable
2059 * for the children of a specific cgroup. This is primarily
2060 * useful for the unified cgroup hierarchy, where each cgroup
2061 * controls which controllers are enabled for its children. */
2063 mask = unit_get_members_mask(u);
2064 mask &= u->manager->cgroup_supported;
2065 mask &= ~unit_get_ancestor_disable_mask(u);
2067 return mask;
2070 void unit_invalidate_cgroup_members_masks(Unit *u) {
2071 Unit *slice;
2073 assert(u);
2075 /* Recurse invalidate the member masks cache all the way up the tree */
2076 u->cgroup_members_mask_valid = false;
2078 slice = UNIT_GET_SLICE(u);
2079 if (slice)
2080 unit_invalidate_cgroup_members_masks(slice);
2083 const char *unit_get_realized_cgroup_path(Unit *u, CGroupMask mask) {
2085 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
2087 while (u) {
2089 if (u->cgroup_path &&
2090 u->cgroup_realized &&
2091 FLAGS_SET(u->cgroup_realized_mask, mask))
2092 return u->cgroup_path;
2094 u = UNIT_GET_SLICE(u);
2097 return NULL;
2100 static const char *migrate_callback(CGroupMask mask, void *userdata) {
2101 /* If not realized at all, migrate to root ("").
2102 * It may happen if we're upgrading from older version that didn't clean up.
2104 return strempty(unit_get_realized_cgroup_path(userdata, mask));
2107 int unit_default_cgroup_path(const Unit *u, char **ret) {
2108 _cleanup_free_ char *p = NULL;
2109 int r;
2111 assert(u);
2112 assert(ret);
2114 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
2115 p = strdup(u->manager->cgroup_root);
2116 else {
2117 _cleanup_free_ char *escaped = NULL, *slice_path = NULL;
2118 Unit *slice;
2120 slice = UNIT_GET_SLICE(u);
2121 if (slice && !unit_has_name(slice, SPECIAL_ROOT_SLICE)) {
2122 r = cg_slice_to_path(slice->id, &slice_path);
2123 if (r < 0)
2124 return r;
2127 r = cg_escape(u->id, &escaped);
2128 if (r < 0)
2129 return r;
2131 p = path_join(empty_to_root(u->manager->cgroup_root), slice_path, escaped);
2133 if (!p)
2134 return -ENOMEM;
2136 *ret = TAKE_PTR(p);
2137 return 0;
2140 int unit_set_cgroup_path(Unit *u, const char *path) {
2141 _cleanup_free_ char *p = NULL;
2142 int r;
2144 assert(u);
2146 if (streq_ptr(u->cgroup_path, path))
2147 return 0;
2149 if (path) {
2150 p = strdup(path);
2151 if (!p)
2152 return -ENOMEM;
2155 if (p) {
2156 r = hashmap_put(u->manager->cgroup_unit, p, u);
2157 if (r < 0)
2158 return r;
2161 unit_release_cgroup(u);
2162 u->cgroup_path = TAKE_PTR(p);
2164 return 1;
2167 int unit_watch_cgroup(Unit *u) {
2168 _cleanup_free_ char *events = NULL;
2169 int r;
2171 assert(u);
2173 /* Watches the "cgroups.events" attribute of this unit's cgroup for "empty" events, but only if
2174 * cgroupv2 is available. */
2176 if (!u->cgroup_path)
2177 return 0;
2179 if (u->cgroup_control_inotify_wd >= 0)
2180 return 0;
2182 /* Only applies to the unified hierarchy */
2183 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2184 if (r < 0)
2185 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
2186 if (r == 0)
2187 return 0;
2189 /* No point in watch the top-level slice, it's never going to run empty. */
2190 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
2191 return 0;
2193 r = hashmap_ensure_allocated(&u->manager->cgroup_control_inotify_wd_unit, &trivial_hash_ops);
2194 if (r < 0)
2195 return log_oom();
2197 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
2198 if (r < 0)
2199 return log_oom();
2201 u->cgroup_control_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
2202 if (u->cgroup_control_inotify_wd < 0) {
2204 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
2205 * is not an error */
2206 return 0;
2208 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));
2211 r = hashmap_put(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd), u);
2212 if (r < 0)
2213 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));
2215 return 0;
2218 int unit_watch_cgroup_memory(Unit *u) {
2219 _cleanup_free_ char *events = NULL;
2220 CGroupContext *c;
2221 int r;
2223 assert(u);
2225 /* Watches the "memory.events" attribute of this unit's cgroup for "oom_kill" events, but only if
2226 * cgroupv2 is available. */
2228 if (!u->cgroup_path)
2229 return 0;
2231 c = unit_get_cgroup_context(u);
2232 if (!c)
2233 return 0;
2235 /* The "memory.events" attribute is only available if the memory controller is on. Let's hence tie
2236 * this to memory accounting, in a way watching for OOM kills is a form of memory accounting after
2237 * all. */
2238 if (!c->memory_accounting)
2239 return 0;
2241 /* Don't watch inner nodes, as the kernel doesn't report oom_kill events recursively currently, and
2242 * we also don't want to generate a log message for each parent cgroup of a process. */
2243 if (u->type == UNIT_SLICE)
2244 return 0;
2246 if (u->cgroup_memory_inotify_wd >= 0)
2247 return 0;
2249 /* Only applies to the unified hierarchy */
2250 r = cg_all_unified();
2251 if (r < 0)
2252 return log_error_errno(r, "Failed to determine whether the memory controller is unified: %m");
2253 if (r == 0)
2254 return 0;
2256 r = hashmap_ensure_allocated(&u->manager->cgroup_memory_inotify_wd_unit, &trivial_hash_ops);
2257 if (r < 0)
2258 return log_oom();
2260 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "memory.events", &events);
2261 if (r < 0)
2262 return log_oom();
2264 u->cgroup_memory_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
2265 if (u->cgroup_memory_inotify_wd < 0) {
2267 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
2268 * is not an error */
2269 return 0;
2271 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));
2274 r = hashmap_put(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd), u);
2275 if (r < 0)
2276 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));
2278 return 0;
2281 int unit_pick_cgroup_path(Unit *u) {
2282 _cleanup_free_ char *path = NULL;
2283 int r;
2285 assert(u);
2287 if (u->cgroup_path)
2288 return 0;
2290 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2291 return -EINVAL;
2293 r = unit_default_cgroup_path(u, &path);
2294 if (r < 0)
2295 return log_unit_error_errno(u, r, "Failed to generate default cgroup path: %m");
2297 r = unit_set_cgroup_path(u, path);
2298 if (r == -EEXIST)
2299 return log_unit_error_errno(u, r, "Control group %s exists already.", empty_to_root(path));
2300 if (r < 0)
2301 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", empty_to_root(path));
2303 return 0;
2306 static int unit_update_cgroup(
2307 Unit *u,
2308 CGroupMask target_mask,
2309 CGroupMask enable_mask,
2310 ManagerState state) {
2312 bool created, is_root_slice;
2313 CGroupMask migrate_mask = 0;
2314 _cleanup_free_ char *cgroup_full_path = NULL;
2315 int r;
2317 assert(u);
2319 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2320 return 0;
2322 /* Figure out our cgroup path */
2323 r = unit_pick_cgroup_path(u);
2324 if (r < 0)
2325 return r;
2327 /* First, create our own group */
2328 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
2329 if (r < 0)
2330 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", empty_to_root(u->cgroup_path));
2331 created = r;
2333 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
2334 uint64_t cgroup_id = 0;
2336 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, NULL, &cgroup_full_path);
2337 if (r == 0) {
2338 r = cg_path_get_cgroupid(cgroup_full_path, &cgroup_id);
2339 if (r < 0)
2340 log_unit_full_errno(u, ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
2341 "Failed to get cgroup ID of cgroup %s, ignoring: %m", cgroup_full_path);
2342 } else
2343 log_unit_warning_errno(u, r, "Failed to get full cgroup path on cgroup %s, ignoring: %m", empty_to_root(u->cgroup_path));
2345 u->cgroup_id = cgroup_id;
2348 /* Start watching it */
2349 (void) unit_watch_cgroup(u);
2350 (void) unit_watch_cgroup_memory(u);
2352 /* For v2 we preserve enabled controllers in delegated units, adjust others,
2353 * for v1 we figure out which controller hierarchies need migration. */
2354 if (created || !u->cgroup_realized || !unit_cgroup_delegate(u)) {
2355 CGroupMask result_mask = 0;
2357 /* Enable all controllers we need */
2358 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path, &result_mask);
2359 if (r < 0)
2360 log_unit_warning_errno(u, r, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", empty_to_root(u->cgroup_path));
2362 /* Remember what's actually enabled now */
2363 u->cgroup_enabled_mask = result_mask;
2365 migrate_mask = u->cgroup_realized_mask ^ target_mask;
2368 /* Keep track that this is now realized */
2369 u->cgroup_realized = true;
2370 u->cgroup_realized_mask = target_mask;
2372 /* Migrate processes in controller hierarchies both downwards (enabling) and upwards (disabling).
2374 * Unnecessary controller cgroups are trimmed (after emptied by upward migration).
2375 * We perform migration also with whole slices for cases when users don't care about leave
2376 * granularity. Since delegated_mask is subset of target mask, we won't trim slice subtree containing
2377 * delegated units.
2379 if (cg_all_unified() == 0) {
2380 r = cg_migrate_v1_controllers(u->manager->cgroup_supported, migrate_mask, u->cgroup_path, migrate_callback, u);
2381 if (r < 0)
2382 log_unit_warning_errno(u, r, "Failed to migrate controller cgroups from %s, ignoring: %m", empty_to_root(u->cgroup_path));
2384 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
2385 r = cg_trim_v1_controllers(u->manager->cgroup_supported, ~target_mask, u->cgroup_path, !is_root_slice);
2386 if (r < 0)
2387 log_unit_warning_errno(u, r, "Failed to delete controller cgroups %s, ignoring: %m", empty_to_root(u->cgroup_path));
2390 /* Set attributes */
2391 cgroup_context_apply(u, target_mask, state);
2392 cgroup_xattr_apply(u);
2394 /* For most units we expect that memory monitoring is set up before the unit is started and we won't
2395 * touch it after. For PID 1 this is different though, because we couldn't possibly do that given
2396 * that PID 1 runs before init.scope is even set up. Hence, whenever init.scope is realized, let's
2397 * try to open the memory pressure interface anew. */
2398 if (unit_has_name(u, SPECIAL_INIT_SCOPE))
2399 (void) manager_setup_memory_pressure_event_source(u->manager);
2401 return 0;
2404 static int unit_attach_pid_to_cgroup_via_bus(Unit *u, pid_t pid, const char *suffix_path) {
2405 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2406 char *pp;
2407 int r;
2409 assert(u);
2411 if (MANAGER_IS_SYSTEM(u->manager))
2412 return -EINVAL;
2414 if (!u->manager->system_bus)
2415 return -EIO;
2417 if (!u->cgroup_path)
2418 return -EINVAL;
2420 /* Determine this unit's cgroup path relative to our cgroup root */
2421 pp = path_startswith(u->cgroup_path, u->manager->cgroup_root);
2422 if (!pp)
2423 return -EINVAL;
2425 pp = strjoina("/", pp, suffix_path);
2426 path_simplify(pp);
2428 r = bus_call_method(u->manager->system_bus,
2429 bus_systemd_mgr,
2430 "AttachProcessesToUnit",
2431 &error, NULL,
2432 "ssau",
2433 NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
2434 if (r < 0)
2435 return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
2437 return 0;
2440 int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
2441 _cleanup_free_ char *joined = NULL;
2442 CGroupMask delegated_mask;
2443 const char *p;
2444 void *pidp;
2445 int ret, r;
2447 assert(u);
2449 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2450 return -EINVAL;
2452 if (set_isempty(pids))
2453 return 0;
2455 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
2456 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
2457 r = bpf_firewall_load_custom(u);
2458 if (r < 0)
2459 return r;
2461 r = unit_realize_cgroup(u);
2462 if (r < 0)
2463 return r;
2465 if (isempty(suffix_path))
2466 p = u->cgroup_path;
2467 else {
2468 joined = path_join(u->cgroup_path, suffix_path);
2469 if (!joined)
2470 return -ENOMEM;
2472 p = joined;
2475 delegated_mask = unit_get_delegate_mask(u);
2477 ret = 0;
2478 SET_FOREACH(pidp, pids) {
2479 pid_t pid = PTR_TO_PID(pidp);
2481 /* First, attach the PID to the main cgroup hierarchy */
2482 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, p, pid);
2483 if (r < 0) {
2484 bool again = MANAGER_IS_USER(u->manager) && ERRNO_IS_PRIVILEGE(r);
2486 log_unit_full_errno(u, again ? LOG_DEBUG : LOG_INFO, r,
2487 "Couldn't move process "PID_FMT" to%s requested cgroup '%s': %m",
2488 pid, again ? " directly" : "", empty_to_root(p));
2490 if (again) {
2491 int z;
2493 /* If we are in a user instance, and we can't move the process ourselves due
2494 * to permission problems, let's ask the system instance about it instead.
2495 * Since it's more privileged it might be able to move the process across the
2496 * leaves of a subtree whose top node is not owned by us. */
2498 z = unit_attach_pid_to_cgroup_via_bus(u, pid, suffix_path);
2499 if (z < 0)
2500 log_unit_info_errno(u, z, "Couldn't move process "PID_FMT" to requested cgroup '%s' (directly or via the system bus): %m", pid, empty_to_root(p));
2501 else {
2502 if (ret >= 0)
2503 ret++; /* Count successful additions */
2504 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
2508 if (ret >= 0)
2509 ret = r; /* Remember first error */
2511 continue;
2512 } else if (ret >= 0)
2513 ret++; /* Count successful additions */
2515 r = cg_all_unified();
2516 if (r < 0)
2517 return r;
2518 if (r > 0)
2519 continue;
2521 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
2522 * innermost realized one */
2524 for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2525 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2526 const char *realized;
2528 if (!(u->manager->cgroup_supported & bit))
2529 continue;
2531 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
2532 if (delegated_mask & u->cgroup_realized_mask & bit) {
2533 r = cg_attach(cgroup_controller_to_string(c), p, pid);
2534 if (r >= 0)
2535 continue; /* Success! */
2537 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",
2538 pid, empty_to_root(p), cgroup_controller_to_string(c));
2541 /* So this controller is either not delegate or realized, or something else weird happened. In
2542 * that case let's attach the PID at least to the closest cgroup up the tree that is
2543 * realized. */
2544 realized = unit_get_realized_cgroup_path(u, bit);
2545 if (!realized)
2546 continue; /* Not even realized in the root slice? Then let's not bother */
2548 r = cg_attach(cgroup_controller_to_string(c), realized, pid);
2549 if (r < 0)
2550 log_unit_debug_errno(u, r, "Failed to attach PID " PID_FMT " to realized cgroup %s in controller %s, ignoring: %m",
2551 pid, realized, cgroup_controller_to_string(c));
2555 return ret;
2558 static bool unit_has_mask_realized(
2559 Unit *u,
2560 CGroupMask target_mask,
2561 CGroupMask enable_mask) {
2563 assert(u);
2565 /* Returns true if this unit is fully realized. We check four things:
2567 * 1. Whether the cgroup was created at all
2568 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
2569 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
2570 * 4. Whether the invalidation mask is currently zero
2572 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
2573 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
2574 * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
2575 * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
2576 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
2577 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
2578 * simply don't matter. */
2580 return u->cgroup_realized &&
2581 ((u->cgroup_realized_mask ^ target_mask) & CGROUP_MASK_V1) == 0 &&
2582 ((u->cgroup_enabled_mask ^ enable_mask) & CGROUP_MASK_V2) == 0 &&
2583 u->cgroup_invalidated_mask == 0;
2586 static bool unit_has_mask_disables_realized(
2587 Unit *u,
2588 CGroupMask target_mask,
2589 CGroupMask enable_mask) {
2591 assert(u);
2593 /* Returns true if all controllers which should be disabled are indeed disabled.
2595 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
2596 * already removed. */
2598 return !u->cgroup_realized ||
2599 (FLAGS_SET(u->cgroup_realized_mask, target_mask & CGROUP_MASK_V1) &&
2600 FLAGS_SET(u->cgroup_enabled_mask, enable_mask & CGROUP_MASK_V2));
2603 static bool unit_has_mask_enables_realized(
2604 Unit *u,
2605 CGroupMask target_mask,
2606 CGroupMask enable_mask) {
2608 assert(u);
2610 /* Returns true if all controllers which should be enabled are indeed enabled.
2612 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
2613 * we want to add is already added. */
2615 return u->cgroup_realized &&
2616 ((u->cgroup_realized_mask | target_mask) & CGROUP_MASK_V1) == (u->cgroup_realized_mask & CGROUP_MASK_V1) &&
2617 ((u->cgroup_enabled_mask | enable_mask) & CGROUP_MASK_V2) == (u->cgroup_enabled_mask & CGROUP_MASK_V2);
2620 void unit_add_to_cgroup_realize_queue(Unit *u) {
2621 assert(u);
2623 if (u->in_cgroup_realize_queue)
2624 return;
2626 LIST_APPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2627 u->in_cgroup_realize_queue = true;
2630 static void unit_remove_from_cgroup_realize_queue(Unit *u) {
2631 assert(u);
2633 if (!u->in_cgroup_realize_queue)
2634 return;
2636 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2637 u->in_cgroup_realize_queue = false;
2640 /* Controllers can only be enabled breadth-first, from the root of the
2641 * hierarchy downwards to the unit in question. */
2642 static int unit_realize_cgroup_now_enable(Unit *u, ManagerState state) {
2643 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2644 Unit *slice;
2645 int r;
2647 assert(u);
2649 /* First go deal with this unit's parent, or we won't be able to enable
2650 * any new controllers at this layer. */
2651 slice = UNIT_GET_SLICE(u);
2652 if (slice) {
2653 r = unit_realize_cgroup_now_enable(slice, state);
2654 if (r < 0)
2655 return r;
2658 target_mask = unit_get_target_mask(u);
2659 enable_mask = unit_get_enable_mask(u);
2661 /* We can only enable in this direction, don't try to disable anything.
2663 if (unit_has_mask_enables_realized(u, target_mask, enable_mask))
2664 return 0;
2666 new_target_mask = u->cgroup_realized_mask | target_mask;
2667 new_enable_mask = u->cgroup_enabled_mask | enable_mask;
2669 return unit_update_cgroup(u, new_target_mask, new_enable_mask, state);
2672 /* Controllers can only be disabled depth-first, from the leaves of the
2673 * hierarchy upwards to the unit in question. */
2674 static int unit_realize_cgroup_now_disable(Unit *u, ManagerState state) {
2675 Unit *m;
2677 assert(u);
2679 if (u->type != UNIT_SLICE)
2680 return 0;
2682 UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
2683 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2684 int r;
2686 /* The cgroup for this unit might not actually be fully realised yet, in which case it isn't
2687 * holding any controllers open anyway. */
2688 if (!m->cgroup_realized)
2689 continue;
2691 /* We must disable those below us first in order to release the controller. */
2692 if (m->type == UNIT_SLICE)
2693 (void) unit_realize_cgroup_now_disable(m, state);
2695 target_mask = unit_get_target_mask(m);
2696 enable_mask = unit_get_enable_mask(m);
2698 /* We can only disable in this direction, don't try to enable anything. */
2699 if (unit_has_mask_disables_realized(m, target_mask, enable_mask))
2700 continue;
2702 new_target_mask = m->cgroup_realized_mask & target_mask;
2703 new_enable_mask = m->cgroup_enabled_mask & enable_mask;
2705 r = unit_update_cgroup(m, new_target_mask, new_enable_mask, state);
2706 if (r < 0)
2707 return r;
2710 return 0;
2713 /* Check if necessary controllers and attributes for a unit are in place.
2715 * - If so, do nothing.
2716 * - If not, create paths, move processes over, and set attributes.
2718 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
2719 * a depth-first way. As such the process looks like this:
2721 * Suppose we have a cgroup hierarchy which looks like this:
2723 * root
2724 * / \
2725 * / \
2726 * / \
2727 * a b
2728 * / \ / \
2729 * / \ / \
2730 * c d e f
2731 * / \ / \ / \ / \
2732 * h i j k l m n o
2734 * 1. We want to realise cgroup "d" now.
2735 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
2736 * 3. cgroup "k" just started requesting the memory controller.
2738 * To make this work we must do the following in order:
2740 * 1. Disable CPU controller in k, j
2741 * 2. Disable CPU controller in d
2742 * 3. Enable memory controller in root
2743 * 4. Enable memory controller in a
2744 * 5. Enable memory controller in d
2745 * 6. Enable memory controller in k
2747 * Notice that we need to touch j in one direction, but not the other. We also
2748 * don't go beyond d when disabling -- it's up to "a" to get realized if it
2749 * wants to disable further. The basic rules are therefore:
2751 * - If you're disabling something, you need to realise all of the cgroups from
2752 * your recursive descendants to the root. This starts from the leaves.
2753 * - If you're enabling something, you need to realise from the root cgroup
2754 * downwards, but you don't need to iterate your recursive descendants.
2756 * Returns 0 on success and < 0 on failure. */
2757 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
2758 CGroupMask target_mask, enable_mask;
2759 Unit *slice;
2760 int r;
2762 assert(u);
2764 unit_remove_from_cgroup_realize_queue(u);
2766 target_mask = unit_get_target_mask(u);
2767 enable_mask = unit_get_enable_mask(u);
2769 if (unit_has_mask_realized(u, target_mask, enable_mask))
2770 return 0;
2772 /* Disable controllers below us, if there are any */
2773 r = unit_realize_cgroup_now_disable(u, state);
2774 if (r < 0)
2775 return r;
2777 /* Enable controllers above us, if there are any */
2778 slice = UNIT_GET_SLICE(u);
2779 if (slice) {
2780 r = unit_realize_cgroup_now_enable(slice, state);
2781 if (r < 0)
2782 return r;
2785 /* Now actually deal with the cgroup we were trying to realise and set attributes */
2786 r = unit_update_cgroup(u, target_mask, enable_mask, state);
2787 if (r < 0)
2788 return r;
2790 /* Now, reset the invalidation mask */
2791 u->cgroup_invalidated_mask = 0;
2792 return 0;
2795 unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
2796 ManagerState state;
2797 unsigned n = 0;
2798 Unit *i;
2799 int r;
2801 assert(m);
2803 state = manager_state(m);
2805 while ((i = m->cgroup_realize_queue)) {
2806 assert(i->in_cgroup_realize_queue);
2808 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
2809 /* Maybe things changed, and the unit is not actually active anymore? */
2810 unit_remove_from_cgroup_realize_queue(i);
2811 continue;
2814 r = unit_realize_cgroup_now(i, state);
2815 if (r < 0)
2816 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
2818 n++;
2821 return n;
2824 void unit_add_family_to_cgroup_realize_queue(Unit *u) {
2825 assert(u);
2826 assert(u->type == UNIT_SLICE);
2828 /* Family of a unit for is defined as (immediate) children of the unit and immediate children of all
2829 * its ancestors.
2831 * Ideally we would enqueue ancestor path only (bottom up). However, on cgroup-v1 scheduling becomes
2832 * very weird if two units that own processes reside in the same slice, but one is realized in the
2833 * "cpu" hierarchy and one is not (for example because one has CPUWeight= set and the other does
2834 * not), because that means individual processes need to be scheduled against whole cgroups. Let's
2835 * avoid this asymmetry by always ensuring that siblings of a unit are always realized in their v1
2836 * controller hierarchies too (if unit requires the controller to be realized).
2838 * The function must invalidate cgroup_members_mask of all ancestors in order to calculate up to date
2839 * masks. */
2841 do {
2842 Unit *m;
2844 /* Children of u likely changed when we're called */
2845 u->cgroup_members_mask_valid = false;
2847 UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
2849 /* No point in doing cgroup application for units without active processes. */
2850 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
2851 continue;
2853 /* We only enqueue siblings if they were realized once at least, in the main
2854 * hierarchy. */
2855 if (!m->cgroup_realized)
2856 continue;
2858 /* If the unit doesn't need any new controllers and has current ones
2859 * realized, it doesn't need any changes. */
2860 if (unit_has_mask_realized(m,
2861 unit_get_target_mask(m),
2862 unit_get_enable_mask(m)))
2863 continue;
2865 unit_add_to_cgroup_realize_queue(m);
2868 /* Parent comes after children */
2869 unit_add_to_cgroup_realize_queue(u);
2871 u = UNIT_GET_SLICE(u);
2872 } while (u);
2875 int unit_realize_cgroup(Unit *u) {
2876 Unit *slice;
2878 assert(u);
2880 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2881 return 0;
2883 /* So, here's the deal: when realizing the cgroups for this unit, we need to first create all
2884 * parents, but there's more actually: for the weight-based controllers we also need to make sure
2885 * that all our siblings (i.e. units that are in the same slice as we are) have cgroups, too. On the
2886 * other hand, when a controller is removed from realized set, it may become unnecessary in siblings
2887 * and ancestors and they should be (de)realized too.
2889 * This call will defer work on the siblings and derealized ancestors to the next event loop
2890 * iteration and synchronously creates the parent cgroups (unit_realize_cgroup_now). */
2892 slice = UNIT_GET_SLICE(u);
2893 if (slice)
2894 unit_add_family_to_cgroup_realize_queue(slice);
2896 /* And realize this one now (and apply the values) */
2897 return unit_realize_cgroup_now(u, manager_state(u->manager));
2900 void unit_release_cgroup(Unit *u) {
2901 assert(u);
2903 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
2904 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
2906 if (u->cgroup_path) {
2907 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
2908 u->cgroup_path = mfree(u->cgroup_path);
2911 if (u->cgroup_control_inotify_wd >= 0) {
2912 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_control_inotify_wd) < 0)
2913 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);
2915 (void) hashmap_remove(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd));
2916 u->cgroup_control_inotify_wd = -1;
2919 if (u->cgroup_memory_inotify_wd >= 0) {
2920 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_memory_inotify_wd) < 0)
2921 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);
2923 (void) hashmap_remove(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd));
2924 u->cgroup_memory_inotify_wd = -1;
2928 bool unit_maybe_release_cgroup(Unit *u) {
2929 int r;
2931 assert(u);
2933 if (!u->cgroup_path)
2934 return true;
2936 /* Don't release the cgroup if there are still processes under it. If we get notified later when all the
2937 * processes exit (e.g. the processes were in D-state and exited after the unit was marked as failed)
2938 * we need the cgroup paths to continue to be tracked by the manager so they can be looked up and cleaned
2939 * up later. */
2940 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
2941 if (r < 0)
2942 log_unit_debug_errno(u, r, "Error checking if the cgroup is recursively empty, ignoring: %m");
2943 else if (r == 1) {
2944 unit_release_cgroup(u);
2945 return true;
2948 return false;
2951 void unit_prune_cgroup(Unit *u) {
2952 int r;
2953 bool is_root_slice;
2955 assert(u);
2957 /* Removes the cgroup, if empty and possible, and stops watching it. */
2959 if (!u->cgroup_path)
2960 return;
2962 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
2964 #if BPF_FRAMEWORK
2965 (void) lsm_bpf_cleanup(u); /* Remove cgroup from the global LSM BPF map */
2966 #endif
2968 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
2970 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
2971 if (r < 0)
2972 /* One reason we could have failed here is, that the cgroup still contains a process.
2973 * However, if the cgroup becomes removable at a later time, it might be removed when
2974 * the containing slice is stopped. So even if we failed now, this unit shouldn't assume
2975 * that the cgroup is still realized the next time it is started. Do not return early
2976 * on error, continue cleanup. */
2977 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));
2979 if (is_root_slice)
2980 return;
2982 if (!unit_maybe_release_cgroup(u)) /* Returns true if the cgroup was released */
2983 return;
2985 u->cgroup_realized = false;
2986 u->cgroup_realized_mask = 0;
2987 u->cgroup_enabled_mask = 0;
2989 u->bpf_device_control_installed = bpf_program_free(u->bpf_device_control_installed);
2992 int unit_search_main_pid(Unit *u, pid_t *ret) {
2993 _cleanup_fclose_ FILE *f = NULL;
2994 pid_t pid = 0, npid;
2995 int r;
2997 assert(u);
2998 assert(ret);
3000 if (!u->cgroup_path)
3001 return -ENXIO;
3003 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
3004 if (r < 0)
3005 return r;
3007 while (cg_read_pid(f, &npid) > 0) {
3009 if (npid == pid)
3010 continue;
3012 if (pid_is_my_child(npid) == 0)
3013 continue;
3015 if (pid != 0)
3016 /* Dang, there's more than one daemonized PID
3017 in this group, so we don't know what process
3018 is the main process. */
3020 return -ENODATA;
3022 pid = npid;
3025 *ret = pid;
3026 return 0;
3029 static int unit_watch_pids_in_path(Unit *u, const char *path) {
3030 _cleanup_closedir_ DIR *d = NULL;
3031 _cleanup_fclose_ FILE *f = NULL;
3032 int ret = 0, r;
3034 assert(u);
3035 assert(path);
3037 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
3038 if (r < 0)
3039 ret = r;
3040 else {
3041 pid_t pid;
3043 while ((r = cg_read_pid(f, &pid)) > 0) {
3044 r = unit_watch_pid(u, pid, false);
3045 if (r < 0 && ret >= 0)
3046 ret = r;
3049 if (r < 0 && ret >= 0)
3050 ret = r;
3053 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
3054 if (r < 0) {
3055 if (ret >= 0)
3056 ret = r;
3057 } else {
3058 char *fn;
3060 while ((r = cg_read_subgroup(d, &fn)) > 0) {
3061 _cleanup_free_ char *p = NULL;
3063 p = path_join(empty_to_root(path), fn);
3064 free(fn);
3066 if (!p)
3067 return -ENOMEM;
3069 r = unit_watch_pids_in_path(u, p);
3070 if (r < 0 && ret >= 0)
3071 ret = r;
3074 if (r < 0 && ret >= 0)
3075 ret = r;
3078 return ret;
3081 int unit_synthesize_cgroup_empty_event(Unit *u) {
3082 int r;
3084 assert(u);
3086 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
3087 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
3088 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
3090 if (!u->cgroup_path)
3091 return -ENOENT;
3093 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
3094 if (r < 0)
3095 return r;
3096 if (r > 0) /* On unified we have reliable notifications, and don't need this */
3097 return 0;
3099 if (!set_isempty(u->pids))
3100 return 0;
3102 unit_add_to_cgroup_empty_queue(u);
3103 return 0;
3106 int unit_watch_all_pids(Unit *u) {
3107 int r;
3109 assert(u);
3111 /* Adds all PIDs from our cgroup to the set of PIDs we
3112 * watch. This is a fallback logic for cases where we do not
3113 * get reliable cgroup empty notifications: we try to use
3114 * SIGCHLD as replacement. */
3116 if (!u->cgroup_path)
3117 return -ENOENT;
3119 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
3120 if (r < 0)
3121 return r;
3122 if (r > 0) /* On unified we can use proper notifications */
3123 return 0;
3125 return unit_watch_pids_in_path(u, u->cgroup_path);
3128 static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
3129 Manager *m = ASSERT_PTR(userdata);
3130 Unit *u;
3131 int r;
3133 assert(s);
3135 u = m->cgroup_empty_queue;
3136 if (!u)
3137 return 0;
3139 assert(u->in_cgroup_empty_queue);
3140 u->in_cgroup_empty_queue = false;
3141 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
3143 if (m->cgroup_empty_queue) {
3144 /* More stuff queued, let's make sure we remain enabled */
3145 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
3146 if (r < 0)
3147 log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
3150 /* Update state based on OOM kills before we notify about cgroup empty event */
3151 (void) unit_check_oom(u);
3152 (void) unit_check_oomd_kill(u);
3154 unit_add_to_gc_queue(u);
3156 if (IN_SET(unit_active_state(u), UNIT_INACTIVE, UNIT_FAILED))
3157 unit_prune_cgroup(u);
3158 else if (UNIT_VTABLE(u)->notify_cgroup_empty)
3159 UNIT_VTABLE(u)->notify_cgroup_empty(u);
3161 return 0;
3164 void unit_add_to_cgroup_empty_queue(Unit *u) {
3165 int r;
3167 assert(u);
3169 /* Note that there are four different ways how cgroup empty events reach us:
3171 * 1. On the unified hierarchy we get an inotify event on the cgroup
3173 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
3175 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
3177 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
3178 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
3180 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
3181 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
3182 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
3183 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
3184 * case for scope units). */
3186 if (u->in_cgroup_empty_queue)
3187 return;
3189 /* Let's verify that the cgroup is really empty */
3190 if (!u->cgroup_path)
3191 return;
3193 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
3194 if (r < 0) {
3195 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", empty_to_root(u->cgroup_path));
3196 return;
3198 if (r == 0)
3199 return;
3201 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
3202 u->in_cgroup_empty_queue = true;
3204 /* Trigger the defer event */
3205 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
3206 if (r < 0)
3207 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
3210 static void unit_remove_from_cgroup_empty_queue(Unit *u) {
3211 assert(u);
3213 if (!u->in_cgroup_empty_queue)
3214 return;
3216 LIST_REMOVE(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
3217 u->in_cgroup_empty_queue = false;
3220 int unit_check_oomd_kill(Unit *u) {
3221 _cleanup_free_ char *value = NULL;
3222 bool increased;
3223 uint64_t n = 0;
3224 int r;
3226 if (!u->cgroup_path)
3227 return 0;
3229 r = cg_all_unified();
3230 if (r < 0)
3231 return log_unit_debug_errno(u, r, "Couldn't determine whether we are in all unified mode: %m");
3232 else if (r == 0)
3233 return 0;
3235 r = cg_get_xattr_malloc(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "user.oomd_ooms", &value);
3236 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
3237 return r;
3239 if (!isempty(value)) {
3240 r = safe_atou64(value, &n);
3241 if (r < 0)
3242 return r;
3245 increased = n > u->managed_oom_kill_last;
3246 u->managed_oom_kill_last = n;
3248 if (!increased)
3249 return 0;
3251 n = 0;
3252 value = mfree(value);
3253 r = cg_get_xattr_malloc(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "user.oomd_kill", &value);
3254 if (r >= 0 && !isempty(value))
3255 (void) safe_atou64(value, &n);
3257 if (n > 0)
3258 log_unit_struct(u, LOG_NOTICE,
3259 "MESSAGE_ID=" SD_MESSAGE_UNIT_OOMD_KILL_STR,
3260 LOG_UNIT_INVOCATION_ID(u),
3261 LOG_UNIT_MESSAGE(u, "systemd-oomd killed %"PRIu64" process(es) in this unit.", n),
3262 "N_PROCESSES=%" PRIu64, n);
3263 else
3264 log_unit_struct(u, LOG_NOTICE,
3265 "MESSAGE_ID=" SD_MESSAGE_UNIT_OOMD_KILL_STR,
3266 LOG_UNIT_INVOCATION_ID(u),
3267 LOG_UNIT_MESSAGE(u, "systemd-oomd killed some process(es) in this unit."));
3269 unit_notify_cgroup_oom(u, /* ManagedOOM= */ true);
3271 return 1;
3274 int unit_check_oom(Unit *u) {
3275 _cleanup_free_ char *oom_kill = NULL;
3276 bool increased;
3277 uint64_t c;
3278 int r;
3280 if (!u->cgroup_path)
3281 return 0;
3283 r = cg_get_keyed_attribute("memory", u->cgroup_path, "memory.events", STRV_MAKE("oom_kill"), &oom_kill);
3284 if (IN_SET(r, -ENOENT, -ENXIO)) /* Handle gracefully if cgroup or oom_kill attribute don't exist */
3285 c = 0;
3286 else if (r < 0)
3287 return log_unit_debug_errno(u, r, "Failed to read oom_kill field of memory.events cgroup attribute: %m");
3288 else {
3289 r = safe_atou64(oom_kill, &c);
3290 if (r < 0)
3291 return log_unit_debug_errno(u, r, "Failed to parse oom_kill field: %m");
3294 increased = c > u->oom_kill_last;
3295 u->oom_kill_last = c;
3297 if (!increased)
3298 return 0;
3300 log_unit_struct(u, LOG_NOTICE,
3301 "MESSAGE_ID=" SD_MESSAGE_UNIT_OUT_OF_MEMORY_STR,
3302 LOG_UNIT_INVOCATION_ID(u),
3303 LOG_UNIT_MESSAGE(u, "A process of this unit has been killed by the OOM killer."));
3305 unit_notify_cgroup_oom(u, /* ManagedOOM= */ false);
3307 return 1;
3310 static int on_cgroup_oom_event(sd_event_source *s, void *userdata) {
3311 Manager *m = ASSERT_PTR(userdata);
3312 Unit *u;
3313 int r;
3315 assert(s);
3317 u = m->cgroup_oom_queue;
3318 if (!u)
3319 return 0;
3321 assert(u->in_cgroup_oom_queue);
3322 u->in_cgroup_oom_queue = false;
3323 LIST_REMOVE(cgroup_oom_queue, m->cgroup_oom_queue, u);
3325 if (m->cgroup_oom_queue) {
3326 /* More stuff queued, let's make sure we remain enabled */
3327 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
3328 if (r < 0)
3329 log_debug_errno(r, "Failed to reenable cgroup oom event source, ignoring: %m");
3332 (void) unit_check_oom(u);
3333 unit_add_to_gc_queue(u);
3335 return 0;
3338 static void unit_add_to_cgroup_oom_queue(Unit *u) {
3339 int r;
3341 assert(u);
3343 if (u->in_cgroup_oom_queue)
3344 return;
3345 if (!u->cgroup_path)
3346 return;
3348 LIST_PREPEND(cgroup_oom_queue, u->manager->cgroup_oom_queue, u);
3349 u->in_cgroup_oom_queue = true;
3351 /* Trigger the defer event */
3352 if (!u->manager->cgroup_oom_event_source) {
3353 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
3355 r = sd_event_add_defer(u->manager->event, &s, on_cgroup_oom_event, u->manager);
3356 if (r < 0) {
3357 log_error_errno(r, "Failed to create cgroup oom event source: %m");
3358 return;
3361 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_NORMAL-8);
3362 if (r < 0) {
3363 log_error_errno(r, "Failed to set priority of cgroup oom event source: %m");
3364 return;
3367 (void) sd_event_source_set_description(s, "cgroup-oom");
3368 u->manager->cgroup_oom_event_source = TAKE_PTR(s);
3371 r = sd_event_source_set_enabled(u->manager->cgroup_oom_event_source, SD_EVENT_ONESHOT);
3372 if (r < 0)
3373 log_error_errno(r, "Failed to enable cgroup oom event source: %m");
3376 static int unit_check_cgroup_events(Unit *u) {
3377 char *values[2] = {};
3378 int r;
3380 assert(u);
3382 if (!u->cgroup_path)
3383 return 0;
3385 r = cg_get_keyed_attribute_graceful(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events",
3386 STRV_MAKE("populated", "frozen"), values);
3387 if (r < 0)
3388 return r;
3390 /* The cgroup.events notifications can be merged together so act as we saw the given state for the
3391 * first time. The functions we call to handle given state are idempotent, which makes them
3392 * effectively remember the previous state. */
3393 if (values[0]) {
3394 if (streq(values[0], "1"))
3395 unit_remove_from_cgroup_empty_queue(u);
3396 else
3397 unit_add_to_cgroup_empty_queue(u);
3400 /* Disregard freezer state changes due to operations not initiated by us */
3401 if (values[1] && IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_THAWING)) {
3402 if (streq(values[1], "0"))
3403 unit_thawed(u);
3404 else
3405 unit_frozen(u);
3408 free(values[0]);
3409 free(values[1]);
3411 return 0;
3414 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
3415 Manager *m = ASSERT_PTR(userdata);
3417 assert(s);
3418 assert(fd >= 0);
3420 for (;;) {
3421 union inotify_event_buffer buffer;
3422 ssize_t l;
3424 l = read(fd, &buffer, sizeof(buffer));
3425 if (l < 0) {
3426 if (ERRNO_IS_TRANSIENT(errno))
3427 return 0;
3429 return log_error_errno(errno, "Failed to read control group inotify events: %m");
3432 FOREACH_INOTIFY_EVENT_WARN(e, buffer, l) {
3433 Unit *u;
3435 if (e->wd < 0)
3436 /* Queue overflow has no watch descriptor */
3437 continue;
3439 if (e->mask & IN_IGNORED)
3440 /* The watch was just removed */
3441 continue;
3443 /* Note that inotify might deliver events for a watch even after it was removed,
3444 * because it was queued before the removal. Let's ignore this here safely. */
3446 u = hashmap_get(m->cgroup_control_inotify_wd_unit, INT_TO_PTR(e->wd));
3447 if (u)
3448 unit_check_cgroup_events(u);
3450 u = hashmap_get(m->cgroup_memory_inotify_wd_unit, INT_TO_PTR(e->wd));
3451 if (u)
3452 unit_add_to_cgroup_oom_queue(u);
3457 static int cg_bpf_mask_supported(CGroupMask *ret) {
3458 CGroupMask mask = 0;
3459 int r;
3461 /* BPF-based firewall */
3462 r = bpf_firewall_supported();
3463 if (r < 0)
3464 return r;
3465 if (r > 0)
3466 mask |= CGROUP_MASK_BPF_FIREWALL;
3468 /* BPF-based device access control */
3469 r = bpf_devices_supported();
3470 if (r < 0)
3471 return r;
3472 if (r > 0)
3473 mask |= CGROUP_MASK_BPF_DEVICES;
3475 /* BPF pinned prog */
3476 r = bpf_foreign_supported();
3477 if (r < 0)
3478 return r;
3479 if (r > 0)
3480 mask |= CGROUP_MASK_BPF_FOREIGN;
3482 /* BPF-based bind{4|6} hooks */
3483 r = bpf_socket_bind_supported();
3484 if (r < 0)
3485 return r;
3486 if (r > 0)
3487 mask |= CGROUP_MASK_BPF_SOCKET_BIND;
3489 /* BPF-based cgroup_skb/{egress|ingress} hooks */
3490 r = restrict_network_interfaces_supported();
3491 if (r < 0)
3492 return r;
3493 if (r > 0)
3494 mask |= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES;
3496 *ret = mask;
3497 return 0;
3500 int manager_setup_cgroup(Manager *m) {
3501 _cleanup_free_ char *path = NULL;
3502 const char *scope_path;
3503 int r, all_unified;
3504 CGroupMask mask;
3505 char *e;
3507 assert(m);
3509 /* 1. Determine hierarchy */
3510 m->cgroup_root = mfree(m->cgroup_root);
3511 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
3512 if (r < 0)
3513 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
3515 /* Chop off the init scope, if we are already located in it */
3516 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
3518 /* LEGACY: Also chop off the system slice if we are in
3519 * it. This is to support live upgrades from older systemd
3520 * versions where PID 1 was moved there. Also see
3521 * cg_get_root_path(). */
3522 if (!e && MANAGER_IS_SYSTEM(m)) {
3523 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
3524 if (!e)
3525 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
3527 if (e)
3528 *e = 0;
3530 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
3531 * easily prepend it everywhere. */
3532 delete_trailing_chars(m->cgroup_root, "/");
3534 /* 2. Show data */
3535 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
3536 if (r < 0)
3537 return log_error_errno(r, "Cannot find cgroup mount point: %m");
3539 r = cg_unified();
3540 if (r < 0)
3541 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
3543 all_unified = cg_all_unified();
3544 if (all_unified < 0)
3545 return log_error_errno(all_unified, "Couldn't determine whether we are in all unified mode: %m");
3546 if (all_unified > 0)
3547 log_debug("Unified cgroup hierarchy is located at %s.", path);
3548 else {
3549 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
3550 if (r < 0)
3551 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
3552 if (r > 0)
3553 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
3554 else
3555 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
3558 /* 3. Allocate cgroup empty defer event source */
3559 m->cgroup_empty_event_source = sd_event_source_disable_unref(m->cgroup_empty_event_source);
3560 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
3561 if (r < 0)
3562 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
3564 /* Schedule cgroup empty checks early, but after having processed service notification messages or
3565 * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of
3566 * notification, and we collected the metadata the notification and SIGCHLD stuff offers first. */
3567 r = sd_event_source_set_priority(m->cgroup_empty_event_source, SD_EVENT_PRIORITY_NORMAL-5);
3568 if (r < 0)
3569 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
3571 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
3572 if (r < 0)
3573 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
3575 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
3577 /* 4. Install notifier inotify object, or agent */
3578 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
3580 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
3582 m->cgroup_inotify_event_source = sd_event_source_disable_unref(m->cgroup_inotify_event_source);
3583 safe_close(m->cgroup_inotify_fd);
3585 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
3586 if (m->cgroup_inotify_fd < 0)
3587 return log_error_errno(errno, "Failed to create control group inotify object: %m");
3589 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
3590 if (r < 0)
3591 return log_error_errno(r, "Failed to watch control group inotify object: %m");
3593 /* Process cgroup empty notifications early. Note that when this event is dispatched it'll
3594 * just add the unit to a cgroup empty queue, hence let's run earlier than that. Also see
3595 * handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
3596 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-9);
3597 if (r < 0)
3598 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
3600 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
3602 } else if (MANAGER_IS_SYSTEM(m) && manager_owns_host_root_cgroup(m) && !MANAGER_IS_TEST_RUN(m)) {
3604 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
3605 * since it does not generate events when control groups with children run empty. */
3607 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUPS_AGENT_PATH);
3608 if (r < 0)
3609 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
3610 else if (r > 0)
3611 log_debug("Installed release agent.");
3612 else if (r == 0)
3613 log_debug("Release agent already installed.");
3616 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
3617 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
3618 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
3619 if (r >= 0) {
3620 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
3621 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
3622 if (r < 0)
3623 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
3625 /* 6. And pin it, so that it cannot be unmounted */
3626 safe_close(m->pin_cgroupfs_fd);
3627 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
3628 if (m->pin_cgroupfs_fd < 0)
3629 return log_error_errno(errno, "Failed to open pin file: %m");
3631 } else if (!MANAGER_IS_TEST_RUN(m))
3632 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
3634 /* 7. Always enable hierarchical support if it exists... */
3635 if (!all_unified && !MANAGER_IS_TEST_RUN(m))
3636 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
3638 /* 8. Figure out which controllers are supported */
3639 r = cg_mask_supported_subtree(m->cgroup_root, &m->cgroup_supported);
3640 if (r < 0)
3641 return log_error_errno(r, "Failed to determine supported controllers: %m");
3643 /* 9. Figure out which bpf-based pseudo-controllers are supported */
3644 r = cg_bpf_mask_supported(&mask);
3645 if (r < 0)
3646 return log_error_errno(r, "Failed to determine supported bpf-based pseudo-controllers: %m");
3647 m->cgroup_supported |= mask;
3649 /* 10. Log which controllers are supported */
3650 for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
3651 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c),
3652 yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
3654 return 0;
3657 void manager_shutdown_cgroup(Manager *m, bool delete) {
3658 assert(m);
3660 /* We can't really delete the group, since we are in it. But
3661 * let's trim it. */
3662 if (delete && m->cgroup_root && !FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
3663 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
3665 m->cgroup_empty_event_source = sd_event_source_disable_unref(m->cgroup_empty_event_source);
3667 m->cgroup_control_inotify_wd_unit = hashmap_free(m->cgroup_control_inotify_wd_unit);
3668 m->cgroup_memory_inotify_wd_unit = hashmap_free(m->cgroup_memory_inotify_wd_unit);
3670 m->cgroup_inotify_event_source = sd_event_source_disable_unref(m->cgroup_inotify_event_source);
3671 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
3673 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
3675 m->cgroup_root = mfree(m->cgroup_root);
3678 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
3679 char *p;
3680 Unit *u;
3682 assert(m);
3683 assert(cgroup);
3685 u = hashmap_get(m->cgroup_unit, cgroup);
3686 if (u)
3687 return u;
3689 p = strdupa_safe(cgroup);
3690 for (;;) {
3691 char *e;
3693 e = strrchr(p, '/');
3694 if (!e || e == p)
3695 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
3697 *e = 0;
3699 u = hashmap_get(m->cgroup_unit, p);
3700 if (u)
3701 return u;
3705 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
3706 _cleanup_free_ char *cgroup = NULL;
3708 assert(m);
3710 if (!pid_is_valid(pid))
3711 return NULL;
3713 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup) < 0)
3714 return NULL;
3716 return manager_get_unit_by_cgroup(m, cgroup);
3719 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
3720 Unit *u, **array;
3722 assert(m);
3724 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
3725 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
3726 * relevant one as children of the process will be assigned to that one, too, before all else. */
3728 if (!pid_is_valid(pid))
3729 return NULL;
3731 if (pid == getpid_cached())
3732 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
3734 u = manager_get_unit_by_pid_cgroup(m, pid);
3735 if (u)
3736 return u;
3738 u = hashmap_get(m->watch_pids, PID_TO_PTR(pid));
3739 if (u)
3740 return u;
3742 array = hashmap_get(m->watch_pids, PID_TO_PTR(-pid));
3743 if (array)
3744 return array[0];
3746 return NULL;
3749 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
3750 Unit *u;
3752 assert(m);
3753 assert(cgroup);
3755 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
3756 * or from the --system instance */
3758 log_debug("Got cgroup empty notification for: %s", cgroup);
3760 u = manager_get_unit_by_cgroup(m, cgroup);
3761 if (!u)
3762 return 0;
3764 unit_add_to_cgroup_empty_queue(u);
3765 return 1;
3768 int unit_get_memory_available(Unit *u, uint64_t *ret) {
3769 uint64_t unit_current, available = UINT64_MAX;
3770 CGroupContext *unit_context;
3771 const char *memory_file;
3772 int r;
3774 assert(u);
3775 assert(ret);
3777 /* If data from cgroups can be accessed, try to find out how much more memory a unit can
3778 * claim before hitting the configured cgroup limits (if any). Consider both MemoryHigh
3779 * and MemoryMax, and also any slice the unit might be nested below. */
3781 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
3782 return -ENODATA;
3784 if (!u->cgroup_path)
3785 return -ENODATA;
3787 /* The root cgroup doesn't expose this information */
3788 if (unit_has_host_root_cgroup(u))
3789 return -ENODATA;
3791 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
3792 return -ENODATA;
3794 r = cg_all_unified();
3795 if (r < 0)
3796 return r;
3797 memory_file = r > 0 ? "memory.current" : "memory.usage_in_bytes";
3799 r = cg_get_attribute_as_uint64("memory", u->cgroup_path, memory_file, &unit_current);
3800 if (r < 0)
3801 return r;
3803 assert_se(unit_context = unit_get_cgroup_context(u));
3805 if (unit_context->memory_max != UINT64_MAX || unit_context->memory_high != UINT64_MAX)
3806 available = LESS_BY(MIN(unit_context->memory_max, unit_context->memory_high), unit_current);
3808 for (Unit *slice = UNIT_GET_SLICE(u); slice; slice = UNIT_GET_SLICE(slice)) {
3809 uint64_t slice_current, slice_available = UINT64_MAX;
3810 CGroupContext *slice_context;
3812 /* No point in continuing if we can't go any lower */
3813 if (available == 0)
3814 break;
3816 if (!slice->cgroup_path)
3817 continue;
3819 slice_context = unit_get_cgroup_context(slice);
3820 if (!slice_context)
3821 continue;
3823 if (slice_context->memory_max == UINT64_MAX && slice_context->memory_high == UINT64_MAX)
3824 continue;
3826 r = cg_get_attribute_as_uint64("memory", slice->cgroup_path, memory_file, &slice_current);
3827 if (r < 0)
3828 continue;
3830 slice_available = LESS_BY(MIN(slice_context->memory_max, slice_context->memory_high), slice_current);
3831 available = MIN(slice_available, available);
3834 *ret = available;
3836 return 0;
3839 int unit_get_memory_current(Unit *u, uint64_t *ret) {
3840 int r;
3842 assert(u);
3843 assert(ret);
3845 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
3846 return -ENODATA;
3848 if (!u->cgroup_path)
3849 return -ENODATA;
3851 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3852 if (unit_has_host_root_cgroup(u))
3853 return procfs_memory_get_used(ret);
3855 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
3856 return -ENODATA;
3858 r = cg_all_unified();
3859 if (r < 0)
3860 return r;
3862 return cg_get_attribute_as_uint64("memory", u->cgroup_path, r > 0 ? "memory.current" : "memory.usage_in_bytes", ret);
3865 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
3866 assert(u);
3867 assert(ret);
3869 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
3870 return -ENODATA;
3872 if (!u->cgroup_path)
3873 return -ENODATA;
3875 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3876 if (unit_has_host_root_cgroup(u))
3877 return procfs_tasks_get_current(ret);
3879 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
3880 return -ENODATA;
3882 return cg_get_attribute_as_uint64("pids", u->cgroup_path, "pids.current", ret);
3885 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
3886 uint64_t ns;
3887 int r;
3889 assert(u);
3890 assert(ret);
3892 if (!u->cgroup_path)
3893 return -ENODATA;
3895 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3896 if (unit_has_host_root_cgroup(u))
3897 return procfs_cpu_get_usage(ret);
3899 /* Requisite controllers for CPU accounting are not enabled */
3900 if ((get_cpu_accounting_mask() & ~u->cgroup_realized_mask) != 0)
3901 return -ENODATA;
3903 r = cg_all_unified();
3904 if (r < 0)
3905 return r;
3906 if (r > 0) {
3907 _cleanup_free_ char *val = NULL;
3908 uint64_t us;
3910 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
3911 if (IN_SET(r, -ENOENT, -ENXIO))
3912 return -ENODATA;
3913 if (r < 0)
3914 return r;
3916 r = safe_atou64(val, &us);
3917 if (r < 0)
3918 return r;
3920 ns = us * NSEC_PER_USEC;
3921 } else
3922 return cg_get_attribute_as_uint64("cpuacct", u->cgroup_path, "cpuacct.usage", ret);
3924 *ret = ns;
3925 return 0;
3928 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
3929 nsec_t ns;
3930 int r;
3932 assert(u);
3934 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
3935 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
3936 * call this function with a NULL return value. */
3938 if (!UNIT_CGROUP_BOOL(u, cpu_accounting))
3939 return -ENODATA;
3941 r = unit_get_cpu_usage_raw(u, &ns);
3942 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
3943 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
3944 * cached value. */
3946 if (ret)
3947 *ret = u->cpu_usage_last;
3948 return 0;
3950 if (r < 0)
3951 return r;
3953 if (ns > u->cpu_usage_base)
3954 ns -= u->cpu_usage_base;
3955 else
3956 ns = 0;
3958 u->cpu_usage_last = ns;
3959 if (ret)
3960 *ret = ns;
3962 return 0;
3965 int unit_get_ip_accounting(
3966 Unit *u,
3967 CGroupIPAccountingMetric metric,
3968 uint64_t *ret) {
3970 uint64_t value;
3971 int fd, r;
3973 assert(u);
3974 assert(metric >= 0);
3975 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
3976 assert(ret);
3978 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
3979 return -ENODATA;
3981 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
3982 u->ip_accounting_ingress_map_fd :
3983 u->ip_accounting_egress_map_fd;
3984 if (fd < 0)
3985 return -ENODATA;
3987 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
3988 r = bpf_firewall_read_accounting(fd, &value, NULL);
3989 else
3990 r = bpf_firewall_read_accounting(fd, NULL, &value);
3991 if (r < 0)
3992 return r;
3994 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
3995 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
3996 * ip_accounting_extra[] field, and add them in here transparently. */
3998 *ret = value + u->ip_accounting_extra[metric];
4000 return r;
4003 static int unit_get_io_accounting_raw(Unit *u, uint64_t ret[static _CGROUP_IO_ACCOUNTING_METRIC_MAX]) {
4004 static const char *const field_names[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
4005 [CGROUP_IO_READ_BYTES] = "rbytes=",
4006 [CGROUP_IO_WRITE_BYTES] = "wbytes=",
4007 [CGROUP_IO_READ_OPERATIONS] = "rios=",
4008 [CGROUP_IO_WRITE_OPERATIONS] = "wios=",
4010 uint64_t acc[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {};
4011 _cleanup_free_ char *path = NULL;
4012 _cleanup_fclose_ FILE *f = NULL;
4013 int r;
4015 assert(u);
4017 if (!u->cgroup_path)
4018 return -ENODATA;
4020 if (unit_has_host_root_cgroup(u))
4021 return -ENODATA; /* TODO: return useful data for the top-level cgroup */
4023 r = cg_all_unified();
4024 if (r < 0)
4025 return r;
4026 if (r == 0) /* TODO: support cgroupv1 */
4027 return -ENODATA;
4029 if (!FLAGS_SET(u->cgroup_realized_mask, CGROUP_MASK_IO))
4030 return -ENODATA;
4032 r = cg_get_path("io", u->cgroup_path, "io.stat", &path);
4033 if (r < 0)
4034 return r;
4036 f = fopen(path, "re");
4037 if (!f)
4038 return -errno;
4040 for (;;) {
4041 _cleanup_free_ char *line = NULL;
4042 const char *p;
4044 r = read_line(f, LONG_LINE_MAX, &line);
4045 if (r < 0)
4046 return r;
4047 if (r == 0)
4048 break;
4050 p = line;
4051 p += strcspn(p, WHITESPACE); /* Skip over device major/minor */
4052 p += strspn(p, WHITESPACE); /* Skip over following whitespace */
4054 for (;;) {
4055 _cleanup_free_ char *word = NULL;
4057 r = extract_first_word(&p, &word, NULL, EXTRACT_RETAIN_ESCAPE);
4058 if (r < 0)
4059 return r;
4060 if (r == 0)
4061 break;
4063 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
4064 const char *x;
4066 x = startswith(word, field_names[i]);
4067 if (x) {
4068 uint64_t w;
4070 r = safe_atou64(x, &w);
4071 if (r < 0)
4072 return r;
4074 /* Sum up the stats of all devices */
4075 acc[i] += w;
4076 break;
4082 memcpy(ret, acc, sizeof(acc));
4083 return 0;
4086 int unit_get_io_accounting(
4087 Unit *u,
4088 CGroupIOAccountingMetric metric,
4089 bool allow_cache,
4090 uint64_t *ret) {
4092 uint64_t raw[_CGROUP_IO_ACCOUNTING_METRIC_MAX];
4093 int r;
4095 /* Retrieve an IO account parameter. This will subtract the counter when the unit was started. */
4097 if (!UNIT_CGROUP_BOOL(u, io_accounting))
4098 return -ENODATA;
4100 if (allow_cache && u->io_accounting_last[metric] != UINT64_MAX)
4101 goto done;
4103 r = unit_get_io_accounting_raw(u, raw);
4104 if (r == -ENODATA && u->io_accounting_last[metric] != UINT64_MAX)
4105 goto done;
4106 if (r < 0)
4107 return r;
4109 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
4110 /* Saturated subtraction */
4111 if (raw[i] > u->io_accounting_base[i])
4112 u->io_accounting_last[i] = raw[i] - u->io_accounting_base[i];
4113 else
4114 u->io_accounting_last[i] = 0;
4117 done:
4118 if (ret)
4119 *ret = u->io_accounting_last[metric];
4121 return 0;
4124 int unit_reset_cpu_accounting(Unit *u) {
4125 int r;
4127 assert(u);
4129 u->cpu_usage_last = NSEC_INFINITY;
4131 r = unit_get_cpu_usage_raw(u, &u->cpu_usage_base);
4132 if (r < 0) {
4133 u->cpu_usage_base = 0;
4134 return r;
4137 return 0;
4140 int unit_reset_ip_accounting(Unit *u) {
4141 int r = 0, q = 0;
4143 assert(u);
4145 if (u->ip_accounting_ingress_map_fd >= 0)
4146 r = bpf_firewall_reset_accounting(u->ip_accounting_ingress_map_fd);
4148 if (u->ip_accounting_egress_map_fd >= 0)
4149 q = bpf_firewall_reset_accounting(u->ip_accounting_egress_map_fd);
4151 zero(u->ip_accounting_extra);
4153 return r < 0 ? r : q;
4156 int unit_reset_io_accounting(Unit *u) {
4157 int r;
4159 assert(u);
4161 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++)
4162 u->io_accounting_last[i] = UINT64_MAX;
4164 r = unit_get_io_accounting_raw(u, u->io_accounting_base);
4165 if (r < 0) {
4166 zero(u->io_accounting_base);
4167 return r;
4170 return 0;
4173 int unit_reset_accounting(Unit *u) {
4174 int r, q, v;
4176 assert(u);
4178 r = unit_reset_cpu_accounting(u);
4179 q = unit_reset_io_accounting(u);
4180 v = unit_reset_ip_accounting(u);
4182 return r < 0 ? r : q < 0 ? q : v;
4185 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
4186 assert(u);
4188 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4189 return;
4191 if (m == 0)
4192 return;
4194 /* always invalidate compat pairs together */
4195 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
4196 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
4198 if (m & (CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT))
4199 m |= CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT;
4201 if (FLAGS_SET(u->cgroup_invalidated_mask, m)) /* NOP? */
4202 return;
4204 u->cgroup_invalidated_mask |= m;
4205 unit_add_to_cgroup_realize_queue(u);
4208 void unit_invalidate_cgroup_bpf(Unit *u) {
4209 assert(u);
4211 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4212 return;
4214 if (u->cgroup_invalidated_mask & CGROUP_MASK_BPF_FIREWALL) /* NOP? */
4215 return;
4217 u->cgroup_invalidated_mask |= CGROUP_MASK_BPF_FIREWALL;
4218 unit_add_to_cgroup_realize_queue(u);
4220 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
4221 * list of our children includes our own. */
4222 if (u->type == UNIT_SLICE) {
4223 Unit *member;
4225 UNIT_FOREACH_DEPENDENCY(member, u, UNIT_ATOM_SLICE_OF)
4226 unit_invalidate_cgroup_bpf(member);
4230 void unit_cgroup_catchup(Unit *u) {
4231 assert(u);
4233 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4234 return;
4236 /* We dropped the inotify watch during reexec/reload, so we need to
4237 * check these as they may have changed.
4238 * Note that (currently) the kernel doesn't actually update cgroup
4239 * file modification times, so we can't just serialize and then check
4240 * the mtime for file(s) we are interested in. */
4241 (void) unit_check_cgroup_events(u);
4242 unit_add_to_cgroup_oom_queue(u);
4245 bool unit_cgroup_delegate(Unit *u) {
4246 CGroupContext *c;
4248 assert(u);
4250 if (!UNIT_VTABLE(u)->can_delegate)
4251 return false;
4253 c = unit_get_cgroup_context(u);
4254 if (!c)
4255 return false;
4257 return c->delegate;
4260 void manager_invalidate_startup_units(Manager *m) {
4261 Unit *u;
4263 assert(m);
4265 SET_FOREACH(u, m->startup_units)
4266 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO|CGROUP_MASK_CPUSET);
4269 static int unit_get_nice(Unit *u) {
4270 ExecContext *ec;
4272 ec = unit_get_exec_context(u);
4273 return ec ? ec->nice : 0;
4276 static uint64_t unit_get_cpu_weight(Unit *u) {
4277 ManagerState state = manager_state(u->manager);
4278 CGroupContext *cc;
4280 cc = unit_get_cgroup_context(u);
4281 return cc ? cgroup_context_cpu_weight(cc, state) : CGROUP_WEIGHT_DEFAULT;
4284 int compare_job_priority(const void *a, const void *b) {
4285 const Job *x = a, *y = b;
4286 int nice_x, nice_y;
4287 uint64_t weight_x, weight_y;
4288 int ret;
4290 if ((ret = CMP(x->unit->type, y->unit->type)) != 0)
4291 return -ret;
4293 weight_x = unit_get_cpu_weight(x->unit);
4294 weight_y = unit_get_cpu_weight(y->unit);
4296 if ((ret = CMP(weight_x, weight_y)) != 0)
4297 return -ret;
4299 nice_x = unit_get_nice(x->unit);
4300 nice_y = unit_get_nice(y->unit);
4302 if ((ret = CMP(nice_x, nice_y)) != 0)
4303 return ret;
4305 return strcmp(x->unit->id, y->unit->id);
4308 int unit_cgroup_freezer_action(Unit *u, FreezerAction action) {
4309 _cleanup_free_ char *path = NULL;
4310 FreezerState target, kernel = _FREEZER_STATE_INVALID;
4311 int r, ret;
4313 assert(u);
4314 assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
4316 if (!cg_freezer_supported())
4317 return 0;
4319 /* Ignore all requests to thaw init.scope or -.slice and reject all requests to freeze them */
4320 if (unit_has_name(u, SPECIAL_ROOT_SLICE) || unit_has_name(u, SPECIAL_INIT_SCOPE))
4321 return action == FREEZER_FREEZE ? -EPERM : 0;
4323 if (!u->cgroup_realized)
4324 return -EBUSY;
4326 if (action == FREEZER_THAW) {
4327 Unit *slice = UNIT_GET_SLICE(u);
4329 if (slice) {
4330 r = unit_cgroup_freezer_action(slice, FREEZER_THAW);
4331 if (r < 0)
4332 return log_unit_error_errno(u, r, "Failed to thaw slice %s of unit: %m", slice->id);
4336 target = action == FREEZER_FREEZE ? FREEZER_FROZEN : FREEZER_RUNNING;
4338 r = unit_freezer_state_kernel(u, &kernel);
4339 if (r < 0)
4340 log_unit_debug_errno(u, r, "Failed to obtain cgroup freezer state: %m");
4342 if (target == kernel) {
4343 u->freezer_state = target;
4344 if (action == FREEZER_FREEZE)
4345 return 0;
4346 ret = 0;
4347 } else
4348 ret = 1;
4350 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.freeze", &path);
4351 if (r < 0)
4352 return r;
4354 log_unit_debug(u, "%s unit.", action == FREEZER_FREEZE ? "Freezing" : "Thawing");
4356 if (target != kernel) {
4357 if (action == FREEZER_FREEZE)
4358 u->freezer_state = FREEZER_FREEZING;
4359 else
4360 u->freezer_state = FREEZER_THAWING;
4363 r = write_string_file(path, one_zero(action == FREEZER_FREEZE), WRITE_STRING_FILE_DISABLE_BUFFER);
4364 if (r < 0)
4365 return r;
4367 return ret;
4370 int unit_get_cpuset(Unit *u, CPUSet *cpus, const char *name) {
4371 _cleanup_free_ char *v = NULL;
4372 int r;
4374 assert(u);
4375 assert(cpus);
4377 if (!u->cgroup_path)
4378 return -ENODATA;
4380 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUSET) == 0)
4381 return -ENODATA;
4383 r = cg_all_unified();
4384 if (r < 0)
4385 return r;
4386 if (r == 0)
4387 return -ENODATA;
4389 r = cg_get_attribute("cpuset", u->cgroup_path, name, &v);
4390 if (r == -ENOENT)
4391 return -ENODATA;
4392 if (r < 0)
4393 return r;
4395 return parse_cpu_set_full(v, cpus, false, NULL, NULL, 0, NULL);
4398 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
4399 [CGROUP_DEVICE_POLICY_AUTO] = "auto",
4400 [CGROUP_DEVICE_POLICY_CLOSED] = "closed",
4401 [CGROUP_DEVICE_POLICY_STRICT] = "strict",
4404 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);
4406 static const char* const freezer_action_table[_FREEZER_ACTION_MAX] = {
4407 [FREEZER_FREEZE] = "freeze",
4408 [FREEZER_THAW] = "thaw",
4411 DEFINE_STRING_TABLE_LOOKUP(freezer_action, FreezerAction);
4413 static const char* const cgroup_pressure_watch_table[_CGROUP_PRESSURE_WATCH_MAX] = {
4414 [CGROUP_PRESSURE_WATCH_OFF] = "off",
4415 [CGROUP_PRESSURE_WATCH_AUTO] = "auto",
4416 [CGROUP_PRESSURE_WATCH_ON] = "on",
4417 [CGROUP_PRESSURE_WATCH_SKIP] = "skip",
4420 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(cgroup_pressure_watch, CGroupPressureWatch, CGROUP_PRESSURE_WATCH_ON);