1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
5 #include "sd-messages.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"
20 #include "devnum-util.h"
23 #include "firewall-util.h"
24 #include "in-addr-prefix-util.h"
25 #include "inotify-util.h"
27 #include "ip-protocol-list.h"
28 #include "limits-util.h"
29 #include "nulstr-util.h"
30 #include "parse-util.h"
31 #include "path-util.h"
32 #include "percent-util.h"
33 #include "process-util.h"
34 #include "procfs-util.h"
35 #include "restrict-ifaces.h"
37 #include "stdio-util.h"
38 #include "string-table.h"
39 #include "string-util.h"
43 #include "bpf-dlopen.h"
45 #include "bpf/restrict_fs/restrict-fs-skel.h"
48 #define CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
50 /* Returns the log level to use when cgroup attribute writes fail. When an attribute is missing or we have access
51 * problems we downgrade to LOG_DEBUG. This is supposed to be nice to container managers and kernels which want to mask
52 * out specific attributes from us. */
53 #define LOG_LEVEL_CGROUP_WRITE(r) (IN_SET(abs(r), ENOENT, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING)
55 uint64_t cgroup_tasks_max_resolve(const CGroupTasksMax
*tasks_max
) {
56 if (tasks_max
->scale
== 0)
57 return tasks_max
->value
;
59 return system_tasks_max_scale(tasks_max
->value
, tasks_max
->scale
);
62 bool manager_owns_host_root_cgroup(Manager
*m
) {
65 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
66 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
67 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
68 * we run in any kind of container virtualization. */
70 if (MANAGER_IS_USER(m
))
73 if (detect_container() > 0)
76 return empty_or_root(m
->cgroup_root
);
79 bool unit_has_startup_cgroup_constraints(Unit
*u
) {
82 /* Returns true if this unit has any directives which apply during
83 * startup/shutdown phases. */
87 c
= unit_get_cgroup_context(u
);
91 return c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
92 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
93 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
94 c
->startup_cpuset_cpus
.set
||
95 c
->startup_cpuset_mems
.set
||
96 c
->startup_memory_high_set
||
97 c
->startup_memory_max_set
||
98 c
->startup_memory_swap_max_set
||
99 c
->startup_memory_zswap_max_set
||
100 c
->startup_memory_low_set
;
103 bool unit_has_host_root_cgroup(Unit
*u
) {
106 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
107 * the manager manages the root cgroup. */
109 if (!manager_owns_host_root_cgroup(u
->manager
))
112 return unit_has_name(u
, SPECIAL_ROOT_SLICE
);
115 static int set_attribute_and_warn(Unit
*u
, const char *controller
, const char *attribute
, const char *value
) {
118 r
= cg_set_attribute(controller
, u
->cgroup_path
, attribute
, value
);
120 log_unit_full_errno(u
, LOG_LEVEL_CGROUP_WRITE(r
), r
, "Failed to set '%s' attribute on '%s' to '%.*s': %m",
121 strna(attribute
), empty_to_root(u
->cgroup_path
), (int) strcspn(value
, NEWLINE
), value
);
126 static void cgroup_compat_warn(void) {
127 static bool cgroup_compat_warned
= false;
129 if (cgroup_compat_warned
)
132 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
133 "See cgroup-compat debug messages for details.");
135 cgroup_compat_warned
= true;
138 #define log_cgroup_compat(unit, fmt, ...) do { \
139 cgroup_compat_warn(); \
140 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
143 void cgroup_context_init(CGroupContext
*c
) {
146 /* Initialize everything to the kernel defaults. When initializing a bool member to 'true', make
147 * sure to serialize in execute-serialize.c using serialize_bool() instead of
148 * serialize_bool_elide(), as sd-executor will initialize here to 'true', but serialize_bool_elide()
149 * skips serialization if the value is 'false' (as that's the common default), so if the value at
150 * runtime is zero it would be lost after deserialization. Same when initializing uint64_t and other
151 * values, update/add a conditional serialization check. This is to minimize the amount of
152 * serialized data that is sent to the sd-executor, so that there is less work to do on the default
155 *c
= (CGroupContext
) {
156 .cpu_weight
= CGROUP_WEIGHT_INVALID
,
157 .startup_cpu_weight
= CGROUP_WEIGHT_INVALID
,
158 .cpu_quota_per_sec_usec
= USEC_INFINITY
,
159 .cpu_quota_period_usec
= USEC_INFINITY
,
161 .cpu_shares
= CGROUP_CPU_SHARES_INVALID
,
162 .startup_cpu_shares
= CGROUP_CPU_SHARES_INVALID
,
164 .memory_high
= CGROUP_LIMIT_MAX
,
165 .startup_memory_high
= CGROUP_LIMIT_MAX
,
166 .memory_max
= CGROUP_LIMIT_MAX
,
167 .startup_memory_max
= CGROUP_LIMIT_MAX
,
168 .memory_swap_max
= CGROUP_LIMIT_MAX
,
169 .startup_memory_swap_max
= CGROUP_LIMIT_MAX
,
170 .memory_zswap_max
= CGROUP_LIMIT_MAX
,
171 .startup_memory_zswap_max
= CGROUP_LIMIT_MAX
,
173 .memory_limit
= CGROUP_LIMIT_MAX
,
175 .io_weight
= CGROUP_WEIGHT_INVALID
,
176 .startup_io_weight
= CGROUP_WEIGHT_INVALID
,
178 .blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
,
179 .startup_blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
,
181 .tasks_max
= CGROUP_TASKS_MAX_UNSET
,
183 .moom_swap
= MANAGED_OOM_AUTO
,
184 .moom_mem_pressure
= MANAGED_OOM_AUTO
,
185 .moom_preference
= MANAGED_OOM_PREFERENCE_NONE
,
187 .memory_pressure_watch
= _CGROUP_PRESSURE_WATCH_INVALID
,
188 .memory_pressure_threshold_usec
= USEC_INFINITY
,
192 void cgroup_context_free_device_allow(CGroupContext
*c
, CGroupDeviceAllow
*a
) {
196 LIST_REMOVE(device_allow
, c
->device_allow
, a
);
201 void cgroup_context_free_io_device_weight(CGroupContext
*c
, CGroupIODeviceWeight
*w
) {
205 LIST_REMOVE(device_weights
, c
->io_device_weights
, w
);
210 void cgroup_context_free_io_device_latency(CGroupContext
*c
, CGroupIODeviceLatency
*l
) {
214 LIST_REMOVE(device_latencies
, c
->io_device_latencies
, l
);
219 void cgroup_context_free_io_device_limit(CGroupContext
*c
, CGroupIODeviceLimit
*l
) {
223 LIST_REMOVE(device_limits
, c
->io_device_limits
, l
);
228 void cgroup_context_free_blockio_device_weight(CGroupContext
*c
, CGroupBlockIODeviceWeight
*w
) {
232 LIST_REMOVE(device_weights
, c
->blockio_device_weights
, w
);
237 void cgroup_context_free_blockio_device_bandwidth(CGroupContext
*c
, CGroupBlockIODeviceBandwidth
*b
) {
241 LIST_REMOVE(device_bandwidths
, c
->blockio_device_bandwidths
, b
);
246 void cgroup_context_remove_bpf_foreign_program(CGroupContext
*c
, CGroupBPFForeignProgram
*p
) {
250 LIST_REMOVE(programs
, c
->bpf_foreign_programs
, p
);
255 void cgroup_context_remove_socket_bind(CGroupSocketBindItem
**head
) {
258 LIST_CLEAR(socket_bind_items
, *head
, free
);
261 void cgroup_context_done(CGroupContext
*c
) {
264 while (c
->io_device_weights
)
265 cgroup_context_free_io_device_weight(c
, c
->io_device_weights
);
267 while (c
->io_device_latencies
)
268 cgroup_context_free_io_device_latency(c
, c
->io_device_latencies
);
270 while (c
->io_device_limits
)
271 cgroup_context_free_io_device_limit(c
, c
->io_device_limits
);
273 while (c
->blockio_device_weights
)
274 cgroup_context_free_blockio_device_weight(c
, c
->blockio_device_weights
);
276 while (c
->blockio_device_bandwidths
)
277 cgroup_context_free_blockio_device_bandwidth(c
, c
->blockio_device_bandwidths
);
279 while (c
->device_allow
)
280 cgroup_context_free_device_allow(c
, c
->device_allow
);
282 cgroup_context_remove_socket_bind(&c
->socket_bind_allow
);
283 cgroup_context_remove_socket_bind(&c
->socket_bind_deny
);
285 c
->ip_address_allow
= set_free(c
->ip_address_allow
);
286 c
->ip_address_deny
= set_free(c
->ip_address_deny
);
288 c
->ip_filters_ingress
= strv_free(c
->ip_filters_ingress
);
289 c
->ip_filters_egress
= strv_free(c
->ip_filters_egress
);
291 while (c
->bpf_foreign_programs
)
292 cgroup_context_remove_bpf_foreign_program(c
, c
->bpf_foreign_programs
);
294 c
->restrict_network_interfaces
= set_free_free(c
->restrict_network_interfaces
);
296 cpu_set_reset(&c
->cpuset_cpus
);
297 cpu_set_reset(&c
->startup_cpuset_cpus
);
298 cpu_set_reset(&c
->cpuset_mems
);
299 cpu_set_reset(&c
->startup_cpuset_mems
);
301 c
->delegate_subgroup
= mfree(c
->delegate_subgroup
);
303 nft_set_context_clear(&c
->nft_set_context
);
306 static int unit_get_kernel_memory_limit(Unit
*u
, const char *file
, uint64_t *ret
) {
309 if (!u
->cgroup_realized
)
312 return cg_get_attribute_as_uint64("memory", u
->cgroup_path
, file
, ret
);
315 static int unit_compare_memory_limit(Unit
*u
, const char *property_name
, uint64_t *ret_unit_value
, uint64_t *ret_kernel_value
) {
322 /* Compare kernel memcg configuration against our internal systemd state. Unsupported (and will
323 * return -ENODATA) on cgroup v1.
328 * 0: If the kernel memory setting doesn't match our configuration.
329 * >0: If the kernel memory setting matches our configuration.
331 * The following values are only guaranteed to be populated on return >=0:
333 * - ret_unit_value will contain our internal expected value for the unit, page-aligned.
334 * - ret_kernel_value will contain the actual value presented by the kernel. */
338 r
= cg_all_unified();
340 return log_debug_errno(r
, "Failed to determine cgroup hierarchy version: %m");
342 /* Unsupported on v1.
344 * We don't return ENOENT, since that could actually mask a genuine problem where somebody else has
345 * silently masked the controller. */
349 /* The root slice doesn't have any controller files, so we can't compare anything. */
350 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
353 /* It's possible to have MemoryFoo set without systemd wanting to have the memory controller enabled,
354 * for example, in the case of DisableControllers= or cgroup_disable on the kernel command line. To
355 * avoid specious errors in these scenarios, check that we even expect the memory controller to be
357 m
= unit_get_target_mask(u
);
358 if (!FLAGS_SET(m
, CGROUP_MASK_MEMORY
))
361 assert_se(c
= unit_get_cgroup_context(u
));
363 bool startup
= u
->manager
&& IN_SET(manager_state(u
->manager
), MANAGER_STARTING
, MANAGER_INITIALIZING
, MANAGER_STOPPING
);
365 if (streq(property_name
, "MemoryLow")) {
366 unit_value
= unit_get_ancestor_memory_low(u
);
368 } else if (startup
&& streq(property_name
, "StartupMemoryLow")) {
369 unit_value
= unit_get_ancestor_startup_memory_low(u
);
371 } else if (streq(property_name
, "MemoryMin")) {
372 unit_value
= unit_get_ancestor_memory_min(u
);
374 } else if (streq(property_name
, "MemoryHigh")) {
375 unit_value
= c
->memory_high
;
376 file
= "memory.high";
377 } else if (startup
&& streq(property_name
, "StartupMemoryHigh")) {
378 unit_value
= c
->startup_memory_high
;
379 file
= "memory.high";
380 } else if (streq(property_name
, "MemoryMax")) {
381 unit_value
= c
->memory_max
;
383 } else if (startup
&& streq(property_name
, "StartupMemoryMax")) {
384 unit_value
= c
->startup_memory_max
;
386 } else if (streq(property_name
, "MemorySwapMax")) {
387 unit_value
= c
->memory_swap_max
;
388 file
= "memory.swap.max";
389 } else if (startup
&& streq(property_name
, "StartupMemorySwapMax")) {
390 unit_value
= c
->startup_memory_swap_max
;
391 file
= "memory.swap.max";
392 } else if (streq(property_name
, "MemoryZSwapMax")) {
393 unit_value
= c
->memory_zswap_max
;
394 file
= "memory.zswap.max";
395 } else if (startup
&& streq(property_name
, "StartupMemoryZSwapMax")) {
396 unit_value
= c
->startup_memory_zswap_max
;
397 file
= "memory.zswap.max";
401 r
= unit_get_kernel_memory_limit(u
, file
, ret_kernel_value
);
403 return log_unit_debug_errno(u
, r
, "Failed to parse %s: %m", file
);
405 /* It's intended (soon) in a future kernel to not expose cgroup memory limits rounded to page
406 * boundaries, but instead separate the user-exposed limit, which is whatever userspace told us, from
407 * our internal page-counting. To support those future kernels, just check the value itself first
408 * without any page-alignment. */
409 if (*ret_kernel_value
== unit_value
) {
410 *ret_unit_value
= unit_value
;
414 /* The current kernel behaviour, by comparison, is that even if you write a particular number of
415 * bytes into a cgroup memory file, it always returns that number page-aligned down (since the kernel
416 * internally stores cgroup limits in pages). As such, so long as it aligns properly, everything is
418 if (unit_value
!= CGROUP_LIMIT_MAX
)
419 unit_value
= PAGE_ALIGN_DOWN(unit_value
);
421 *ret_unit_value
= unit_value
;
423 return *ret_kernel_value
== *ret_unit_value
;
426 #define FORMAT_CGROUP_DIFF_MAX 128
428 static char *format_cgroup_memory_limit_comparison(char *buf
, size_t l
, Unit
*u
, const char *property_name
) {
436 r
= unit_compare_memory_limit(u
, property_name
, &sval
, &kval
);
438 /* memory.swap.max is special in that it relies on CONFIG_MEMCG_SWAP (and the default swapaccount=1).
439 * In the absence of reliably being able to detect whether memcg swap support is available or not,
440 * only complain if the error is not ENOENT. This is similarly the case for memory.zswap.max relying
441 * on CONFIG_ZSWAP. */
442 if (r
> 0 || IN_SET(r
, -ENODATA
, -EOWNERDEAD
) ||
443 (r
== -ENOENT
&& STR_IN_SET(property_name
,
445 "StartupMemorySwapMax",
447 "StartupMemoryZSwapMax")))
451 (void) snprintf(buf
, l
, " (error getting kernel value: %m)");
453 (void) snprintf(buf
, l
, " (different value in kernel: %" PRIu64
")", kval
);
458 const char *cgroup_device_permissions_to_string(CGroupDevicePermissions p
) {
459 static const char *table
[_CGROUP_DEVICE_PERMISSIONS_MAX
] = {
460 /* Lets simply define a table with every possible combination. As long as those are just 8 we
461 * can get away with it. If this ever grows to more we need to revisit this logic though. */
463 [CGROUP_DEVICE_READ
] = "r",
464 [CGROUP_DEVICE_WRITE
] = "w",
465 [CGROUP_DEVICE_MKNOD
] = "m",
466 [CGROUP_DEVICE_READ
|CGROUP_DEVICE_WRITE
] = "rw",
467 [CGROUP_DEVICE_READ
|CGROUP_DEVICE_MKNOD
] = "rm",
468 [CGROUP_DEVICE_WRITE
|CGROUP_DEVICE_MKNOD
] = "wm",
469 [CGROUP_DEVICE_READ
|CGROUP_DEVICE_WRITE
|CGROUP_DEVICE_MKNOD
] = "rwm",
472 if (p
< 0 || p
>= _CGROUP_DEVICE_PERMISSIONS_MAX
)
478 CGroupDevicePermissions
cgroup_device_permissions_from_string(const char *s
) {
479 CGroupDevicePermissions p
= 0;
482 return _CGROUP_DEVICE_PERMISSIONS_INVALID
;
484 for (const char *c
= s
; *c
; c
++) {
486 p
|= CGROUP_DEVICE_READ
;
488 p
|= CGROUP_DEVICE_WRITE
;
490 p
|= CGROUP_DEVICE_MKNOD
;
492 return _CGROUP_DEVICE_PERMISSIONS_INVALID
;
498 void cgroup_context_dump(Unit
*u
, FILE* f
, const char *prefix
) {
499 _cleanup_free_
char *disable_controllers_str
= NULL
, *delegate_controllers_str
= NULL
, *cpuset_cpus
= NULL
, *cpuset_mems
= NULL
, *startup_cpuset_cpus
= NULL
, *startup_cpuset_mems
= NULL
;
501 struct in_addr_prefix
*iaai
;
503 char cda
[FORMAT_CGROUP_DIFF_MAX
];
504 char cdb
[FORMAT_CGROUP_DIFF_MAX
];
505 char cdc
[FORMAT_CGROUP_DIFF_MAX
];
506 char cdd
[FORMAT_CGROUP_DIFF_MAX
];
507 char cde
[FORMAT_CGROUP_DIFF_MAX
];
508 char cdf
[FORMAT_CGROUP_DIFF_MAX
];
509 char cdg
[FORMAT_CGROUP_DIFF_MAX
];
510 char cdh
[FORMAT_CGROUP_DIFF_MAX
];
511 char cdi
[FORMAT_CGROUP_DIFF_MAX
];
512 char cdj
[FORMAT_CGROUP_DIFF_MAX
];
513 char cdk
[FORMAT_CGROUP_DIFF_MAX
];
518 assert_se(c
= unit_get_cgroup_context(u
));
520 prefix
= strempty(prefix
);
522 (void) cg_mask_to_string(c
->disable_controllers
, &disable_controllers_str
);
523 (void) cg_mask_to_string(c
->delegate_controllers
, &delegate_controllers_str
);
525 /* "Delegate=" means "yes, but no controllers". Show this as "(none)". */
526 const char *delegate_str
= delegate_controllers_str
?: c
->delegate
? "(none)" : "no";
528 cpuset_cpus
= cpu_set_to_range_string(&c
->cpuset_cpus
);
529 startup_cpuset_cpus
= cpu_set_to_range_string(&c
->startup_cpuset_cpus
);
530 cpuset_mems
= cpu_set_to_range_string(&c
->cpuset_mems
);
531 startup_cpuset_mems
= cpu_set_to_range_string(&c
->startup_cpuset_mems
);
534 "%sCPUAccounting: %s\n"
535 "%sIOAccounting: %s\n"
536 "%sBlockIOAccounting: %s\n"
537 "%sMemoryAccounting: %s\n"
538 "%sTasksAccounting: %s\n"
539 "%sIPAccounting: %s\n"
540 "%sCPUWeight: %" PRIu64
"\n"
541 "%sStartupCPUWeight: %" PRIu64
"\n"
542 "%sCPUShares: %" PRIu64
"\n"
543 "%sStartupCPUShares: %" PRIu64
"\n"
544 "%sCPUQuotaPerSecSec: %s\n"
545 "%sCPUQuotaPeriodSec: %s\n"
546 "%sAllowedCPUs: %s\n"
547 "%sStartupAllowedCPUs: %s\n"
548 "%sAllowedMemoryNodes: %s\n"
549 "%sStartupAllowedMemoryNodes: %s\n"
550 "%sIOWeight: %" PRIu64
"\n"
551 "%sStartupIOWeight: %" PRIu64
"\n"
552 "%sBlockIOWeight: %" PRIu64
"\n"
553 "%sStartupBlockIOWeight: %" PRIu64
"\n"
554 "%sDefaultMemoryMin: %" PRIu64
"\n"
555 "%sDefaultMemoryLow: %" PRIu64
"\n"
556 "%sMemoryMin: %" PRIu64
"%s\n"
557 "%sMemoryLow: %" PRIu64
"%s\n"
558 "%sStartupMemoryLow: %" PRIu64
"%s\n"
559 "%sMemoryHigh: %" PRIu64
"%s\n"
560 "%sStartupMemoryHigh: %" PRIu64
"%s\n"
561 "%sMemoryMax: %" PRIu64
"%s\n"
562 "%sStartupMemoryMax: %" PRIu64
"%s\n"
563 "%sMemorySwapMax: %" PRIu64
"%s\n"
564 "%sStartupMemorySwapMax: %" PRIu64
"%s\n"
565 "%sMemoryZSwapMax: %" PRIu64
"%s\n"
566 "%sStartupMemoryZSwapMax: %" PRIu64
"%s\n"
567 "%sMemoryLimit: %" PRIu64
"\n"
568 "%sTasksMax: %" PRIu64
"\n"
569 "%sDevicePolicy: %s\n"
570 "%sDisableControllers: %s\n"
572 "%sManagedOOMSwap: %s\n"
573 "%sManagedOOMMemoryPressure: %s\n"
574 "%sManagedOOMMemoryPressureLimit: " PERMYRIAD_AS_PERCENT_FORMAT_STR
"\n"
575 "%sManagedOOMPreference: %s\n"
576 "%sMemoryPressureWatch: %s\n"
577 "%sCoredumpReceive: %s\n",
578 prefix
, yes_no(c
->cpu_accounting
),
579 prefix
, yes_no(c
->io_accounting
),
580 prefix
, yes_no(c
->blockio_accounting
),
581 prefix
, yes_no(c
->memory_accounting
),
582 prefix
, yes_no(c
->tasks_accounting
),
583 prefix
, yes_no(c
->ip_accounting
),
584 prefix
, c
->cpu_weight
,
585 prefix
, c
->startup_cpu_weight
,
586 prefix
, c
->cpu_shares
,
587 prefix
, c
->startup_cpu_shares
,
588 prefix
, FORMAT_TIMESPAN(c
->cpu_quota_per_sec_usec
, 1),
589 prefix
, FORMAT_TIMESPAN(c
->cpu_quota_period_usec
, 1),
590 prefix
, strempty(cpuset_cpus
),
591 prefix
, strempty(startup_cpuset_cpus
),
592 prefix
, strempty(cpuset_mems
),
593 prefix
, strempty(startup_cpuset_mems
),
594 prefix
, c
->io_weight
,
595 prefix
, c
->startup_io_weight
,
596 prefix
, c
->blockio_weight
,
597 prefix
, c
->startup_blockio_weight
,
598 prefix
, c
->default_memory_min
,
599 prefix
, c
->default_memory_low
,
600 prefix
, c
->memory_min
, format_cgroup_memory_limit_comparison(cda
, sizeof(cda
), u
, "MemoryMin"),
601 prefix
, c
->memory_low
, format_cgroup_memory_limit_comparison(cdb
, sizeof(cdb
), u
, "MemoryLow"),
602 prefix
, c
->startup_memory_low
, format_cgroup_memory_limit_comparison(cdc
, sizeof(cdc
), u
, "StartupMemoryLow"),
603 prefix
, c
->memory_high
, format_cgroup_memory_limit_comparison(cdd
, sizeof(cdd
), u
, "MemoryHigh"),
604 prefix
, c
->startup_memory_high
, format_cgroup_memory_limit_comparison(cde
, sizeof(cde
), u
, "StartupMemoryHigh"),
605 prefix
, c
->memory_max
, format_cgroup_memory_limit_comparison(cdf
, sizeof(cdf
), u
, "MemoryMax"),
606 prefix
, c
->startup_memory_max
, format_cgroup_memory_limit_comparison(cdg
, sizeof(cdg
), u
, "StartupMemoryMax"),
607 prefix
, c
->memory_swap_max
, format_cgroup_memory_limit_comparison(cdh
, sizeof(cdh
), u
, "MemorySwapMax"),
608 prefix
, c
->startup_memory_swap_max
, format_cgroup_memory_limit_comparison(cdi
, sizeof(cdi
), u
, "StartupMemorySwapMax"),
609 prefix
, c
->memory_zswap_max
, format_cgroup_memory_limit_comparison(cdj
, sizeof(cdj
), u
, "MemoryZSwapMax"),
610 prefix
, c
->startup_memory_zswap_max
, format_cgroup_memory_limit_comparison(cdk
, sizeof(cdk
), u
, "StartupMemoryZSwapMax"),
611 prefix
, c
->memory_limit
,
612 prefix
, cgroup_tasks_max_resolve(&c
->tasks_max
),
613 prefix
, cgroup_device_policy_to_string(c
->device_policy
),
614 prefix
, strempty(disable_controllers_str
),
615 prefix
, delegate_str
,
616 prefix
, managed_oom_mode_to_string(c
->moom_swap
),
617 prefix
, managed_oom_mode_to_string(c
->moom_mem_pressure
),
618 prefix
, PERMYRIAD_AS_PERCENT_FORMAT_VAL(UINT32_SCALE_TO_PERMYRIAD(c
->moom_mem_pressure_limit
)),
619 prefix
, managed_oom_preference_to_string(c
->moom_preference
),
620 prefix
, cgroup_pressure_watch_to_string(c
->memory_pressure_watch
),
621 prefix
, yes_no(c
->coredump_receive
));
623 if (c
->delegate_subgroup
)
624 fprintf(f
, "%sDelegateSubgroup: %s\n",
625 prefix
, c
->delegate_subgroup
);
627 if (c
->memory_pressure_threshold_usec
!= USEC_INFINITY
)
628 fprintf(f
, "%sMemoryPressureThresholdSec: %s\n",
629 prefix
, FORMAT_TIMESPAN(c
->memory_pressure_threshold_usec
, 1));
631 LIST_FOREACH(device_allow
, a
, c
->device_allow
)
632 /* strna() below should be redundant, for avoiding -Werror=format-overflow= error. See #30223. */
634 "%sDeviceAllow: %s %s\n",
637 strna(cgroup_device_permissions_to_string(a
->permissions
)));
639 LIST_FOREACH(device_weights
, iw
, c
->io_device_weights
)
641 "%sIODeviceWeight: %s %" PRIu64
"\n",
646 LIST_FOREACH(device_latencies
, l
, c
->io_device_latencies
)
648 "%sIODeviceLatencyTargetSec: %s %s\n",
651 FORMAT_TIMESPAN(l
->target_usec
, 1));
653 LIST_FOREACH(device_limits
, il
, c
->io_device_limits
)
654 for (CGroupIOLimitType type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
655 if (il
->limits
[type
] != cgroup_io_limit_defaults
[type
])
659 cgroup_io_limit_type_to_string(type
),
661 FORMAT_BYTES(il
->limits
[type
]));
663 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
665 "%sBlockIODeviceWeight: %s %" PRIu64
,
670 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
671 if (b
->rbps
!= CGROUP_LIMIT_MAX
)
673 "%sBlockIOReadBandwidth: %s %s\n",
676 FORMAT_BYTES(b
->rbps
));
677 if (b
->wbps
!= CGROUP_LIMIT_MAX
)
679 "%sBlockIOWriteBandwidth: %s %s\n",
682 FORMAT_BYTES(b
->wbps
));
685 SET_FOREACH(iaai
, c
->ip_address_allow
)
686 fprintf(f
, "%sIPAddressAllow: %s\n", prefix
,
687 IN_ADDR_PREFIX_TO_STRING(iaai
->family
, &iaai
->address
, iaai
->prefixlen
));
688 SET_FOREACH(iaai
, c
->ip_address_deny
)
689 fprintf(f
, "%sIPAddressDeny: %s\n", prefix
,
690 IN_ADDR_PREFIX_TO_STRING(iaai
->family
, &iaai
->address
, iaai
->prefixlen
));
692 STRV_FOREACH(path
, c
->ip_filters_ingress
)
693 fprintf(f
, "%sIPIngressFilterPath: %s\n", prefix
, *path
);
694 STRV_FOREACH(path
, c
->ip_filters_egress
)
695 fprintf(f
, "%sIPEgressFilterPath: %s\n", prefix
, *path
);
697 LIST_FOREACH(programs
, p
, c
->bpf_foreign_programs
)
698 fprintf(f
, "%sBPFProgram: %s:%s",
699 prefix
, bpf_cgroup_attach_type_to_string(p
->attach_type
), p
->bpffs_path
);
701 if (c
->socket_bind_allow
) {
702 fprintf(f
, "%sSocketBindAllow: ", prefix
);
703 cgroup_context_dump_socket_bind_items(c
->socket_bind_allow
, f
);
707 if (c
->socket_bind_deny
) {
708 fprintf(f
, "%sSocketBindDeny: ", prefix
);
709 cgroup_context_dump_socket_bind_items(c
->socket_bind_deny
, f
);
713 if (c
->restrict_network_interfaces
) {
715 SET_FOREACH(iface
, c
->restrict_network_interfaces
)
716 fprintf(f
, "%sRestrictNetworkInterfaces: %s\n", prefix
, iface
);
719 FOREACH_ARRAY(nft_set
, c
->nft_set_context
.sets
, c
->nft_set_context
.n_sets
)
720 fprintf(f
, "%sNFTSet: %s:%s:%s:%s\n", prefix
, nft_set_source_to_string(nft_set
->source
),
721 nfproto_to_string(nft_set
->nfproto
), nft_set
->table
, nft_set
->set
);
724 void cgroup_context_dump_socket_bind_item(const CGroupSocketBindItem
*item
, FILE *f
) {
725 const char *family
, *colon1
, *protocol
= "", *colon2
= "";
727 family
= strempty(af_to_ipv4_ipv6(item
->address_family
));
728 colon1
= isempty(family
) ? "" : ":";
730 if (item
->ip_protocol
!= 0) {
731 protocol
= ip_protocol_to_tcp_udp(item
->ip_protocol
);
735 if (item
->nr_ports
== 0)
736 fprintf(f
, "%s%s%s%sany", family
, colon1
, protocol
, colon2
);
737 else if (item
->nr_ports
== 1)
738 fprintf(f
, "%s%s%s%s%" PRIu16
, family
, colon1
, protocol
, colon2
, item
->port_min
);
740 uint16_t port_max
= item
->port_min
+ item
->nr_ports
- 1;
741 fprintf(f
, "%s%s%s%s%" PRIu16
"-%" PRIu16
, family
, colon1
, protocol
, colon2
,
742 item
->port_min
, port_max
);
746 void cgroup_context_dump_socket_bind_items(const CGroupSocketBindItem
*items
, FILE *f
) {
749 LIST_FOREACH(socket_bind_items
, bi
, items
) {
755 cgroup_context_dump_socket_bind_item(bi
, f
);
759 int cgroup_context_add_device_allow(CGroupContext
*c
, const char *dev
, CGroupDevicePermissions p
) {
760 _cleanup_free_ CGroupDeviceAllow
*a
= NULL
;
761 _cleanup_free_
char *d
= NULL
;
765 assert(p
>= 0 && p
< _CGROUP_DEVICE_PERMISSIONS_MAX
);
768 p
= _CGROUP_DEVICE_PERMISSIONS_ALL
;
770 a
= new(CGroupDeviceAllow
, 1);
778 *a
= (CGroupDeviceAllow
) {
783 LIST_PREPEND(device_allow
, c
->device_allow
, a
);
789 int cgroup_context_add_or_update_device_allow(CGroupContext
*c
, const char *dev
, CGroupDevicePermissions p
) {
792 assert(p
>= 0 && p
< _CGROUP_DEVICE_PERMISSIONS_MAX
);
795 p
= _CGROUP_DEVICE_PERMISSIONS_ALL
;
797 LIST_FOREACH(device_allow
, b
, c
->device_allow
)
798 if (path_equal(b
->path
, dev
)) {
803 return cgroup_context_add_device_allow(c
, dev
, p
);
806 int cgroup_context_add_bpf_foreign_program(CGroupContext
*c
, uint32_t attach_type
, const char *bpffs_path
) {
807 CGroupBPFForeignProgram
*p
;
808 _cleanup_free_
char *d
= NULL
;
813 if (!path_is_normalized(bpffs_path
) || !path_is_absolute(bpffs_path
))
814 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Path is not normalized: %m");
816 d
= strdup(bpffs_path
);
820 p
= new(CGroupBPFForeignProgram
, 1);
824 *p
= (CGroupBPFForeignProgram
) {
825 .attach_type
= attach_type
,
826 .bpffs_path
= TAKE_PTR(d
),
829 LIST_PREPEND(programs
, c
->bpf_foreign_programs
, TAKE_PTR(p
));
834 #define UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(entry) \
835 uint64_t unit_get_ancestor_##entry(Unit *u) { \
838 /* 1. Is entry set in this unit? If so, use that. \
839 * 2. Is the default for this entry set in any \
840 * ancestor? If so, use that. \
841 * 3. Otherwise, return CGROUP_LIMIT_MIN. */ \
845 c = unit_get_cgroup_context(u); \
846 if (c && c->entry##_set) \
849 while ((u = UNIT_GET_SLICE(u))) { \
850 c = unit_get_cgroup_context(u); \
851 if (c && c->default_##entry##_set) \
852 return c->default_##entry; \
855 /* We've reached the root, but nobody had default for \
856 * this entry set, so set it to the kernel default. */ \
857 return CGROUP_LIMIT_MIN; \
860 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_low
);
861 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(startup_memory_low
);
862 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_min
);
864 static void unit_set_xattr_graceful(Unit
*u
, const char *name
, const void *data
, size_t size
) {
873 r
= cg_set_xattr(u
->cgroup_path
, name
, data
, size
, 0);
875 log_unit_debug_errno(u
, r
, "Failed to set '%s' xattr on control group %s, ignoring: %m", name
, empty_to_root(u
->cgroup_path
));
878 static void unit_remove_xattr_graceful(Unit
*u
, const char *name
) {
887 r
= cg_remove_xattr(u
->cgroup_path
, name
);
888 if (r
< 0 && !ERRNO_IS_XATTR_ABSENT(r
))
889 log_unit_debug_errno(u
, r
, "Failed to remove '%s' xattr flag on control group %s, ignoring: %m", name
, empty_to_root(u
->cgroup_path
));
892 static void cgroup_oomd_xattr_apply(Unit
*u
) {
897 c
= unit_get_cgroup_context(u
);
901 if (c
->moom_preference
== MANAGED_OOM_PREFERENCE_OMIT
)
902 unit_set_xattr_graceful(u
, "user.oomd_omit", "1", 1);
904 if (c
->moom_preference
== MANAGED_OOM_PREFERENCE_AVOID
)
905 unit_set_xattr_graceful(u
, "user.oomd_avoid", "1", 1);
907 if (c
->moom_preference
!= MANAGED_OOM_PREFERENCE_AVOID
)
908 unit_remove_xattr_graceful(u
, "user.oomd_avoid");
910 if (c
->moom_preference
!= MANAGED_OOM_PREFERENCE_OMIT
)
911 unit_remove_xattr_graceful(u
, "user.oomd_omit");
914 static int cgroup_log_xattr_apply(Unit
*u
) {
916 size_t len
, allowed_patterns_len
, denied_patterns_len
;
917 _cleanup_free_
char *patterns
= NULL
, *allowed_patterns
= NULL
, *denied_patterns
= NULL
;
923 c
= unit_get_exec_context(u
);
925 /* Some unit types have a cgroup context but no exec context, so we do not log
926 * any error here to avoid confusion. */
929 if (set_isempty(c
->log_filter_allowed_patterns
) && set_isempty(c
->log_filter_denied_patterns
)) {
930 unit_remove_xattr_graceful(u
, "user.journald_log_filter_patterns");
934 r
= set_make_nulstr(c
->log_filter_allowed_patterns
, &allowed_patterns
, &allowed_patterns_len
);
936 return log_debug_errno(r
, "Failed to make nulstr from set: %m");
938 r
= set_make_nulstr(c
->log_filter_denied_patterns
, &denied_patterns
, &denied_patterns_len
);
940 return log_debug_errno(r
, "Failed to make nulstr from set: %m");
942 /* Use nul character separated strings without trailing nul */
943 allowed_patterns_len
= LESS_BY(allowed_patterns_len
, 1u);
944 denied_patterns_len
= LESS_BY(denied_patterns_len
, 1u);
946 len
= allowed_patterns_len
+ 1 + denied_patterns_len
;
947 patterns
= new(char, len
);
949 return log_oom_debug();
951 last
= mempcpy_safe(patterns
, allowed_patterns
, allowed_patterns_len
);
953 memcpy_safe(last
, denied_patterns
, denied_patterns_len
);
955 unit_set_xattr_graceful(u
, "user.journald_log_filter_patterns", patterns
, len
);
960 static void cgroup_invocation_id_xattr_apply(Unit
*u
) {
965 b
= !sd_id128_is_null(u
->invocation_id
);
966 FOREACH_STRING(xn
, "trusted.invocation_id", "user.invocation_id") {
968 unit_set_xattr_graceful(u
, xn
, SD_ID128_TO_STRING(u
->invocation_id
), 32);
970 unit_remove_xattr_graceful(u
, xn
);
974 static void cgroup_coredump_xattr_apply(Unit
*u
) {
979 c
= unit_get_cgroup_context(u
);
983 if (unit_cgroup_delegate(u
) && c
->coredump_receive
)
984 unit_set_xattr_graceful(u
, "user.coredump_receive", "1", 1);
986 unit_remove_xattr_graceful(u
, "user.coredump_receive");
989 static void cgroup_delegate_xattr_apply(Unit
*u
) {
994 /* Indicate on the cgroup whether delegation is on, via an xattr. This is best-effort, as old kernels
995 * didn't support xattrs on cgroups at all. Later they got support for setting 'trusted.*' xattrs,
996 * and even later 'user.*' xattrs. We started setting this field when 'trusted.*' was added, and
997 * given this is now pretty much API, let's continue to support that. But also set 'user.*' as well,
998 * since it is readable by any user, not just CAP_SYS_ADMIN. This hence comes with slightly weaker
999 * security (as users who got delegated cgroups could turn it off if they like), but this shouldn't
1000 * be a big problem given this communicates delegation state to clients, but the manager never reads
1002 b
= unit_cgroup_delegate(u
);
1003 FOREACH_STRING(xn
, "trusted.delegate", "user.delegate") {
1005 unit_set_xattr_graceful(u
, xn
, "1", 1);
1007 unit_remove_xattr_graceful(u
, xn
);
1011 static void cgroup_survive_xattr_apply(Unit
*u
) {
1016 if (u
->survive_final_kill_signal
) {
1019 "user.survive_final_kill_signal",
1023 /* user xattr support was added in kernel v5.7 */
1024 if (ERRNO_IS_NEG_NOT_SUPPORTED(r
))
1027 "trusted.survive_final_kill_signal",
1032 log_unit_debug_errno(u
,
1034 "Failed to set 'survive_final_kill_signal' xattr on control "
1035 "group %s, ignoring: %m",
1036 empty_to_root(u
->cgroup_path
));
1038 unit_remove_xattr_graceful(u
, "user.survive_final_kill_signal");
1039 unit_remove_xattr_graceful(u
, "trusted.survive_final_kill_signal");
1043 static void cgroup_xattr_apply(Unit
*u
) {
1046 /* The 'user.*' xattrs can be set from a user manager. */
1047 cgroup_oomd_xattr_apply(u
);
1048 cgroup_log_xattr_apply(u
);
1049 cgroup_coredump_xattr_apply(u
);
1051 if (!MANAGER_IS_SYSTEM(u
->manager
))
1054 cgroup_invocation_id_xattr_apply(u
);
1055 cgroup_delegate_xattr_apply(u
);
1056 cgroup_survive_xattr_apply(u
);
1059 static int lookup_block_device(const char *p
, dev_t
*ret
) {
1060 dev_t rdev
, dev
= 0;
1067 r
= device_path_parse_major_minor(p
, &mode
, &rdev
);
1068 if (r
== -ENODEV
) { /* not a parsable device node, need to go to disk */
1071 if (stat(p
, &st
) < 0)
1072 return log_warning_errno(errno
, "Couldn't stat device '%s': %m", p
);
1078 return log_warning_errno(r
, "Failed to parse major/minor from path '%s': %m", p
);
1081 return log_warning_errno(SYNTHETIC_ERRNO(ENOTBLK
),
1082 "Device node '%s' is a character device, but block device needed.", p
);
1085 else if (major(dev
) != 0)
1086 *ret
= dev
; /* If this is not a device node then use the block device this file is stored on */
1088 /* If this is btrfs, getting the backing block device is a bit harder */
1089 r
= btrfs_get_block_device(p
, ret
);
1091 return log_warning_errno(SYNTHETIC_ERRNO(ENODEV
),
1092 "'%s' is not a block device node, and file system block device cannot be determined or is not local.", p
);
1094 return log_warning_errno(r
, "Failed to determine block device backing btrfs file system '%s': %m", p
);
1097 /* If this is a LUKS/DM device, recursively try to get the originating block device */
1098 while (block_get_originating(*ret
, ret
) > 0);
1100 /* If this is a partition, try to get the originating block device */
1101 (void) block_get_whole_disk(*ret
, ret
);
1105 static bool cgroup_context_has_cpu_weight(CGroupContext
*c
) {
1106 return c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
||
1107 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
;
1110 static bool cgroup_context_has_cpu_shares(CGroupContext
*c
) {
1111 return c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
1112 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
;
1115 static bool cgroup_context_has_allowed_cpus(CGroupContext
*c
) {
1116 return c
->cpuset_cpus
.set
|| c
->startup_cpuset_cpus
.set
;
1119 static bool cgroup_context_has_allowed_mems(CGroupContext
*c
) {
1120 return c
->cpuset_mems
.set
|| c
->startup_cpuset_mems
.set
;
1123 uint64_t cgroup_context_cpu_weight(CGroupContext
*c
, ManagerState state
) {
1126 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
, MANAGER_STOPPING
) &&
1127 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
)
1128 return c
->startup_cpu_weight
;
1129 else if (c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
)
1130 return c
->cpu_weight
;
1132 return CGROUP_WEIGHT_DEFAULT
;
1135 static uint64_t cgroup_context_cpu_shares(CGroupContext
*c
, ManagerState state
) {
1136 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
, MANAGER_STOPPING
) &&
1137 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
1138 return c
->startup_cpu_shares
;
1139 else if (c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
1140 return c
->cpu_shares
;
1142 return CGROUP_CPU_SHARES_DEFAULT
;
1145 static CPUSet
*cgroup_context_allowed_cpus(CGroupContext
*c
, ManagerState state
) {
1146 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
, MANAGER_STOPPING
) &&
1147 c
->startup_cpuset_cpus
.set
)
1148 return &c
->startup_cpuset_cpus
;
1150 return &c
->cpuset_cpus
;
1153 static CPUSet
*cgroup_context_allowed_mems(CGroupContext
*c
, ManagerState state
) {
1154 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
, MANAGER_STOPPING
) &&
1155 c
->startup_cpuset_mems
.set
)
1156 return &c
->startup_cpuset_mems
;
1158 return &c
->cpuset_mems
;
1161 usec_t
cgroup_cpu_adjust_period(usec_t period
, usec_t quota
, usec_t resolution
, usec_t max_period
) {
1162 /* kernel uses a minimum resolution of 1ms, so both period and (quota * period)
1163 * need to be higher than that boundary. quota is specified in USecPerSec.
1164 * Additionally, period must be at most max_period. */
1167 return MIN(MAX3(period
, resolution
, resolution
* USEC_PER_SEC
/ quota
), max_period
);
1170 static usec_t
cgroup_cpu_adjust_period_and_log(Unit
*u
, usec_t period
, usec_t quota
) {
1173 if (quota
== USEC_INFINITY
)
1174 /* Always use default period for infinity quota. */
1175 return CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC
;
1177 if (period
== USEC_INFINITY
)
1178 /* Default period was requested. */
1179 period
= CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC
;
1181 /* Clamp to interval [1ms, 1s] */
1182 new_period
= cgroup_cpu_adjust_period(period
, quota
, USEC_PER_MSEC
, USEC_PER_SEC
);
1184 if (new_period
!= period
) {
1185 log_unit_full(u
, u
->warned_clamping_cpu_quota_period
? LOG_DEBUG
: LOG_WARNING
,
1186 "Clamping CPU interval for cpu.max: period is now %s",
1187 FORMAT_TIMESPAN(new_period
, 1));
1188 u
->warned_clamping_cpu_quota_period
= true;
1194 static void cgroup_apply_unified_cpu_weight(Unit
*u
, uint64_t weight
) {
1195 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
1197 if (weight
== CGROUP_WEIGHT_IDLE
)
1199 xsprintf(buf
, "%" PRIu64
"\n", weight
);
1200 (void) set_attribute_and_warn(u
, "cpu", "cpu.weight", buf
);
1203 static void cgroup_apply_unified_cpu_idle(Unit
*u
, uint64_t weight
) {
1206 const char *idle_val
;
1208 is_idle
= weight
== CGROUP_WEIGHT_IDLE
;
1209 idle_val
= one_zero(is_idle
);
1210 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.idle", idle_val
);
1211 if (r
< 0 && (r
!= -ENOENT
|| is_idle
))
1212 log_unit_full_errno(u
, LOG_LEVEL_CGROUP_WRITE(r
), r
, "Failed to set '%s' attribute on '%s' to '%s': %m",
1213 "cpu.idle", empty_to_root(u
->cgroup_path
), idle_val
);
1216 static void cgroup_apply_unified_cpu_quota(Unit
*u
, usec_t quota
, usec_t period
) {
1217 char buf
[(DECIMAL_STR_MAX(usec_t
) + 1) * 2 + 1];
1219 period
= cgroup_cpu_adjust_period_and_log(u
, period
, quota
);
1220 if (quota
!= USEC_INFINITY
)
1221 xsprintf(buf
, USEC_FMT
" " USEC_FMT
"\n",
1222 MAX(quota
* period
/ USEC_PER_SEC
, USEC_PER_MSEC
), period
);
1224 xsprintf(buf
, "max " USEC_FMT
"\n", period
);
1225 (void) set_attribute_and_warn(u
, "cpu", "cpu.max", buf
);
1228 static void cgroup_apply_legacy_cpu_shares(Unit
*u
, uint64_t shares
) {
1229 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
1231 xsprintf(buf
, "%" PRIu64
"\n", shares
);
1232 (void) set_attribute_and_warn(u
, "cpu", "cpu.shares", buf
);
1235 static void cgroup_apply_legacy_cpu_quota(Unit
*u
, usec_t quota
, usec_t period
) {
1236 char buf
[DECIMAL_STR_MAX(usec_t
) + 2];
1238 period
= cgroup_cpu_adjust_period_and_log(u
, period
, quota
);
1240 xsprintf(buf
, USEC_FMT
"\n", period
);
1241 (void) set_attribute_and_warn(u
, "cpu", "cpu.cfs_period_us", buf
);
1243 if (quota
!= USEC_INFINITY
) {
1244 xsprintf(buf
, USEC_FMT
"\n", MAX(quota
* period
/ USEC_PER_SEC
, USEC_PER_MSEC
));
1245 (void) set_attribute_and_warn(u
, "cpu", "cpu.cfs_quota_us", buf
);
1247 (void) set_attribute_and_warn(u
, "cpu", "cpu.cfs_quota_us", "-1\n");
1250 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares
) {
1251 return CLAMP(shares
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_CPU_SHARES_DEFAULT
,
1252 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
1255 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight
) {
1256 /* we don't support idle in cgroupv1 */
1257 if (weight
== CGROUP_WEIGHT_IDLE
)
1258 return CGROUP_CPU_SHARES_MIN
;
1260 return CLAMP(weight
* CGROUP_CPU_SHARES_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
1261 CGROUP_CPU_SHARES_MIN
, CGROUP_CPU_SHARES_MAX
);
1264 static void cgroup_apply_unified_cpuset(Unit
*u
, const CPUSet
*cpus
, const char *name
) {
1265 _cleanup_free_
char *buf
= NULL
;
1267 buf
= cpu_set_to_range_string(cpus
);
1273 (void) set_attribute_and_warn(u
, "cpuset", name
, buf
);
1276 static bool cgroup_context_has_io_config(CGroupContext
*c
) {
1277 return c
->io_accounting
||
1278 c
->io_weight
!= CGROUP_WEIGHT_INVALID
||
1279 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
1280 c
->io_device_weights
||
1281 c
->io_device_latencies
||
1282 c
->io_device_limits
;
1285 static bool cgroup_context_has_blockio_config(CGroupContext
*c
) {
1286 return c
->blockio_accounting
||
1287 c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
1288 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
1289 c
->blockio_device_weights
||
1290 c
->blockio_device_bandwidths
;
1293 static uint64_t cgroup_context_io_weight(CGroupContext
*c
, ManagerState state
) {
1294 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
, MANAGER_STOPPING
) &&
1295 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
)
1296 return c
->startup_io_weight
;
1297 if (c
->io_weight
!= CGROUP_WEIGHT_INVALID
)
1298 return c
->io_weight
;
1299 return CGROUP_WEIGHT_DEFAULT
;
1302 static uint64_t cgroup_context_blkio_weight(CGroupContext
*c
, ManagerState state
) {
1303 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
, MANAGER_STOPPING
) &&
1304 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
1305 return c
->startup_blockio_weight
;
1306 if (c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
1307 return c
->blockio_weight
;
1308 return CGROUP_BLKIO_WEIGHT_DEFAULT
;
1311 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight
) {
1312 return CLAMP(blkio_weight
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_BLKIO_WEIGHT_DEFAULT
,
1313 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
1316 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight
) {
1317 return CLAMP(io_weight
* CGROUP_BLKIO_WEIGHT_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
1318 CGROUP_BLKIO_WEIGHT_MIN
, CGROUP_BLKIO_WEIGHT_MAX
);
1321 static int set_bfq_weight(Unit
*u
, const char *controller
, dev_t dev
, uint64_t io_weight
) {
1322 static const char * const prop_names
[] = {
1326 "BlockIODeviceWeight",
1328 static bool warned
= false;
1329 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+STRLEN("\n")];
1331 uint64_t bfq_weight
;
1334 /* FIXME: drop this function when distro kernels properly support BFQ through "io.weight"
1335 * See also: https://github.com/systemd/systemd/pull/13335 and
1336 * https://github.com/torvalds/linux/commit/65752aef0a407e1ef17ec78a7fc31ba4e0b360f9. */
1337 p
= strjoina(controller
, ".bfq.weight");
1338 /* Adjust to kernel range is 1..1000, the default is 100. */
1339 bfq_weight
= BFQ_WEIGHT(io_weight
);
1342 xsprintf(buf
, DEVNUM_FORMAT_STR
" %" PRIu64
"\n", DEVNUM_FORMAT_VAL(dev
), bfq_weight
);
1344 xsprintf(buf
, "%" PRIu64
"\n", bfq_weight
);
1346 r
= cg_set_attribute(controller
, u
->cgroup_path
, p
, buf
);
1348 /* FIXME: drop this when kernels prior
1349 * 795fe54c2a82 ("bfq: Add per-device weight") v5.4
1350 * are not interesting anymore. Old kernels will fail with EINVAL, while new kernels won't return
1351 * EINVAL on properly formatted input by us. Treat EINVAL accordingly. */
1352 if (r
== -EINVAL
&& major(dev
) > 0) {
1354 log_unit_warning(u
, "Kernel version does not accept per-device setting in %s.", p
);
1357 r
= -EOPNOTSUPP
; /* mask as unconfigured device */
1358 } else if (r
>= 0 && io_weight
!= bfq_weight
)
1359 log_unit_debug(u
, "%s=%" PRIu64
" scaled to %s=%" PRIu64
,
1360 prop_names
[2*(major(dev
) > 0) + streq(controller
, "blkio")],
1361 io_weight
, p
, bfq_weight
);
1365 static void cgroup_apply_io_device_weight(Unit
*u
, const char *dev_path
, uint64_t io_weight
) {
1366 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1370 if (lookup_block_device(dev_path
, &dev
) < 0)
1373 r1
= set_bfq_weight(u
, "io", dev
, io_weight
);
1375 xsprintf(buf
, DEVNUM_FORMAT_STR
" %" PRIu64
"\n", DEVNUM_FORMAT_VAL(dev
), io_weight
);
1376 r2
= cg_set_attribute("io", u
->cgroup_path
, "io.weight", buf
);
1378 /* Look at the configured device, when both fail, prefer io.weight errno. */
1379 r
= r2
== -EOPNOTSUPP
? r1
: r2
;
1382 log_unit_full_errno(u
, LOG_LEVEL_CGROUP_WRITE(r
),
1383 r
, "Failed to set 'io[.bfq].weight' attribute on '%s' to '%.*s': %m",
1384 empty_to_root(u
->cgroup_path
), (int) strcspn(buf
, NEWLINE
), buf
);
1387 static void cgroup_apply_blkio_device_weight(Unit
*u
, const char *dev_path
, uint64_t blkio_weight
) {
1388 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1392 r
= lookup_block_device(dev_path
, &dev
);
1396 xsprintf(buf
, DEVNUM_FORMAT_STR
" %" PRIu64
"\n", DEVNUM_FORMAT_VAL(dev
), blkio_weight
);
1397 (void) set_attribute_and_warn(u
, "blkio", "blkio.weight_device", buf
);
1400 static void cgroup_apply_io_device_latency(Unit
*u
, const char *dev_path
, usec_t target
) {
1401 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+7+DECIMAL_STR_MAX(uint64_t)+1];
1405 r
= lookup_block_device(dev_path
, &dev
);
1409 if (target
!= USEC_INFINITY
)
1410 xsprintf(buf
, DEVNUM_FORMAT_STR
" target=%" PRIu64
"\n", DEVNUM_FORMAT_VAL(dev
), target
);
1412 xsprintf(buf
, DEVNUM_FORMAT_STR
" target=max\n", DEVNUM_FORMAT_VAL(dev
));
1414 (void) set_attribute_and_warn(u
, "io", "io.latency", buf
);
1417 static void cgroup_apply_io_device_limit(Unit
*u
, const char *dev_path
, uint64_t *limits
) {
1418 char limit_bufs
[_CGROUP_IO_LIMIT_TYPE_MAX
][DECIMAL_STR_MAX(uint64_t)],
1419 buf
[DECIMAL_STR_MAX(dev_t
)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
1422 if (lookup_block_device(dev_path
, &dev
) < 0)
1425 for (CGroupIOLimitType type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
1426 if (limits
[type
] != cgroup_io_limit_defaults
[type
])
1427 xsprintf(limit_bufs
[type
], "%" PRIu64
, limits
[type
]);
1429 xsprintf(limit_bufs
[type
], "%s", limits
[type
] == CGROUP_LIMIT_MAX
? "max" : "0");
1431 xsprintf(buf
, DEVNUM_FORMAT_STR
" rbps=%s wbps=%s riops=%s wiops=%s\n", DEVNUM_FORMAT_VAL(dev
),
1432 limit_bufs
[CGROUP_IO_RBPS_MAX
], limit_bufs
[CGROUP_IO_WBPS_MAX
],
1433 limit_bufs
[CGROUP_IO_RIOPS_MAX
], limit_bufs
[CGROUP_IO_WIOPS_MAX
]);
1434 (void) set_attribute_and_warn(u
, "io", "io.max", buf
);
1437 static void cgroup_apply_blkio_device_limit(Unit
*u
, const char *dev_path
, uint64_t rbps
, uint64_t wbps
) {
1438 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1441 if (lookup_block_device(dev_path
, &dev
) < 0)
1444 sprintf(buf
, DEVNUM_FORMAT_STR
" %" PRIu64
"\n", DEVNUM_FORMAT_VAL(dev
), rbps
);
1445 (void) set_attribute_and_warn(u
, "blkio", "blkio.throttle.read_bps_device", buf
);
1447 sprintf(buf
, DEVNUM_FORMAT_STR
" %" PRIu64
"\n", DEVNUM_FORMAT_VAL(dev
), wbps
);
1448 (void) set_attribute_and_warn(u
, "blkio", "blkio.throttle.write_bps_device", buf
);
1451 static bool unit_has_unified_memory_config(Unit
*u
) {
1456 assert_se(c
= unit_get_cgroup_context(u
));
1458 return unit_get_ancestor_memory_min(u
) > 0 ||
1459 unit_get_ancestor_memory_low(u
) > 0 || unit_get_ancestor_startup_memory_low(u
) > 0 ||
1460 c
->memory_high
!= CGROUP_LIMIT_MAX
|| c
->startup_memory_high_set
||
1461 c
->memory_max
!= CGROUP_LIMIT_MAX
|| c
->startup_memory_max_set
||
1462 c
->memory_swap_max
!= CGROUP_LIMIT_MAX
|| c
->startup_memory_swap_max_set
||
1463 c
->memory_zswap_max
!= CGROUP_LIMIT_MAX
|| c
->startup_memory_zswap_max_set
;
1466 static void cgroup_apply_unified_memory_limit(Unit
*u
, const char *file
, uint64_t v
) {
1467 char buf
[DECIMAL_STR_MAX(uint64_t) + 1] = "max\n";
1469 if (v
!= CGROUP_LIMIT_MAX
)
1470 xsprintf(buf
, "%" PRIu64
"\n", v
);
1472 (void) set_attribute_and_warn(u
, "memory", file
, buf
);
1475 static void cgroup_apply_firewall(Unit
*u
) {
1478 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
1480 if (bpf_firewall_compile(u
) < 0)
1483 (void) bpf_firewall_load_custom(u
);
1484 (void) bpf_firewall_install(u
);
1487 void unit_modify_nft_set(Unit
*u
, bool add
) {
1492 if (!MANAGER_IS_SYSTEM(u
->manager
))
1495 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1498 if (cg_all_unified() <= 0)
1501 if (u
->cgroup_id
== 0)
1504 if (!u
->manager
->fw_ctx
) {
1505 r
= fw_ctx_new_full(&u
->manager
->fw_ctx
, /* init_tables= */ false);
1509 assert(u
->manager
->fw_ctx
);
1512 CGroupContext
*c
= ASSERT_PTR(unit_get_cgroup_context(u
));
1514 FOREACH_ARRAY(nft_set
, c
->nft_set_context
.sets
, c
->nft_set_context
.n_sets
) {
1515 if (nft_set
->source
!= NFT_SET_SOURCE_CGROUP
)
1518 uint64_t element
= u
->cgroup_id
;
1520 r
= nft_set_element_modify_any(u
->manager
->fw_ctx
, add
, nft_set
->nfproto
, nft_set
->table
, nft_set
->set
, &element
, sizeof(element
));
1522 log_warning_errno(r
, "Failed to %s NFT set: family %s, table %s, set %s, cgroup %" PRIu64
", ignoring: %m",
1523 add
? "add" : "delete", nfproto_to_string(nft_set
->nfproto
), nft_set
->table
, nft_set
->set
, u
->cgroup_id
);
1525 log_debug("%s NFT set: family %s, table %s, set %s, cgroup %" PRIu64
,
1526 add
? "Added" : "Deleted", nfproto_to_string(nft_set
->nfproto
), nft_set
->table
, nft_set
->set
, u
->cgroup_id
);
1530 static void cgroup_apply_socket_bind(Unit
*u
) {
1533 (void) bpf_socket_bind_install(u
);
1536 static void cgroup_apply_restrict_network_interfaces(Unit
*u
) {
1539 (void) restrict_network_interfaces_install(u
);
1542 static int cgroup_apply_devices(Unit
*u
) {
1543 _cleanup_(bpf_program_freep
) BPFProgram
*prog
= NULL
;
1546 CGroupDevicePolicy policy
;
1549 assert_se(c
= unit_get_cgroup_context(u
));
1550 assert_se(path
= u
->cgroup_path
);
1552 policy
= c
->device_policy
;
1554 if (cg_all_unified() > 0) {
1555 r
= bpf_devices_cgroup_init(&prog
, policy
, c
->device_allow
);
1557 return log_unit_warning_errno(u
, r
, "Failed to initialize device control bpf program: %m");
1560 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore
1563 if (c
->device_allow
|| policy
!= CGROUP_DEVICE_POLICY_AUTO
)
1564 r
= cg_set_attribute("devices", path
, "devices.deny", "a");
1566 r
= cg_set_attribute("devices", path
, "devices.allow", "a");
1568 log_unit_full_errno(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
, -EPERM
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1569 "Failed to reset devices.allow/devices.deny: %m");
1572 bool allow_list_static
= policy
== CGROUP_DEVICE_POLICY_CLOSED
||
1573 (policy
== CGROUP_DEVICE_POLICY_AUTO
&& c
->device_allow
);
1574 if (allow_list_static
)
1575 (void) bpf_devices_allow_list_static(prog
, path
);
1577 bool any
= allow_list_static
;
1578 LIST_FOREACH(device_allow
, a
, c
->device_allow
) {
1581 if (a
->permissions
== 0)
1584 if (path_startswith(a
->path
, "/dev/"))
1585 r
= bpf_devices_allow_list_device(prog
, path
, a
->path
, a
->permissions
);
1586 else if ((val
= startswith(a
->path
, "block-")))
1587 r
= bpf_devices_allow_list_major(prog
, path
, val
, 'b', a
->permissions
);
1588 else if ((val
= startswith(a
->path
, "char-")))
1589 r
= bpf_devices_allow_list_major(prog
, path
, val
, 'c', a
->permissions
);
1591 log_unit_debug(u
, "Ignoring device '%s' while writing cgroup attribute.", a
->path
);
1600 log_unit_warning_errno(u
, SYNTHETIC_ERRNO(ENODEV
), "No devices matched by device filter.");
1602 /* The kernel verifier would reject a program we would build with the normal intro and outro
1603 but no allow-listing rules (outro would contain an unreachable instruction for successful
1605 policy
= CGROUP_DEVICE_POLICY_STRICT
;
1608 r
= bpf_devices_apply_policy(&prog
, policy
, any
, path
, &u
->bpf_device_control_installed
);
1610 static bool warned
= false;
1612 log_full_errno(warned
? LOG_DEBUG
: LOG_WARNING
, r
,
1613 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1614 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1615 "(This warning is only shown for the first loaded unit using device ACL.)", u
->id
);
1622 static void set_io_weight(Unit
*u
, uint64_t weight
) {
1623 char buf
[STRLEN("default \n")+DECIMAL_STR_MAX(uint64_t)];
1627 (void) set_bfq_weight(u
, "io", makedev(0, 0), weight
);
1629 xsprintf(buf
, "default %" PRIu64
"\n", weight
);
1630 (void) set_attribute_and_warn(u
, "io", "io.weight", buf
);
1633 static void set_blkio_weight(Unit
*u
, uint64_t weight
) {
1634 char buf
[STRLEN("\n")+DECIMAL_STR_MAX(uint64_t)];
1638 (void) set_bfq_weight(u
, "blkio", makedev(0, 0), weight
);
1640 xsprintf(buf
, "%" PRIu64
"\n", weight
);
1641 (void) set_attribute_and_warn(u
, "blkio", "blkio.weight", buf
);
1644 static void cgroup_apply_bpf_foreign_program(Unit
*u
) {
1647 (void) bpf_foreign_install(u
);
1650 static void cgroup_context_apply(
1652 CGroupMask apply_mask
,
1653 ManagerState state
) {
1657 bool is_host_root
, is_local_root
;
1662 /* Nothing to do? Exit early! */
1663 if (apply_mask
== 0)
1666 /* Some cgroup attributes are not supported on the host root cgroup, hence silently ignore them here. And other
1667 * attributes should only be managed for cgroups further down the tree. */
1668 is_local_root
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
1669 is_host_root
= unit_has_host_root_cgroup(u
);
1671 assert_se(c
= unit_get_cgroup_context(u
));
1672 assert_se(path
= u
->cgroup_path
);
1674 if (is_local_root
) /* Make sure we don't try to display messages with an empty path. */
1677 /* We generally ignore errors caused by read-only mounted cgroup trees (assuming we are running in a container
1678 * then), and missing cgroups, i.e. EROFS and ENOENT. */
1680 /* In fully unified mode these attributes don't exist on the host cgroup root. On legacy the weights exist, but
1681 * setting the weight makes very little sense on the host root cgroup, as there are no other cgroups at this
1682 * level. The quota exists there too, but any attempt to write to it is refused with EINVAL. Inside of
1683 * containers we want to leave control of these to the container manager (and if cgroup v2 delegation is used
1684 * we couldn't even write to them if we wanted to). */
1685 if ((apply_mask
& CGROUP_MASK_CPU
) && !is_local_root
) {
1687 if (cg_all_unified() > 0) {
1690 if (cgroup_context_has_cpu_weight(c
))
1691 weight
= cgroup_context_cpu_weight(c
, state
);
1692 else if (cgroup_context_has_cpu_shares(c
)) {
1695 shares
= cgroup_context_cpu_shares(c
, state
);
1696 weight
= cgroup_cpu_shares_to_weight(shares
);
1698 log_cgroup_compat(u
, "Applying [Startup]CPUShares=%" PRIu64
" as [Startup]CPUWeight=%" PRIu64
" on %s",
1699 shares
, weight
, path
);
1701 weight
= CGROUP_WEIGHT_DEFAULT
;
1703 cgroup_apply_unified_cpu_idle(u
, weight
);
1704 cgroup_apply_unified_cpu_weight(u
, weight
);
1705 cgroup_apply_unified_cpu_quota(u
, c
->cpu_quota_per_sec_usec
, c
->cpu_quota_period_usec
);
1710 if (cgroup_context_has_cpu_weight(c
)) {
1713 weight
= cgroup_context_cpu_weight(c
, state
);
1714 shares
= cgroup_cpu_weight_to_shares(weight
);
1716 log_cgroup_compat(u
, "Applying [Startup]CPUWeight=%" PRIu64
" as [Startup]CPUShares=%" PRIu64
" on %s",
1717 weight
, shares
, path
);
1718 } else if (cgroup_context_has_cpu_shares(c
))
1719 shares
= cgroup_context_cpu_shares(c
, state
);
1721 shares
= CGROUP_CPU_SHARES_DEFAULT
;
1723 cgroup_apply_legacy_cpu_shares(u
, shares
);
1724 cgroup_apply_legacy_cpu_quota(u
, c
->cpu_quota_per_sec_usec
, c
->cpu_quota_period_usec
);
1728 if ((apply_mask
& CGROUP_MASK_CPUSET
) && !is_local_root
) {
1729 cgroup_apply_unified_cpuset(u
, cgroup_context_allowed_cpus(c
, state
), "cpuset.cpus");
1730 cgroup_apply_unified_cpuset(u
, cgroup_context_allowed_mems(c
, state
), "cpuset.mems");
1733 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroup v2
1734 * controller), and in case of containers we want to leave control of these attributes to the container manager
1735 * (and we couldn't access that stuff anyway, even if we tried if proper delegation is used). */
1736 if ((apply_mask
& CGROUP_MASK_IO
) && !is_local_root
) {
1737 bool has_io
, has_blockio
;
1740 has_io
= cgroup_context_has_io_config(c
);
1741 has_blockio
= cgroup_context_has_blockio_config(c
);
1744 weight
= cgroup_context_io_weight(c
, state
);
1745 else if (has_blockio
) {
1746 uint64_t blkio_weight
;
1748 blkio_weight
= cgroup_context_blkio_weight(c
, state
);
1749 weight
= cgroup_weight_blkio_to_io(blkio_weight
);
1751 log_cgroup_compat(u
, "Applying [Startup]BlockIOWeight=%" PRIu64
" as [Startup]IOWeight=%" PRIu64
,
1752 blkio_weight
, weight
);
1754 weight
= CGROUP_WEIGHT_DEFAULT
;
1756 set_io_weight(u
, weight
);
1759 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
)
1760 cgroup_apply_io_device_weight(u
, w
->path
, w
->weight
);
1762 LIST_FOREACH(device_limits
, limit
, c
->io_device_limits
)
1763 cgroup_apply_io_device_limit(u
, limit
->path
, limit
->limits
);
1765 LIST_FOREACH(device_latencies
, latency
, c
->io_device_latencies
)
1766 cgroup_apply_io_device_latency(u
, latency
->path
, latency
->target_usec
);
1768 } else if (has_blockio
) {
1769 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
) {
1770 weight
= cgroup_weight_blkio_to_io(w
->weight
);
1772 log_cgroup_compat(u
, "Applying BlockIODeviceWeight=%" PRIu64
" as IODeviceWeight=%" PRIu64
" for %s",
1773 w
->weight
, weight
, w
->path
);
1775 cgroup_apply_io_device_weight(u
, w
->path
, weight
);
1778 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
1779 uint64_t limits
[_CGROUP_IO_LIMIT_TYPE_MAX
];
1781 for (CGroupIOLimitType type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
1782 limits
[type
] = cgroup_io_limit_defaults
[type
];
1784 limits
[CGROUP_IO_RBPS_MAX
] = b
->rbps
;
1785 limits
[CGROUP_IO_WBPS_MAX
] = b
->wbps
;
1787 log_cgroup_compat(u
, "Applying BlockIO{Read|Write}Bandwidth=%" PRIu64
" %" PRIu64
" as IO{Read|Write}BandwidthMax= for %s",
1788 b
->rbps
, b
->wbps
, b
->path
);
1790 cgroup_apply_io_device_limit(u
, b
->path
, limits
);
1795 if (apply_mask
& CGROUP_MASK_BLKIO
) {
1796 bool has_io
, has_blockio
;
1798 has_io
= cgroup_context_has_io_config(c
);
1799 has_blockio
= cgroup_context_has_blockio_config(c
);
1801 /* Applying a 'weight' never makes sense for the host root cgroup, and for containers this should be
1802 * left to our container manager, too. */
1803 if (!is_local_root
) {
1809 io_weight
= cgroup_context_io_weight(c
, state
);
1810 weight
= cgroup_weight_io_to_blkio(cgroup_context_io_weight(c
, state
));
1812 log_cgroup_compat(u
, "Applying [Startup]IOWeight=%" PRIu64
" as [Startup]BlockIOWeight=%" PRIu64
,
1814 } else if (has_blockio
)
1815 weight
= cgroup_context_blkio_weight(c
, state
);
1817 weight
= CGROUP_BLKIO_WEIGHT_DEFAULT
;
1819 set_blkio_weight(u
, weight
);
1822 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
) {
1823 weight
= cgroup_weight_io_to_blkio(w
->weight
);
1825 log_cgroup_compat(u
, "Applying IODeviceWeight=%" PRIu64
" as BlockIODeviceWeight=%" PRIu64
" for %s",
1826 w
->weight
, weight
, w
->path
);
1828 cgroup_apply_blkio_device_weight(u
, w
->path
, weight
);
1830 else if (has_blockio
)
1831 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
1832 cgroup_apply_blkio_device_weight(u
, w
->path
, w
->weight
);
1835 /* The bandwidth limits are something that make sense to be applied to the host's root but not container
1836 * roots, as there we want the container manager to handle it */
1837 if (is_host_root
|| !is_local_root
) {
1839 LIST_FOREACH(device_limits
, l
, c
->io_device_limits
) {
1840 log_cgroup_compat(u
, "Applying IO{Read|Write}Bandwidth=%" PRIu64
" %" PRIu64
" as BlockIO{Read|Write}BandwidthMax= for %s",
1841 l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
], l
->path
);
1843 cgroup_apply_blkio_device_limit(u
, l
->path
, l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
]);
1845 else if (has_blockio
)
1846 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
)
1847 cgroup_apply_blkio_device_limit(u
, b
->path
, b
->rbps
, b
->wbps
);
1851 /* In unified mode 'memory' attributes do not exist on the root cgroup. In legacy mode 'memory.limit_in_bytes'
1852 * exists on the root cgroup, but any writes to it are refused with EINVAL. And if we run in a container we
1853 * want to leave control to the container manager (and if proper cgroup v2 delegation is used we couldn't even
1854 * write to this if we wanted to.) */
1855 if ((apply_mask
& CGROUP_MASK_MEMORY
) && !is_local_root
) {
1857 if (cg_all_unified() > 0) {
1858 uint64_t max
, swap_max
= CGROUP_LIMIT_MAX
, zswap_max
= CGROUP_LIMIT_MAX
, high
= CGROUP_LIMIT_MAX
;
1860 if (unit_has_unified_memory_config(u
)) {
1861 bool startup
= IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
, MANAGER_STOPPING
);
1863 high
= startup
&& c
->startup_memory_high_set
? c
->startup_memory_high
: c
->memory_high
;
1864 max
= startup
&& c
->startup_memory_max_set
? c
->startup_memory_max
: c
->memory_max
;
1865 swap_max
= startup
&& c
->startup_memory_swap_max_set
? c
->startup_memory_swap_max
: c
->memory_swap_max
;
1866 zswap_max
= startup
&& c
->startup_memory_zswap_max_set
? c
->startup_memory_zswap_max
: c
->memory_zswap_max
;
1868 max
= c
->memory_limit
;
1870 if (max
!= CGROUP_LIMIT_MAX
)
1871 log_cgroup_compat(u
, "Applying MemoryLimit=%" PRIu64
" as MemoryMax=", max
);
1874 cgroup_apply_unified_memory_limit(u
, "memory.min", unit_get_ancestor_memory_min(u
));
1875 cgroup_apply_unified_memory_limit(u
, "memory.low", unit_get_ancestor_memory_low(u
));
1876 cgroup_apply_unified_memory_limit(u
, "memory.high", high
);
1877 cgroup_apply_unified_memory_limit(u
, "memory.max", max
);
1878 cgroup_apply_unified_memory_limit(u
, "memory.swap.max", swap_max
);
1879 cgroup_apply_unified_memory_limit(u
, "memory.zswap.max", zswap_max
);
1881 (void) set_attribute_and_warn(u
, "memory", "memory.oom.group", one_zero(c
->memory_oom_group
));
1884 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
1887 if (unit_has_unified_memory_config(u
)) {
1888 val
= c
->memory_max
;
1889 if (val
!= CGROUP_LIMIT_MAX
)
1890 log_cgroup_compat(u
, "Applying MemoryMax=%" PRIu64
" as MemoryLimit=", val
);
1892 val
= c
->memory_limit
;
1894 if (val
== CGROUP_LIMIT_MAX
)
1895 strncpy(buf
, "-1\n", sizeof(buf
));
1897 xsprintf(buf
, "%" PRIu64
"\n", val
);
1899 (void) set_attribute_and_warn(u
, "memory", "memory.limit_in_bytes", buf
);
1903 /* On cgroup v2 we can apply BPF everywhere. On cgroup v1 we apply it everywhere except for the root of
1904 * containers, where we leave this to the manager */
1905 if ((apply_mask
& (CGROUP_MASK_DEVICES
| CGROUP_MASK_BPF_DEVICES
)) &&
1906 (is_host_root
|| cg_all_unified() > 0 || !is_local_root
))
1907 (void) cgroup_apply_devices(u
);
1909 if (apply_mask
& CGROUP_MASK_PIDS
) {
1912 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1913 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1914 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1915 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1916 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1917 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1918 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1919 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1920 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1921 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1922 * which is desirable so that there's an official way to release control of the sysctl from
1923 * systemd: set the limit to unbounded and reload. */
1925 if (cgroup_tasks_max_isset(&c
->tasks_max
)) {
1926 u
->manager
->sysctl_pid_max_changed
= true;
1927 r
= procfs_tasks_set_limit(cgroup_tasks_max_resolve(&c
->tasks_max
));
1928 } else if (u
->manager
->sysctl_pid_max_changed
)
1929 r
= procfs_tasks_set_limit(TASKS_MAX
);
1933 log_unit_full_errno(u
, LOG_LEVEL_CGROUP_WRITE(r
), r
,
1934 "Failed to write to tasks limit sysctls: %m");
1937 /* The attribute itself is not available on the host root cgroup, and in the container case we want to
1938 * leave it for the container manager. */
1939 if (!is_local_root
) {
1940 if (cgroup_tasks_max_isset(&c
->tasks_max
)) {
1941 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
1943 xsprintf(buf
, "%" PRIu64
"\n", cgroup_tasks_max_resolve(&c
->tasks_max
));
1944 (void) set_attribute_and_warn(u
, "pids", "pids.max", buf
);
1946 (void) set_attribute_and_warn(u
, "pids", "pids.max", "max\n");
1950 if (apply_mask
& CGROUP_MASK_BPF_FIREWALL
)
1951 cgroup_apply_firewall(u
);
1953 if (apply_mask
& CGROUP_MASK_BPF_FOREIGN
)
1954 cgroup_apply_bpf_foreign_program(u
);
1956 if (apply_mask
& CGROUP_MASK_BPF_SOCKET_BIND
)
1957 cgroup_apply_socket_bind(u
);
1959 if (apply_mask
& CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES
)
1960 cgroup_apply_restrict_network_interfaces(u
);
1962 unit_modify_nft_set(u
, /* add = */ true);
1965 static bool unit_get_needs_bpf_firewall(Unit
*u
) {
1969 c
= unit_get_cgroup_context(u
);
1973 if (c
->ip_accounting
||
1974 !set_isempty(c
->ip_address_allow
) ||
1975 !set_isempty(c
->ip_address_deny
) ||
1976 c
->ip_filters_ingress
||
1977 c
->ip_filters_egress
)
1980 /* If any parent slice has an IP access list defined, it applies too */
1981 for (Unit
*p
= UNIT_GET_SLICE(u
); p
; p
= UNIT_GET_SLICE(p
)) {
1982 c
= unit_get_cgroup_context(p
);
1986 if (!set_isempty(c
->ip_address_allow
) ||
1987 !set_isempty(c
->ip_address_deny
))
1994 static bool unit_get_needs_bpf_foreign_program(Unit
*u
) {
1998 c
= unit_get_cgroup_context(u
);
2002 return !!c
->bpf_foreign_programs
;
2005 static bool unit_get_needs_socket_bind(Unit
*u
) {
2009 c
= unit_get_cgroup_context(u
);
2013 return c
->socket_bind_allow
|| c
->socket_bind_deny
;
2016 static bool unit_get_needs_restrict_network_interfaces(Unit
*u
) {
2020 c
= unit_get_cgroup_context(u
);
2024 return !set_isempty(c
->restrict_network_interfaces
);
2027 static CGroupMask
unit_get_cgroup_mask(Unit
*u
) {
2028 CGroupMask mask
= 0;
2033 assert_se(c
= unit_get_cgroup_context(u
));
2035 /* Figure out which controllers we need, based on the cgroup context object */
2037 if (c
->cpu_accounting
)
2038 mask
|= get_cpu_accounting_mask();
2040 if (cgroup_context_has_cpu_weight(c
) ||
2041 cgroup_context_has_cpu_shares(c
) ||
2042 c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
)
2043 mask
|= CGROUP_MASK_CPU
;
2045 if (cgroup_context_has_allowed_cpus(c
) || cgroup_context_has_allowed_mems(c
))
2046 mask
|= CGROUP_MASK_CPUSET
;
2048 if (cgroup_context_has_io_config(c
) || cgroup_context_has_blockio_config(c
))
2049 mask
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
2051 if (c
->memory_accounting
||
2052 c
->memory_limit
!= CGROUP_LIMIT_MAX
||
2053 unit_has_unified_memory_config(u
))
2054 mask
|= CGROUP_MASK_MEMORY
;
2056 if (c
->device_allow
||
2057 c
->device_policy
!= CGROUP_DEVICE_POLICY_AUTO
)
2058 mask
|= CGROUP_MASK_DEVICES
| CGROUP_MASK_BPF_DEVICES
;
2060 if (c
->tasks_accounting
||
2061 cgroup_tasks_max_isset(&c
->tasks_max
))
2062 mask
|= CGROUP_MASK_PIDS
;
2064 return CGROUP_MASK_EXTEND_JOINED(mask
);
2067 static CGroupMask
unit_get_bpf_mask(Unit
*u
) {
2068 CGroupMask mask
= 0;
2070 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
2073 if (unit_get_needs_bpf_firewall(u
))
2074 mask
|= CGROUP_MASK_BPF_FIREWALL
;
2076 if (unit_get_needs_bpf_foreign_program(u
))
2077 mask
|= CGROUP_MASK_BPF_FOREIGN
;
2079 if (unit_get_needs_socket_bind(u
))
2080 mask
|= CGROUP_MASK_BPF_SOCKET_BIND
;
2082 if (unit_get_needs_restrict_network_interfaces(u
))
2083 mask
|= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES
;
2088 CGroupMask
unit_get_own_mask(Unit
*u
) {
2091 /* Returns the mask of controllers the unit needs for itself. If a unit is not properly loaded, return an empty
2092 * mask, as we shouldn't reflect it in the cgroup hierarchy then. */
2094 if (u
->load_state
!= UNIT_LOADED
)
2097 c
= unit_get_cgroup_context(u
);
2101 return unit_get_cgroup_mask(u
) | unit_get_bpf_mask(u
) | unit_get_delegate_mask(u
);
2104 CGroupMask
unit_get_delegate_mask(Unit
*u
) {
2107 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
2108 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
2110 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
2112 if (!unit_cgroup_delegate(u
))
2115 if (cg_all_unified() <= 0) {
2118 e
= unit_get_exec_context(u
);
2119 if (e
&& !exec_context_maintains_privileges(e
))
2123 assert_se(c
= unit_get_cgroup_context(u
));
2124 return CGROUP_MASK_EXTEND_JOINED(c
->delegate_controllers
);
2127 static CGroupMask
unit_get_subtree_mask(Unit
*u
) {
2129 /* Returns the mask of this subtree, meaning of the group
2130 * itself and its children. */
2132 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
2135 CGroupMask
unit_get_members_mask(Unit
*u
) {
2138 /* Returns the mask of controllers all of the unit's children require, merged */
2140 if (u
->cgroup_members_mask_valid
)
2141 return u
->cgroup_members_mask
; /* Use cached value if possible */
2143 u
->cgroup_members_mask
= 0;
2145 if (u
->type
== UNIT_SLICE
) {
2148 UNIT_FOREACH_DEPENDENCY(member
, u
, UNIT_ATOM_SLICE_OF
)
2149 u
->cgroup_members_mask
|= unit_get_subtree_mask(member
); /* note that this calls ourselves again, for the children */
2152 u
->cgroup_members_mask_valid
= true;
2153 return u
->cgroup_members_mask
;
2156 CGroupMask
unit_get_siblings_mask(Unit
*u
) {
2160 /* Returns the mask of controllers all of the unit's siblings
2161 * require, i.e. the members mask of the unit's parent slice
2162 * if there is one. */
2164 slice
= UNIT_GET_SLICE(u
);
2166 return unit_get_members_mask(slice
);
2168 return unit_get_subtree_mask(u
); /* we are the top-level slice */
2171 static CGroupMask
unit_get_disable_mask(Unit
*u
) {
2174 c
= unit_get_cgroup_context(u
);
2178 return c
->disable_controllers
;
2181 CGroupMask
unit_get_ancestor_disable_mask(Unit
*u
) {
2186 mask
= unit_get_disable_mask(u
);
2188 /* Returns the mask of controllers which are marked as forcibly
2189 * disabled in any ancestor unit or the unit in question. */
2191 slice
= UNIT_GET_SLICE(u
);
2193 mask
|= unit_get_ancestor_disable_mask(slice
);
2198 CGroupMask
unit_get_target_mask(Unit
*u
) {
2199 CGroupMask own_mask
, mask
;
2201 /* This returns the cgroup mask of all controllers to enable for a specific cgroup, i.e. everything
2202 * it needs itself, plus all that its children need, plus all that its siblings need. This is
2203 * primarily useful on the legacy cgroup hierarchy, where we need to duplicate each cgroup in each
2204 * hierarchy that shall be enabled for it. */
2206 own_mask
= unit_get_own_mask(u
);
2208 if (own_mask
& CGROUP_MASK_BPF_FIREWALL
& ~u
->manager
->cgroup_supported
)
2209 emit_bpf_firewall_warning(u
);
2211 mask
= own_mask
| unit_get_members_mask(u
) | unit_get_siblings_mask(u
);
2213 mask
&= u
->manager
->cgroup_supported
;
2214 mask
&= ~unit_get_ancestor_disable_mask(u
);
2219 CGroupMask
unit_get_enable_mask(Unit
*u
) {
2222 /* This returns the cgroup mask of all controllers to enable
2223 * for the children of a specific cgroup. This is primarily
2224 * useful for the unified cgroup hierarchy, where each cgroup
2225 * controls which controllers are enabled for its children. */
2227 mask
= unit_get_members_mask(u
);
2228 mask
&= u
->manager
->cgroup_supported
;
2229 mask
&= ~unit_get_ancestor_disable_mask(u
);
2234 void unit_invalidate_cgroup_members_masks(Unit
*u
) {
2239 /* Recurse invalidate the member masks cache all the way up the tree */
2240 u
->cgroup_members_mask_valid
= false;
2242 slice
= UNIT_GET_SLICE(u
);
2244 unit_invalidate_cgroup_members_masks(slice
);
2247 const char *unit_get_realized_cgroup_path(Unit
*u
, CGroupMask mask
) {
2249 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
2253 if (u
->cgroup_path
&&
2254 u
->cgroup_realized
&&
2255 FLAGS_SET(u
->cgroup_realized_mask
, mask
))
2256 return u
->cgroup_path
;
2258 u
= UNIT_GET_SLICE(u
);
2264 static const char *migrate_callback(CGroupMask mask
, void *userdata
) {
2265 /* If not realized at all, migrate to root ("").
2266 * It may happen if we're upgrading from older version that didn't clean up.
2268 return strempty(unit_get_realized_cgroup_path(userdata
, mask
));
2271 int unit_default_cgroup_path(const Unit
*u
, char **ret
) {
2272 _cleanup_free_
char *p
= NULL
;
2278 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
2279 p
= strdup(u
->manager
->cgroup_root
);
2281 _cleanup_free_
char *escaped
= NULL
, *slice_path
= NULL
;
2284 slice
= UNIT_GET_SLICE(u
);
2285 if (slice
&& !unit_has_name(slice
, SPECIAL_ROOT_SLICE
)) {
2286 r
= cg_slice_to_path(slice
->id
, &slice_path
);
2291 r
= cg_escape(u
->id
, &escaped
);
2295 p
= path_join(empty_to_root(u
->manager
->cgroup_root
), slice_path
, escaped
);
2304 int unit_set_cgroup_path(Unit
*u
, const char *path
) {
2305 _cleanup_free_
char *p
= NULL
;
2310 if (streq_ptr(u
->cgroup_path
, path
))
2320 r
= hashmap_put(u
->manager
->cgroup_unit
, p
, u
);
2325 unit_release_cgroup(u
);
2326 u
->cgroup_path
= TAKE_PTR(p
);
2331 int unit_watch_cgroup(Unit
*u
) {
2332 _cleanup_free_
char *events
= NULL
;
2337 /* Watches the "cgroups.events" attribute of this unit's cgroup for "empty" events, but only if
2338 * cgroupv2 is available. */
2340 if (!u
->cgroup_path
)
2343 if (u
->cgroup_control_inotify_wd
>= 0)
2346 /* Only applies to the unified hierarchy */
2347 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2349 return log_error_errno(r
, "Failed to determine whether the name=systemd hierarchy is unified: %m");
2353 /* No point in watch the top-level slice, it's never going to run empty. */
2354 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
2357 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_control_inotify_wd_unit
, &trivial_hash_ops
);
2361 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events", &events
);
2365 u
->cgroup_control_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
2366 if (u
->cgroup_control_inotify_wd
< 0) {
2368 if (errno
== ENOENT
) /* If the directory is already gone we don't need to track it, so this
2369 * is not an error */
2372 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
));
2375 r
= hashmap_put(u
->manager
->cgroup_control_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_control_inotify_wd
), u
);
2377 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
));
2382 int unit_watch_cgroup_memory(Unit
*u
) {
2383 _cleanup_free_
char *events
= NULL
;
2389 /* Watches the "memory.events" attribute of this unit's cgroup for "oom_kill" events, but only if
2390 * cgroupv2 is available. */
2392 if (!u
->cgroup_path
)
2395 c
= unit_get_cgroup_context(u
);
2399 /* The "memory.events" attribute is only available if the memory controller is on. Let's hence tie
2400 * this to memory accounting, in a way watching for OOM kills is a form of memory accounting after
2402 if (!c
->memory_accounting
)
2405 /* Don't watch inner nodes, as the kernel doesn't report oom_kill events recursively currently, and
2406 * we also don't want to generate a log message for each parent cgroup of a process. */
2407 if (u
->type
== UNIT_SLICE
)
2410 if (u
->cgroup_memory_inotify_wd
>= 0)
2413 /* Only applies to the unified hierarchy */
2414 r
= cg_all_unified();
2416 return log_error_errno(r
, "Failed to determine whether the memory controller is unified: %m");
2420 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_memory_inotify_wd_unit
, &trivial_hash_ops
);
2424 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "memory.events", &events
);
2428 u
->cgroup_memory_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
2429 if (u
->cgroup_memory_inotify_wd
< 0) {
2431 if (errno
== ENOENT
) /* If the directory is already gone we don't need to track it, so this
2432 * is not an error */
2435 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
));
2438 r
= hashmap_put(u
->manager
->cgroup_memory_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_memory_inotify_wd
), u
);
2440 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
));
2445 int unit_pick_cgroup_path(Unit
*u
) {
2446 _cleanup_free_
char *path
= NULL
;
2454 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2457 r
= unit_default_cgroup_path(u
, &path
);
2459 return log_unit_error_errno(u
, r
, "Failed to generate default cgroup path: %m");
2461 r
= unit_set_cgroup_path(u
, path
);
2463 return log_unit_error_errno(u
, r
, "Control group %s exists already.", empty_to_root(path
));
2465 return log_unit_error_errno(u
, r
, "Failed to set unit's control group path to %s: %m", empty_to_root(path
));
2470 static int unit_update_cgroup(
2472 CGroupMask target_mask
,
2473 CGroupMask enable_mask
,
2474 ManagerState state
) {
2476 bool created
, is_root_slice
;
2477 CGroupMask migrate_mask
= 0;
2478 _cleanup_free_
char *cgroup_full_path
= NULL
;
2483 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2486 /* Figure out our cgroup path */
2487 r
= unit_pick_cgroup_path(u
);
2491 /* First, create our own group */
2492 r
= cg_create_everywhere(u
->manager
->cgroup_supported
, target_mask
, u
->cgroup_path
);
2494 return log_unit_error_errno(u
, r
, "Failed to create cgroup %s: %m", empty_to_root(u
->cgroup_path
));
2497 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0) {
2498 uint64_t cgroup_id
= 0;
2500 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, NULL
, &cgroup_full_path
);
2502 r
= cg_path_get_cgroupid(cgroup_full_path
, &cgroup_id
);
2504 log_unit_full_errno(u
, ERRNO_IS_NOT_SUPPORTED(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
2505 "Failed to get cgroup ID of cgroup %s, ignoring: %m", cgroup_full_path
);
2507 log_unit_warning_errno(u
, r
, "Failed to get full cgroup path on cgroup %s, ignoring: %m", empty_to_root(u
->cgroup_path
));
2509 u
->cgroup_id
= cgroup_id
;
2512 /* Start watching it */
2513 (void) unit_watch_cgroup(u
);
2514 (void) unit_watch_cgroup_memory(u
);
2516 /* For v2 we preserve enabled controllers in delegated units, adjust others,
2517 * for v1 we figure out which controller hierarchies need migration. */
2518 if (created
|| !u
->cgroup_realized
|| !unit_cgroup_delegate(u
)) {
2519 CGroupMask result_mask
= 0;
2521 /* Enable all controllers we need */
2522 r
= cg_enable_everywhere(u
->manager
->cgroup_supported
, enable_mask
, u
->cgroup_path
, &result_mask
);
2524 log_unit_warning_errno(u
, r
, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", empty_to_root(u
->cgroup_path
));
2526 /* Remember what's actually enabled now */
2527 u
->cgroup_enabled_mask
= result_mask
;
2529 migrate_mask
= u
->cgroup_realized_mask
^ target_mask
;
2532 /* Keep track that this is now realized */
2533 u
->cgroup_realized
= true;
2534 u
->cgroup_realized_mask
= target_mask
;
2536 /* Migrate processes in controller hierarchies both downwards (enabling) and upwards (disabling).
2538 * Unnecessary controller cgroups are trimmed (after emptied by upward migration).
2539 * We perform migration also with whole slices for cases when users don't care about leave
2540 * granularity. Since delegated_mask is subset of target mask, we won't trim slice subtree containing
2543 if (cg_all_unified() == 0) {
2544 r
= cg_migrate_v1_controllers(u
->manager
->cgroup_supported
, migrate_mask
, u
->cgroup_path
, migrate_callback
, u
);
2546 log_unit_warning_errno(u
, r
, "Failed to migrate controller cgroups from %s, ignoring: %m", empty_to_root(u
->cgroup_path
));
2548 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
2549 r
= cg_trim_v1_controllers(u
->manager
->cgroup_supported
, ~target_mask
, u
->cgroup_path
, !is_root_slice
);
2551 log_unit_warning_errno(u
, r
, "Failed to delete controller cgroups %s, ignoring: %m", empty_to_root(u
->cgroup_path
));
2554 /* Set attributes */
2555 cgroup_context_apply(u
, target_mask
, state
);
2556 cgroup_xattr_apply(u
);
2558 /* For most units we expect that memory monitoring is set up before the unit is started and we won't
2559 * touch it after. For PID 1 this is different though, because we couldn't possibly do that given
2560 * that PID 1 runs before init.scope is even set up. Hence, whenever init.scope is realized, let's
2561 * try to open the memory pressure interface anew. */
2562 if (unit_has_name(u
, SPECIAL_INIT_SCOPE
))
2563 (void) manager_setup_memory_pressure_event_source(u
->manager
);
2568 static int unit_attach_pid_to_cgroup_via_bus(Unit
*u
, pid_t pid
, const char *suffix_path
) {
2569 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2575 if (MANAGER_IS_SYSTEM(u
->manager
))
2578 if (!u
->manager
->system_bus
)
2581 if (!u
->cgroup_path
)
2584 /* Determine this unit's cgroup path relative to our cgroup root */
2585 pp
= path_startswith(u
->cgroup_path
, u
->manager
->cgroup_root
);
2589 pp
= strjoina("/", pp
, suffix_path
);
2592 r
= bus_call_method(u
->manager
->system_bus
,
2594 "AttachProcessesToUnit",
2597 NULL
/* empty unit name means client's unit, i.e. us */, pp
, 1, (uint32_t) pid
);
2599 return log_unit_debug_errno(u
, r
, "Failed to attach unit process " PID_FMT
" via the bus: %s", pid
, bus_error_message(&error
, r
));
2604 int unit_attach_pids_to_cgroup(Unit
*u
, Set
*pids
, const char *suffix_path
) {
2605 _cleanup_free_
char *joined
= NULL
;
2606 CGroupMask delegated_mask
;
2613 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2616 if (set_isempty(pids
))
2619 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
2620 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
2621 r
= bpf_firewall_load_custom(u
);
2625 r
= unit_realize_cgroup(u
);
2629 if (isempty(suffix_path
))
2632 joined
= path_join(u
->cgroup_path
, suffix_path
);
2639 delegated_mask
= unit_get_delegate_mask(u
);
2642 SET_FOREACH(pid
, pids
) {
2644 /* Unfortunately we cannot add pids by pidfd to a cgroup. Hence we have to use PIDs instead,
2645 * which of course is racy. Let's shorten the race a bit though, and re-validate the PID
2646 * before we use it */
2647 r
= pidref_verify(pid
);
2649 log_unit_info_errno(u
, r
, "PID " PID_FMT
" vanished before we could move it to target cgroup '%s', skipping: %m", pid
->pid
, empty_to_root(p
));
2653 /* First, attach the PID to the main cgroup hierarchy */
2654 r
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, p
, pid
->pid
);
2656 bool again
= MANAGER_IS_USER(u
->manager
) && ERRNO_IS_PRIVILEGE(r
);
2658 log_unit_full_errno(u
, again
? LOG_DEBUG
: LOG_INFO
, r
,
2659 "Couldn't move process "PID_FMT
" to%s requested cgroup '%s': %m",
2660 pid
->pid
, again
? " directly" : "", empty_to_root(p
));
2665 /* If we are in a user instance, and we can't move the process ourselves due
2666 * to permission problems, let's ask the system instance about it instead.
2667 * Since it's more privileged it might be able to move the process across the
2668 * leaves of a subtree whose top node is not owned by us. */
2670 z
= unit_attach_pid_to_cgroup_via_bus(u
, pid
->pid
, suffix_path
);
2672 log_unit_info_errno(u
, z
, "Couldn't move process "PID_FMT
" to requested cgroup '%s' (directly or via the system bus): %m", pid
->pid
, empty_to_root(p
));
2675 ret
++; /* Count successful additions */
2676 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
2681 ret
= r
; /* Remember first error */
2684 } else if (ret
>= 0)
2685 ret
++; /* Count successful additions */
2687 r
= cg_all_unified();
2693 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
2694 * innermost realized one */
2696 for (CGroupController c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2697 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2698 const char *realized
;
2700 if (!(u
->manager
->cgroup_supported
& bit
))
2703 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
2704 if (delegated_mask
& u
->cgroup_realized_mask
& bit
) {
2705 r
= cg_attach(cgroup_controller_to_string(c
), p
, pid
->pid
);
2707 continue; /* Success! */
2709 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",
2710 pid
->pid
, empty_to_root(p
), cgroup_controller_to_string(c
));
2713 /* So this controller is either not delegate or realized, or something else weird happened. In
2714 * that case let's attach the PID at least to the closest cgroup up the tree that is
2716 realized
= unit_get_realized_cgroup_path(u
, bit
);
2718 continue; /* Not even realized in the root slice? Then let's not bother */
2720 r
= cg_attach(cgroup_controller_to_string(c
), realized
, pid
->pid
);
2722 log_unit_debug_errno(u
, r
, "Failed to attach PID " PID_FMT
" to realized cgroup %s in controller %s, ignoring: %m",
2723 pid
->pid
, realized
, cgroup_controller_to_string(c
));
2730 static bool unit_has_mask_realized(
2732 CGroupMask target_mask
,
2733 CGroupMask enable_mask
) {
2737 /* Returns true if this unit is fully realized. We check four things:
2739 * 1. Whether the cgroup was created at all
2740 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
2741 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
2742 * 4. Whether the invalidation mask is currently zero
2744 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
2745 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
2746 * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
2747 * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
2748 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
2749 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
2750 * simply don't matter. */
2752 return u
->cgroup_realized
&&
2753 ((u
->cgroup_realized_mask
^ target_mask
) & CGROUP_MASK_V1
) == 0 &&
2754 ((u
->cgroup_enabled_mask
^ enable_mask
) & CGROUP_MASK_V2
) == 0 &&
2755 u
->cgroup_invalidated_mask
== 0;
2758 static bool unit_has_mask_disables_realized(
2760 CGroupMask target_mask
,
2761 CGroupMask enable_mask
) {
2765 /* Returns true if all controllers which should be disabled are indeed disabled.
2767 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
2768 * already removed. */
2770 return !u
->cgroup_realized
||
2771 (FLAGS_SET(u
->cgroup_realized_mask
, target_mask
& CGROUP_MASK_V1
) &&
2772 FLAGS_SET(u
->cgroup_enabled_mask
, enable_mask
& CGROUP_MASK_V2
));
2775 static bool unit_has_mask_enables_realized(
2777 CGroupMask target_mask
,
2778 CGroupMask enable_mask
) {
2782 /* Returns true if all controllers which should be enabled are indeed enabled.
2784 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
2785 * we want to add is already added. */
2787 return u
->cgroup_realized
&&
2788 ((u
->cgroup_realized_mask
| target_mask
) & CGROUP_MASK_V1
) == (u
->cgroup_realized_mask
& CGROUP_MASK_V1
) &&
2789 ((u
->cgroup_enabled_mask
| enable_mask
) & CGROUP_MASK_V2
) == (u
->cgroup_enabled_mask
& CGROUP_MASK_V2
);
2792 void unit_add_to_cgroup_realize_queue(Unit
*u
) {
2795 if (u
->in_cgroup_realize_queue
)
2798 LIST_APPEND(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
2799 u
->in_cgroup_realize_queue
= true;
2802 static void unit_remove_from_cgroup_realize_queue(Unit
*u
) {
2805 if (!u
->in_cgroup_realize_queue
)
2808 LIST_REMOVE(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
2809 u
->in_cgroup_realize_queue
= false;
2812 /* Controllers can only be enabled breadth-first, from the root of the
2813 * hierarchy downwards to the unit in question. */
2814 static int unit_realize_cgroup_now_enable(Unit
*u
, ManagerState state
) {
2815 CGroupMask target_mask
, enable_mask
, new_target_mask
, new_enable_mask
;
2821 /* First go deal with this unit's parent, or we won't be able to enable
2822 * any new controllers at this layer. */
2823 slice
= UNIT_GET_SLICE(u
);
2825 r
= unit_realize_cgroup_now_enable(slice
, state
);
2830 target_mask
= unit_get_target_mask(u
);
2831 enable_mask
= unit_get_enable_mask(u
);
2833 /* We can only enable in this direction, don't try to disable anything.
2835 if (unit_has_mask_enables_realized(u
, target_mask
, enable_mask
))
2838 new_target_mask
= u
->cgroup_realized_mask
| target_mask
;
2839 new_enable_mask
= u
->cgroup_enabled_mask
| enable_mask
;
2841 return unit_update_cgroup(u
, new_target_mask
, new_enable_mask
, state
);
2844 /* Controllers can only be disabled depth-first, from the leaves of the
2845 * hierarchy upwards to the unit in question. */
2846 static int unit_realize_cgroup_now_disable(Unit
*u
, ManagerState state
) {
2851 if (u
->type
!= UNIT_SLICE
)
2854 UNIT_FOREACH_DEPENDENCY(m
, u
, UNIT_ATOM_SLICE_OF
) {
2855 CGroupMask target_mask
, enable_mask
, new_target_mask
, new_enable_mask
;
2858 /* The cgroup for this unit might not actually be fully realised yet, in which case it isn't
2859 * holding any controllers open anyway. */
2860 if (!m
->cgroup_realized
)
2863 /* We must disable those below us first in order to release the controller. */
2864 if (m
->type
== UNIT_SLICE
)
2865 (void) unit_realize_cgroup_now_disable(m
, state
);
2867 target_mask
= unit_get_target_mask(m
);
2868 enable_mask
= unit_get_enable_mask(m
);
2870 /* We can only disable in this direction, don't try to enable anything. */
2871 if (unit_has_mask_disables_realized(m
, target_mask
, enable_mask
))
2874 new_target_mask
= m
->cgroup_realized_mask
& target_mask
;
2875 new_enable_mask
= m
->cgroup_enabled_mask
& enable_mask
;
2877 r
= unit_update_cgroup(m
, new_target_mask
, new_enable_mask
, state
);
2885 /* Check if necessary controllers and attributes for a unit are in place.
2887 * - If so, do nothing.
2888 * - If not, create paths, move processes over, and set attributes.
2890 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
2891 * a depth-first way. As such the process looks like this:
2893 * Suppose we have a cgroup hierarchy which looks like this:
2906 * 1. We want to realise cgroup "d" now.
2907 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
2908 * 3. cgroup "k" just started requesting the memory controller.
2910 * To make this work we must do the following in order:
2912 * 1. Disable CPU controller in k, j
2913 * 2. Disable CPU controller in d
2914 * 3. Enable memory controller in root
2915 * 4. Enable memory controller in a
2916 * 5. Enable memory controller in d
2917 * 6. Enable memory controller in k
2919 * Notice that we need to touch j in one direction, but not the other. We also
2920 * don't go beyond d when disabling -- it's up to "a" to get realized if it
2921 * wants to disable further. The basic rules are therefore:
2923 * - If you're disabling something, you need to realise all of the cgroups from
2924 * your recursive descendants to the root. This starts from the leaves.
2925 * - If you're enabling something, you need to realise from the root cgroup
2926 * downwards, but you don't need to iterate your recursive descendants.
2928 * Returns 0 on success and < 0 on failure. */
2929 static int unit_realize_cgroup_now(Unit
*u
, ManagerState state
) {
2930 CGroupMask target_mask
, enable_mask
;
2936 unit_remove_from_cgroup_realize_queue(u
);
2938 target_mask
= unit_get_target_mask(u
);
2939 enable_mask
= unit_get_enable_mask(u
);
2941 if (unit_has_mask_realized(u
, target_mask
, enable_mask
))
2944 /* Disable controllers below us, if there are any */
2945 r
= unit_realize_cgroup_now_disable(u
, state
);
2949 /* Enable controllers above us, if there are any */
2950 slice
= UNIT_GET_SLICE(u
);
2952 r
= unit_realize_cgroup_now_enable(slice
, state
);
2957 /* Now actually deal with the cgroup we were trying to realise and set attributes */
2958 r
= unit_update_cgroup(u
, target_mask
, enable_mask
, state
);
2962 /* Now, reset the invalidation mask */
2963 u
->cgroup_invalidated_mask
= 0;
2967 unsigned manager_dispatch_cgroup_realize_queue(Manager
*m
) {
2975 state
= manager_state(m
);
2977 while ((i
= m
->cgroup_realize_queue
)) {
2978 assert(i
->in_cgroup_realize_queue
);
2980 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i
))) {
2981 /* Maybe things changed, and the unit is not actually active anymore? */
2982 unit_remove_from_cgroup_realize_queue(i
);
2986 r
= unit_realize_cgroup_now(i
, state
);
2988 log_warning_errno(r
, "Failed to realize cgroups for queued unit %s, ignoring: %m", i
->id
);
2996 void unit_add_family_to_cgroup_realize_queue(Unit
*u
) {
2998 assert(u
->type
== UNIT_SLICE
);
3000 /* Family of a unit for is defined as (immediate) children of the unit and immediate children of all
3003 * Ideally we would enqueue ancestor path only (bottom up). However, on cgroup-v1 scheduling becomes
3004 * very weird if two units that own processes reside in the same slice, but one is realized in the
3005 * "cpu" hierarchy and one is not (for example because one has CPUWeight= set and the other does
3006 * not), because that means individual processes need to be scheduled against whole cgroups. Let's
3007 * avoid this asymmetry by always ensuring that siblings of a unit are always realized in their v1
3008 * controller hierarchies too (if unit requires the controller to be realized).
3010 * The function must invalidate cgroup_members_mask of all ancestors in order to calculate up to date
3016 /* Children of u likely changed when we're called */
3017 u
->cgroup_members_mask_valid
= false;
3019 UNIT_FOREACH_DEPENDENCY(m
, u
, UNIT_ATOM_SLICE_OF
) {
3021 /* No point in doing cgroup application for units without active processes. */
3022 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m
)))
3025 /* We only enqueue siblings if they were realized once at least, in the main
3027 if (!m
->cgroup_realized
)
3030 /* If the unit doesn't need any new controllers and has current ones
3031 * realized, it doesn't need any changes. */
3032 if (unit_has_mask_realized(m
,
3033 unit_get_target_mask(m
),
3034 unit_get_enable_mask(m
)))
3037 unit_add_to_cgroup_realize_queue(m
);
3040 /* Parent comes after children */
3041 unit_add_to_cgroup_realize_queue(u
);
3043 u
= UNIT_GET_SLICE(u
);
3047 int unit_realize_cgroup(Unit
*u
) {
3052 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
3055 /* So, here's the deal: when realizing the cgroups for this unit, we need to first create all
3056 * parents, but there's more actually: for the weight-based controllers we also need to make sure
3057 * that all our siblings (i.e. units that are in the same slice as we are) have cgroups, too. On the
3058 * other hand, when a controller is removed from realized set, it may become unnecessary in siblings
3059 * and ancestors and they should be (de)realized too.
3061 * This call will defer work on the siblings and derealized ancestors to the next event loop
3062 * iteration and synchronously creates the parent cgroups (unit_realize_cgroup_now). */
3064 slice
= UNIT_GET_SLICE(u
);
3066 unit_add_family_to_cgroup_realize_queue(slice
);
3068 /* And realize this one now (and apply the values) */
3069 return unit_realize_cgroup_now(u
, manager_state(u
->manager
));
3072 void unit_release_cgroup(Unit
*u
) {
3075 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
3076 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
3078 if (u
->cgroup_path
) {
3079 (void) hashmap_remove(u
->manager
->cgroup_unit
, u
->cgroup_path
);
3080 u
->cgroup_path
= mfree(u
->cgroup_path
);
3083 if (u
->cgroup_control_inotify_wd
>= 0) {
3084 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_control_inotify_wd
) < 0)
3085 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
);
3087 (void) hashmap_remove(u
->manager
->cgroup_control_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_control_inotify_wd
));
3088 u
->cgroup_control_inotify_wd
= -1;
3091 if (u
->cgroup_memory_inotify_wd
>= 0) {
3092 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_memory_inotify_wd
) < 0)
3093 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
);
3095 (void) hashmap_remove(u
->manager
->cgroup_memory_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_memory_inotify_wd
));
3096 u
->cgroup_memory_inotify_wd
= -1;
3100 bool unit_maybe_release_cgroup(Unit
*u
) {
3105 if (!u
->cgroup_path
)
3108 /* Don't release the cgroup if there are still processes under it. If we get notified later when all the
3109 * processes exit (e.g. the processes were in D-state and exited after the unit was marked as failed)
3110 * we need the cgroup paths to continue to be tracked by the manager so they can be looked up and cleaned
3112 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
3114 log_unit_debug_errno(u
, r
, "Error checking if the cgroup is recursively empty, ignoring: %m");
3116 unit_release_cgroup(u
);
3123 void unit_prune_cgroup(Unit
*u
) {
3129 /* Removes the cgroup, if empty and possible, and stops watching it. */
3131 if (!u
->cgroup_path
)
3134 /* Cache the last CPU and memory usage values before we destroy the cgroup */
3135 (void) unit_get_cpu_usage(u
, /* ret = */ NULL
);
3137 for (CGroupMemoryAccountingMetric metric
= 0; metric
<= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST
; metric
++)
3138 (void) unit_get_memory_accounting(u
, metric
, /* ret = */ NULL
);
3141 (void) lsm_bpf_cleanup(u
); /* Remove cgroup from the global LSM BPF map */
3144 unit_modify_nft_set(u
, /* add = */ false);
3146 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
3148 r
= cg_trim_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, !is_root_slice
);
3150 /* One reason we could have failed here is, that the cgroup still contains a process.
3151 * However, if the cgroup becomes removable at a later time, it might be removed when
3152 * the containing slice is stopped. So even if we failed now, this unit shouldn't assume
3153 * that the cgroup is still realized the next time it is started. Do not return early
3154 * on error, continue cleanup. */
3155 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
));
3160 if (!unit_maybe_release_cgroup(u
)) /* Returns true if the cgroup was released */
3163 u
->cgroup_realized
= false;
3164 u
->cgroup_realized_mask
= 0;
3165 u
->cgroup_enabled_mask
= 0;
3167 u
->bpf_device_control_installed
= bpf_program_free(u
->bpf_device_control_installed
);
3170 int unit_search_main_pid(Unit
*u
, PidRef
*ret
) {
3171 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
3172 _cleanup_fclose_
FILE *f
= NULL
;
3178 if (!u
->cgroup_path
)
3181 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, &f
);
3186 _cleanup_(pidref_done
) PidRef npidref
= PIDREF_NULL
;
3188 r
= cg_read_pidref(f
, &npidref
);
3194 if (pidref_equal(&pidref
, &npidref
)) /* seen already, cgroupfs reports duplicates! */
3197 if (pidref_is_my_child(&npidref
) <= 0) /* ignore processes further down the tree */
3200 if (pidref_is_set(&pidref
) != 0)
3201 /* Dang, there's more than one daemonized PID in this group, so we don't know what
3202 * process is the main process. */
3205 pidref
= TAKE_PIDREF(npidref
);
3208 if (!pidref_is_set(&pidref
))
3211 *ret
= TAKE_PIDREF(pidref
);
3215 static int unit_watch_pids_in_path(Unit
*u
, const char *path
) {
3216 _cleanup_closedir_
DIR *d
= NULL
;
3217 _cleanup_fclose_
FILE *f
= NULL
;
3223 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
);
3228 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
3230 r
= cg_read_pidref(f
, &pid
);
3238 RET_GATHER(ret
, unit_watch_pidref(u
, &pid
, /* exclusive= */ false));
3242 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
3247 _cleanup_free_
char *fn
= NULL
, *p
= NULL
;
3249 r
= cg_read_subgroup(d
, &fn
);
3257 p
= path_join(empty_to_root(path
), fn
);
3261 RET_GATHER(ret
, unit_watch_pids_in_path(u
, p
));
3268 int unit_synthesize_cgroup_empty_event(Unit
*u
) {
3273 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
3274 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
3275 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
3277 if (!u
->cgroup_path
)
3280 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
3283 if (r
> 0) /* On unified we have reliable notifications, and don't need this */
3286 if (!set_isempty(u
->pids
))
3289 unit_add_to_cgroup_empty_queue(u
);
3293 int unit_watch_all_pids(Unit
*u
) {
3298 /* Adds all PIDs from our cgroup to the set of PIDs we
3299 * watch. This is a fallback logic for cases where we do not
3300 * get reliable cgroup empty notifications: we try to use
3301 * SIGCHLD as replacement. */
3303 if (!u
->cgroup_path
)
3306 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
3309 if (r
> 0) /* On unified we can use proper notifications */
3312 return unit_watch_pids_in_path(u
, u
->cgroup_path
);
3315 static int on_cgroup_empty_event(sd_event_source
*s
, void *userdata
) {
3316 Manager
*m
= ASSERT_PTR(userdata
);
3322 u
= m
->cgroup_empty_queue
;
3326 assert(u
->in_cgroup_empty_queue
);
3327 u
->in_cgroup_empty_queue
= false;
3328 LIST_REMOVE(cgroup_empty_queue
, m
->cgroup_empty_queue
, u
);
3330 if (m
->cgroup_empty_queue
) {
3331 /* More stuff queued, let's make sure we remain enabled */
3332 r
= sd_event_source_set_enabled(s
, SD_EVENT_ONESHOT
);
3334 log_debug_errno(r
, "Failed to reenable cgroup empty event source, ignoring: %m");
3337 /* Update state based on OOM kills before we notify about cgroup empty event */
3338 (void) unit_check_oom(u
);
3339 (void) unit_check_oomd_kill(u
);
3341 unit_add_to_gc_queue(u
);
3343 if (IN_SET(unit_active_state(u
), UNIT_INACTIVE
, UNIT_FAILED
))
3344 unit_prune_cgroup(u
);
3345 else if (UNIT_VTABLE(u
)->notify_cgroup_empty
)
3346 UNIT_VTABLE(u
)->notify_cgroup_empty(u
);
3351 void unit_add_to_cgroup_empty_queue(Unit
*u
) {
3356 /* Note that there are four different ways how cgroup empty events reach us:
3358 * 1. On the unified hierarchy we get an inotify event on the cgroup
3360 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
3362 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
3364 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
3365 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
3367 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
3368 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
3369 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
3370 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
3371 * case for scope units). */
3373 if (u
->in_cgroup_empty_queue
)
3376 /* Let's verify that the cgroup is really empty */
3377 if (!u
->cgroup_path
)
3380 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
3382 log_unit_debug_errno(u
, r
, "Failed to determine whether cgroup %s is empty: %m", empty_to_root(u
->cgroup_path
));
3388 LIST_PREPEND(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
3389 u
->in_cgroup_empty_queue
= true;
3391 /* Trigger the defer event */
3392 r
= sd_event_source_set_enabled(u
->manager
->cgroup_empty_event_source
, SD_EVENT_ONESHOT
);
3394 log_debug_errno(r
, "Failed to enable cgroup empty event source: %m");
3397 static void unit_remove_from_cgroup_empty_queue(Unit
*u
) {
3400 if (!u
->in_cgroup_empty_queue
)
3403 LIST_REMOVE(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
3404 u
->in_cgroup_empty_queue
= false;
3407 int unit_check_oomd_kill(Unit
*u
) {
3408 _cleanup_free_
char *value
= NULL
;
3413 if (!u
->cgroup_path
)
3416 r
= cg_all_unified();
3418 return log_unit_debug_errno(u
, r
, "Couldn't determine whether we are in all unified mode: %m");
3422 r
= cg_get_xattr_malloc(u
->cgroup_path
, "user.oomd_ooms", &value
);
3423 if (r
< 0 && !ERRNO_IS_XATTR_ABSENT(r
))
3426 if (!isempty(value
)) {
3427 r
= safe_atou64(value
, &n
);
3432 increased
= n
> u
->managed_oom_kill_last
;
3433 u
->managed_oom_kill_last
= n
;
3439 value
= mfree(value
);
3440 r
= cg_get_xattr_malloc(u
->cgroup_path
, "user.oomd_kill", &value
);
3441 if (r
>= 0 && !isempty(value
))
3442 (void) safe_atou64(value
, &n
);
3445 log_unit_struct(u
, LOG_NOTICE
,
3446 "MESSAGE_ID=" SD_MESSAGE_UNIT_OOMD_KILL_STR
,
3447 LOG_UNIT_INVOCATION_ID(u
),
3448 LOG_UNIT_MESSAGE(u
, "systemd-oomd killed %"PRIu64
" process(es) in this unit.", n
),
3449 "N_PROCESSES=%" PRIu64
, n
);
3451 log_unit_struct(u
, LOG_NOTICE
,
3452 "MESSAGE_ID=" SD_MESSAGE_UNIT_OOMD_KILL_STR
,
3453 LOG_UNIT_INVOCATION_ID(u
),
3454 LOG_UNIT_MESSAGE(u
, "systemd-oomd killed some process(es) in this unit."));
3456 unit_notify_cgroup_oom(u
, /* ManagedOOM= */ true);
3461 int unit_check_oom(Unit
*u
) {
3462 _cleanup_free_
char *oom_kill
= NULL
;
3467 if (!u
->cgroup_path
)
3470 r
= cg_get_keyed_attribute("memory", u
->cgroup_path
, "memory.events", STRV_MAKE("oom_kill"), &oom_kill
);
3471 if (IN_SET(r
, -ENOENT
, -ENXIO
)) /* Handle gracefully if cgroup or oom_kill attribute don't exist */
3474 return log_unit_debug_errno(u
, r
, "Failed to read oom_kill field of memory.events cgroup attribute: %m");
3476 r
= safe_atou64(oom_kill
, &c
);
3478 return log_unit_debug_errno(u
, r
, "Failed to parse oom_kill field: %m");
3481 increased
= c
> u
->oom_kill_last
;
3482 u
->oom_kill_last
= c
;
3487 log_unit_struct(u
, LOG_NOTICE
,
3488 "MESSAGE_ID=" SD_MESSAGE_UNIT_OUT_OF_MEMORY_STR
,
3489 LOG_UNIT_INVOCATION_ID(u
),
3490 LOG_UNIT_MESSAGE(u
, "A process of this unit has been killed by the OOM killer."));
3492 unit_notify_cgroup_oom(u
, /* ManagedOOM= */ false);
3497 static int on_cgroup_oom_event(sd_event_source
*s
, void *userdata
) {
3498 Manager
*m
= ASSERT_PTR(userdata
);
3504 u
= m
->cgroup_oom_queue
;
3508 assert(u
->in_cgroup_oom_queue
);
3509 u
->in_cgroup_oom_queue
= false;
3510 LIST_REMOVE(cgroup_oom_queue
, m
->cgroup_oom_queue
, u
);
3512 if (m
->cgroup_oom_queue
) {
3513 /* More stuff queued, let's make sure we remain enabled */
3514 r
= sd_event_source_set_enabled(s
, SD_EVENT_ONESHOT
);
3516 log_debug_errno(r
, "Failed to reenable cgroup oom event source, ignoring: %m");
3519 (void) unit_check_oom(u
);
3520 unit_add_to_gc_queue(u
);
3525 static void unit_add_to_cgroup_oom_queue(Unit
*u
) {
3530 if (u
->in_cgroup_oom_queue
)
3532 if (!u
->cgroup_path
)
3535 LIST_PREPEND(cgroup_oom_queue
, u
->manager
->cgroup_oom_queue
, u
);
3536 u
->in_cgroup_oom_queue
= true;
3538 /* Trigger the defer event */
3539 if (!u
->manager
->cgroup_oom_event_source
) {
3540 _cleanup_(sd_event_source_unrefp
) sd_event_source
*s
= NULL
;
3542 r
= sd_event_add_defer(u
->manager
->event
, &s
, on_cgroup_oom_event
, u
->manager
);
3544 log_error_errno(r
, "Failed to create cgroup oom event source: %m");
3548 r
= sd_event_source_set_priority(s
, SD_EVENT_PRIORITY_NORMAL
-8);
3550 log_error_errno(r
, "Failed to set priority of cgroup oom event source: %m");
3554 (void) sd_event_source_set_description(s
, "cgroup-oom");
3555 u
->manager
->cgroup_oom_event_source
= TAKE_PTR(s
);
3558 r
= sd_event_source_set_enabled(u
->manager
->cgroup_oom_event_source
, SD_EVENT_ONESHOT
);
3560 log_error_errno(r
, "Failed to enable cgroup oom event source: %m");
3563 static int unit_check_cgroup_events(Unit
*u
) {
3564 char *values
[2] = {};
3569 if (!u
->cgroup_path
)
3572 r
= cg_get_keyed_attribute_graceful(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events",
3573 STRV_MAKE("populated", "frozen"), values
);
3577 /* The cgroup.events notifications can be merged together so act as we saw the given state for the
3578 * first time. The functions we call to handle given state are idempotent, which makes them
3579 * effectively remember the previous state. */
3581 if (streq(values
[0], "1"))
3582 unit_remove_from_cgroup_empty_queue(u
);
3584 unit_add_to_cgroup_empty_queue(u
);
3587 /* Disregard freezer state changes due to operations not initiated by us */
3588 if (values
[1] && IN_SET(u
->freezer_state
, FREEZER_FREEZING
, FREEZER_THAWING
)) {
3589 if (streq(values
[1], "0"))
3601 static int on_cgroup_inotify_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
3602 Manager
*m
= ASSERT_PTR(userdata
);
3608 union inotify_event_buffer buffer
;
3611 l
= read(fd
, &buffer
, sizeof(buffer
));
3613 if (ERRNO_IS_TRANSIENT(errno
))
3616 return log_error_errno(errno
, "Failed to read control group inotify events: %m");
3619 FOREACH_INOTIFY_EVENT_WARN(e
, buffer
, l
) {
3623 /* Queue overflow has no watch descriptor */
3626 if (e
->mask
& IN_IGNORED
)
3627 /* The watch was just removed */
3630 /* Note that inotify might deliver events for a watch even after it was removed,
3631 * because it was queued before the removal. Let's ignore this here safely. */
3633 u
= hashmap_get(m
->cgroup_control_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
3635 unit_check_cgroup_events(u
);
3637 u
= hashmap_get(m
->cgroup_memory_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
3639 unit_add_to_cgroup_oom_queue(u
);
3644 static int cg_bpf_mask_supported(CGroupMask
*ret
) {
3645 CGroupMask mask
= 0;
3648 /* BPF-based firewall */
3649 r
= bpf_firewall_supported();
3653 mask
|= CGROUP_MASK_BPF_FIREWALL
;
3655 /* BPF-based device access control */
3656 r
= bpf_devices_supported();
3660 mask
|= CGROUP_MASK_BPF_DEVICES
;
3662 /* BPF pinned prog */
3663 r
= bpf_foreign_supported();
3667 mask
|= CGROUP_MASK_BPF_FOREIGN
;
3669 /* BPF-based bind{4|6} hooks */
3670 r
= bpf_socket_bind_supported();
3674 mask
|= CGROUP_MASK_BPF_SOCKET_BIND
;
3676 /* BPF-based cgroup_skb/{egress|ingress} hooks */
3677 r
= restrict_network_interfaces_supported();
3681 mask
|= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES
;
3687 int manager_setup_cgroup(Manager
*m
) {
3688 _cleanup_free_
char *path
= NULL
;
3689 const char *scope_path
;
3696 /* 1. Determine hierarchy */
3697 m
->cgroup_root
= mfree(m
->cgroup_root
);
3698 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &m
->cgroup_root
);
3700 return log_error_errno(r
, "Cannot determine cgroup we are running in: %m");
3702 /* Chop off the init scope, if we are already located in it */
3703 e
= endswith(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
3705 /* LEGACY: Also chop off the system slice if we are in
3706 * it. This is to support live upgrades from older systemd
3707 * versions where PID 1 was moved there. Also see
3708 * cg_get_root_path(). */
3709 if (!e
&& MANAGER_IS_SYSTEM(m
)) {
3710 e
= endswith(m
->cgroup_root
, "/" SPECIAL_SYSTEM_SLICE
);
3712 e
= endswith(m
->cgroup_root
, "/system"); /* even more legacy */
3717 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
3718 * easily prepend it everywhere. */
3719 delete_trailing_chars(m
->cgroup_root
, "/");
3722 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, NULL
, &path
);
3724 return log_error_errno(r
, "Cannot find cgroup mount point: %m");
3728 return log_error_errno(r
, "Couldn't determine if we are running in the unified hierarchy: %m");
3730 all_unified
= cg_all_unified();
3731 if (all_unified
< 0)
3732 return log_error_errno(all_unified
, "Couldn't determine whether we are in all unified mode: %m");
3733 if (all_unified
> 0)
3734 log_debug("Unified cgroup hierarchy is located at %s.", path
);
3736 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
3738 return log_error_errno(r
, "Failed to determine whether systemd's own controller is in unified mode: %m");
3740 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path
);
3742 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY
". File system hierarchy is at %s.", path
);
3745 /* 3. Allocate cgroup empty defer event source */
3746 m
->cgroup_empty_event_source
= sd_event_source_disable_unref(m
->cgroup_empty_event_source
);
3747 r
= sd_event_add_defer(m
->event
, &m
->cgroup_empty_event_source
, on_cgroup_empty_event
, m
);
3749 return log_error_errno(r
, "Failed to create cgroup empty event source: %m");
3751 /* Schedule cgroup empty checks early, but after having processed service notification messages or
3752 * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of
3753 * notification, and we collected the metadata the notification and SIGCHLD stuff offers first. */
3754 r
= sd_event_source_set_priority(m
->cgroup_empty_event_source
, SD_EVENT_PRIORITY_NORMAL
-5);
3756 return log_error_errno(r
, "Failed to set priority of cgroup empty event source: %m");
3758 r
= sd_event_source_set_enabled(m
->cgroup_empty_event_source
, SD_EVENT_OFF
);
3760 return log_error_errno(r
, "Failed to disable cgroup empty event source: %m");
3762 (void) sd_event_source_set_description(m
->cgroup_empty_event_source
, "cgroup-empty");
3764 /* 4. Install notifier inotify object, or agent */
3765 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0) {
3767 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
3769 m
->cgroup_inotify_event_source
= sd_event_source_disable_unref(m
->cgroup_inotify_event_source
);
3770 safe_close(m
->cgroup_inotify_fd
);
3772 m
->cgroup_inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
3773 if (m
->cgroup_inotify_fd
< 0)
3774 return log_error_errno(errno
, "Failed to create control group inotify object: %m");
3776 r
= sd_event_add_io(m
->event
, &m
->cgroup_inotify_event_source
, m
->cgroup_inotify_fd
, EPOLLIN
, on_cgroup_inotify_event
, m
);
3778 return log_error_errno(r
, "Failed to watch control group inotify object: %m");
3780 /* Process cgroup empty notifications early. Note that when this event is dispatched it'll
3781 * just add the unit to a cgroup empty queue, hence let's run earlier than that. Also see
3782 * handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
3783 r
= sd_event_source_set_priority(m
->cgroup_inotify_event_source
, SD_EVENT_PRIORITY_NORMAL
-9);
3785 return log_error_errno(r
, "Failed to set priority of inotify event source: %m");
3787 (void) sd_event_source_set_description(m
->cgroup_inotify_event_source
, "cgroup-inotify");
3789 } else if (MANAGER_IS_SYSTEM(m
) && manager_owns_host_root_cgroup(m
) && !MANAGER_IS_TEST_RUN(m
)) {
3791 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
3792 * since it does not generate events when control groups with children run empty. */
3794 r
= cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER
, SYSTEMD_CGROUPS_AGENT_PATH
);
3796 log_warning_errno(r
, "Failed to install release agent, ignoring: %m");
3798 log_debug("Installed release agent.");
3800 log_debug("Release agent already installed.");
3803 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
3804 scope_path
= strjoina(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
3805 r
= cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
3807 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
3808 r
= cg_migrate(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
3810 log_warning_errno(r
, "Couldn't move remaining userspace processes, ignoring: %m");
3812 /* 6. And pin it, so that it cannot be unmounted */
3813 safe_close(m
->pin_cgroupfs_fd
);
3814 m
->pin_cgroupfs_fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
3815 if (m
->pin_cgroupfs_fd
< 0)
3816 return log_error_errno(errno
, "Failed to open pin file: %m");
3818 } else if (!MANAGER_IS_TEST_RUN(m
))
3819 return log_error_errno(r
, "Failed to create %s control group: %m", scope_path
);
3821 /* 7. Always enable hierarchical support if it exists... */
3822 if (!all_unified
&& !MANAGER_IS_TEST_RUN(m
))
3823 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
3825 /* 8. Figure out which controllers are supported */
3826 r
= cg_mask_supported_subtree(m
->cgroup_root
, &m
->cgroup_supported
);
3828 return log_error_errno(r
, "Failed to determine supported controllers: %m");
3830 /* 9. Figure out which bpf-based pseudo-controllers are supported */
3831 r
= cg_bpf_mask_supported(&mask
);
3833 return log_error_errno(r
, "Failed to determine supported bpf-based pseudo-controllers: %m");
3834 m
->cgroup_supported
|= mask
;
3836 /* 10. Log which controllers are supported */
3837 for (CGroupController c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++)
3838 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c
),
3839 yes_no(m
->cgroup_supported
& CGROUP_CONTROLLER_TO_MASK(c
)));
3844 void manager_shutdown_cgroup(Manager
*m
, bool delete) {
3847 /* We can't really delete the group, since we are in it. But
3849 if (delete && m
->cgroup_root
&& !FLAGS_SET(m
->test_run_flags
, MANAGER_TEST_RUN_MINIMAL
))
3850 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, false);
3852 m
->cgroup_empty_event_source
= sd_event_source_disable_unref(m
->cgroup_empty_event_source
);
3854 m
->cgroup_control_inotify_wd_unit
= hashmap_free(m
->cgroup_control_inotify_wd_unit
);
3855 m
->cgroup_memory_inotify_wd_unit
= hashmap_free(m
->cgroup_memory_inotify_wd_unit
);
3857 m
->cgroup_inotify_event_source
= sd_event_source_disable_unref(m
->cgroup_inotify_event_source
);
3858 m
->cgroup_inotify_fd
= safe_close(m
->cgroup_inotify_fd
);
3860 m
->pin_cgroupfs_fd
= safe_close(m
->pin_cgroupfs_fd
);
3862 m
->cgroup_root
= mfree(m
->cgroup_root
);
3865 Unit
* manager_get_unit_by_cgroup(Manager
*m
, const char *cgroup
) {
3872 u
= hashmap_get(m
->cgroup_unit
, cgroup
);
3876 p
= strdupa_safe(cgroup
);
3880 e
= strrchr(p
, '/');
3882 return hashmap_get(m
->cgroup_unit
, SPECIAL_ROOT_SLICE
);
3886 u
= hashmap_get(m
->cgroup_unit
, p
);
3892 Unit
*manager_get_unit_by_pidref_cgroup(Manager
*m
, PidRef
*pid
) {
3893 _cleanup_free_
char *cgroup
= NULL
;
3897 if (cg_pidref_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &cgroup
) < 0)
3900 return manager_get_unit_by_cgroup(m
, cgroup
);
3903 Unit
*manager_get_unit_by_pidref_watching(Manager
*m
, PidRef
*pid
) {
3908 if (!pidref_is_set(pid
))
3911 u
= hashmap_get(m
->watch_pids
, pid
);
3915 array
= hashmap_get(m
->watch_pids_more
, pid
);
3922 Unit
*manager_get_unit_by_pidref(Manager
*m
, PidRef
*pid
) {
3927 /* Note that a process might be owned by multiple units, we return only one here, which is good
3928 * enough for most cases, though not strictly correct. We prefer the one reported by cgroup
3929 * membership, as that's the most relevant one as children of the process will be assigned to that
3930 * one, too, before all else. */
3932 if (!pidref_is_set(pid
))
3935 if (pidref_is_self(pid
))
3936 return hashmap_get(m
->units
, SPECIAL_INIT_SCOPE
);
3940 u
= manager_get_unit_by_pidref_cgroup(m
, pid
);
3944 u
= manager_get_unit_by_pidref_watching(m
, pid
);
3951 Unit
*manager_get_unit_by_pid(Manager
*m
, pid_t pid
) {
3954 if (!pid_is_valid(pid
))
3957 return manager_get_unit_by_pidref(m
, &PIDREF_MAKE_FROM_PID(pid
));
3960 int manager_notify_cgroup_empty(Manager
*m
, const char *cgroup
) {
3966 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
3967 * or from the --system instance */
3969 log_debug("Got cgroup empty notification for: %s", cgroup
);
3971 u
= manager_get_unit_by_cgroup(m
, cgroup
);
3975 unit_add_to_cgroup_empty_queue(u
);
3979 int unit_get_memory_available(Unit
*u
, uint64_t *ret
) {
3980 uint64_t available
= UINT64_MAX
, current
= 0;
3985 /* If data from cgroups can be accessed, try to find out how much more memory a unit can
3986 * claim before hitting the configured cgroup limits (if any). Consider both MemoryHigh
3987 * and MemoryMax, and also any slice the unit might be nested below. */
3990 uint64_t unit_available
, unit_limit
= UINT64_MAX
;
3991 CGroupContext
*unit_context
;
3993 /* No point in continuing if we can't go any lower */
3997 unit_context
= unit_get_cgroup_context(u
);
4001 if (!u
->cgroup_path
)
4004 (void) unit_get_memory_current(u
, ¤t
);
4005 /* in case of error, previous current propagates as lower bound */
4007 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
4008 unit_limit
= physical_memory();
4009 else if (unit_context
->memory_max
== UINT64_MAX
&& unit_context
->memory_high
== UINT64_MAX
)
4011 unit_limit
= MIN3(unit_limit
, unit_context
->memory_max
, unit_context
->memory_high
);
4013 unit_available
= LESS_BY(unit_limit
, current
);
4014 available
= MIN(unit_available
, available
);
4015 } while ((u
= UNIT_GET_SLICE(u
)));
4022 int unit_get_memory_current(Unit
*u
, uint64_t *ret
) {
4025 // FIXME: Merge this into unit_get_memory_accounting after support for cgroup v1 is dropped
4030 if (!UNIT_CGROUP_BOOL(u
, memory_accounting
))
4033 if (!u
->cgroup_path
)
4036 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
4037 if (unit_has_host_root_cgroup(u
))
4038 return procfs_memory_get_used(ret
);
4040 if ((u
->cgroup_realized_mask
& CGROUP_MASK_MEMORY
) == 0)
4043 r
= cg_all_unified();
4047 return cg_get_attribute_as_uint64("memory", u
->cgroup_path
, r
> 0 ? "memory.current" : "memory.usage_in_bytes", ret
);
4050 int unit_get_memory_accounting(Unit
*u
, CGroupMemoryAccountingMetric metric
, uint64_t *ret
) {
4052 static const char* const attributes_table
[_CGROUP_MEMORY_ACCOUNTING_METRIC_MAX
] = {
4053 [CGROUP_MEMORY_PEAK
] = "memory.peak",
4054 [CGROUP_MEMORY_SWAP_CURRENT
] = "memory.swap.current",
4055 [CGROUP_MEMORY_SWAP_PEAK
] = "memory.swap.peak",
4056 [CGROUP_MEMORY_ZSWAP_CURRENT
] = "memory.zswap.current",
4060 bool updated
= false;
4064 assert(metric
>= 0);
4065 assert(metric
< _CGROUP_MEMORY_ACCOUNTING_METRIC_MAX
);
4067 if (!UNIT_CGROUP_BOOL(u
, memory_accounting
))
4070 if (!u
->cgroup_path
)
4071 /* If the cgroup is already gone, we try to find the last cached value. */
4074 /* The root cgroup doesn't expose this information. */
4075 if (unit_has_host_root_cgroup(u
))
4078 if (!FLAGS_SET(u
->cgroup_realized_mask
, CGROUP_MASK_MEMORY
))
4081 r
= cg_all_unified();
4087 r
= cg_get_attribute_as_uint64("memory", u
->cgroup_path
, attributes_table
[metric
], &bytes
);
4088 if (r
< 0 && r
!= -ENODATA
)
4093 if (metric
<= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST
) {
4094 uint64_t *last
= &u
->memory_accounting_last
[metric
];
4098 else if (*last
!= UINT64_MAX
)
4103 } else if (!updated
)
4112 int unit_get_tasks_current(Unit
*u
, uint64_t *ret
) {
4116 if (!UNIT_CGROUP_BOOL(u
, tasks_accounting
))
4119 if (!u
->cgroup_path
)
4122 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
4123 if (unit_has_host_root_cgroup(u
))
4124 return procfs_tasks_get_current(ret
);
4126 if ((u
->cgroup_realized_mask
& CGROUP_MASK_PIDS
) == 0)
4129 return cg_get_attribute_as_uint64("pids", u
->cgroup_path
, "pids.current", ret
);
4132 static int unit_get_cpu_usage_raw(Unit
*u
, nsec_t
*ret
) {
4139 if (!u
->cgroup_path
)
4142 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
4143 if (unit_has_host_root_cgroup(u
))
4144 return procfs_cpu_get_usage(ret
);
4146 /* Requisite controllers for CPU accounting are not enabled */
4147 if ((get_cpu_accounting_mask() & ~u
->cgroup_realized_mask
) != 0)
4150 r
= cg_all_unified();
4154 _cleanup_free_
char *val
= NULL
;
4157 r
= cg_get_keyed_attribute("cpu", u
->cgroup_path
, "cpu.stat", STRV_MAKE("usage_usec"), &val
);
4158 if (IN_SET(r
, -ENOENT
, -ENXIO
))
4163 r
= safe_atou64(val
, &us
);
4167 ns
= us
* NSEC_PER_USEC
;
4169 return cg_get_attribute_as_uint64("cpuacct", u
->cgroup_path
, "cpuacct.usage", ret
);
4175 int unit_get_cpu_usage(Unit
*u
, nsec_t
*ret
) {
4181 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
4182 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
4183 * call this function with a NULL return value. */
4185 if (!UNIT_CGROUP_BOOL(u
, cpu_accounting
))
4188 r
= unit_get_cpu_usage_raw(u
, &ns
);
4189 if (r
== -ENODATA
&& u
->cpu_usage_last
!= NSEC_INFINITY
) {
4190 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
4194 *ret
= u
->cpu_usage_last
;
4200 if (ns
> u
->cpu_usage_base
)
4201 ns
-= u
->cpu_usage_base
;
4205 u
->cpu_usage_last
= ns
;
4212 int unit_get_ip_accounting(
4214 CGroupIPAccountingMetric metric
,
4221 assert(metric
>= 0);
4222 assert(metric
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
);
4225 if (!UNIT_CGROUP_BOOL(u
, ip_accounting
))
4228 fd
= IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_INGRESS_PACKETS
) ?
4229 u
->ip_accounting_ingress_map_fd
:
4230 u
->ip_accounting_egress_map_fd
;
4234 if (IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_EGRESS_BYTES
))
4235 r
= bpf_firewall_read_accounting(fd
, &value
, NULL
);
4237 r
= bpf_firewall_read_accounting(fd
, NULL
, &value
);
4241 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
4242 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
4243 * ip_accounting_extra[] field, and add them in here transparently. */
4245 *ret
= value
+ u
->ip_accounting_extra
[metric
];
4250 static uint64_t unit_get_effective_limit_one(Unit
*u
, CGroupLimitType type
) {
4254 assert(UNIT_HAS_CGROUP_CONTEXT(u
));
4256 cc
= unit_get_cgroup_context(u
);
4258 /* Note: on legacy/hybrid hierarchies memory_max stays CGROUP_LIMIT_MAX unless configured
4259 * explicitly. Effective value of MemoryLimit= (cgroup v1) is not implemented. */
4260 case CGROUP_LIMIT_MEMORY_MAX
:
4261 return cc
->memory_max
;
4262 case CGROUP_LIMIT_MEMORY_HIGH
:
4263 return cc
->memory_high
;
4264 case CGROUP_LIMIT_TASKS_MAX
:
4265 return cgroup_tasks_max_resolve(&cc
->tasks_max
);
4267 assert_not_reached();
4271 int unit_get_effective_limit(Unit
*u
, CGroupLimitType type
, uint64_t *ret
) {
4277 assert(type
< _CGROUP_LIMIT_TYPE_MAX
);
4279 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
4282 infimum
= unit_get_effective_limit_one(u
, type
);
4283 for (Unit
*slice
= UNIT_GET_SLICE(u
); slice
; slice
= UNIT_GET_SLICE(slice
))
4284 infimum
= MIN(infimum
, unit_get_effective_limit_one(slice
, type
));
4290 static int unit_get_io_accounting_raw(Unit
*u
, uint64_t ret
[static _CGROUP_IO_ACCOUNTING_METRIC_MAX
]) {
4291 static const char *const field_names
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {
4292 [CGROUP_IO_READ_BYTES
] = "rbytes=",
4293 [CGROUP_IO_WRITE_BYTES
] = "wbytes=",
4294 [CGROUP_IO_READ_OPERATIONS
] = "rios=",
4295 [CGROUP_IO_WRITE_OPERATIONS
] = "wios=",
4297 uint64_t acc
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {};
4298 _cleanup_free_
char *path
= NULL
;
4299 _cleanup_fclose_
FILE *f
= NULL
;
4304 if (!u
->cgroup_path
)
4307 if (unit_has_host_root_cgroup(u
))
4308 return -ENODATA
; /* TODO: return useful data for the top-level cgroup */
4310 r
= cg_all_unified();
4313 if (r
== 0) /* TODO: support cgroupv1 */
4316 if (!FLAGS_SET(u
->cgroup_realized_mask
, CGROUP_MASK_IO
))
4319 r
= cg_get_path("io", u
->cgroup_path
, "io.stat", &path
);
4323 f
= fopen(path
, "re");
4328 _cleanup_free_
char *line
= NULL
;
4331 r
= read_line(f
, LONG_LINE_MAX
, &line
);
4338 p
+= strcspn(p
, WHITESPACE
); /* Skip over device major/minor */
4339 p
+= strspn(p
, WHITESPACE
); /* Skip over following whitespace */
4342 _cleanup_free_
char *word
= NULL
;
4344 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_RETAIN_ESCAPE
);
4350 for (CGroupIOAccountingMetric i
= 0; i
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; i
++) {
4353 x
= startswith(word
, field_names
[i
]);
4357 r
= safe_atou64(x
, &w
);
4361 /* Sum up the stats of all devices */
4369 memcpy(ret
, acc
, sizeof(acc
));
4373 int unit_get_io_accounting(
4375 CGroupIOAccountingMetric metric
,
4379 uint64_t raw
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
];
4382 /* Retrieve an IO account parameter. This will subtract the counter when the unit was started. */
4384 if (!UNIT_CGROUP_BOOL(u
, io_accounting
))
4387 if (allow_cache
&& u
->io_accounting_last
[metric
] != UINT64_MAX
)
4390 r
= unit_get_io_accounting_raw(u
, raw
);
4391 if (r
== -ENODATA
&& u
->io_accounting_last
[metric
] != UINT64_MAX
)
4396 for (CGroupIOAccountingMetric i
= 0; i
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; i
++) {
4397 /* Saturated subtraction */
4398 if (raw
[i
] > u
->io_accounting_base
[i
])
4399 u
->io_accounting_last
[i
] = raw
[i
] - u
->io_accounting_base
[i
];
4401 u
->io_accounting_last
[i
] = 0;
4406 *ret
= u
->io_accounting_last
[metric
];
4411 int unit_reset_cpu_accounting(Unit
*u
) {
4416 u
->cpu_usage_last
= NSEC_INFINITY
;
4418 r
= unit_get_cpu_usage_raw(u
, &u
->cpu_usage_base
);
4420 u
->cpu_usage_base
= 0;
4427 void unit_reset_memory_accounting_last(Unit
*u
) {
4430 FOREACH_ARRAY(i
, u
->memory_accounting_last
, ELEMENTSOF(u
->memory_accounting_last
))
4434 int unit_reset_ip_accounting(Unit
*u
) {
4439 if (u
->ip_accounting_ingress_map_fd
>= 0)
4440 RET_GATHER(r
, bpf_firewall_reset_accounting(u
->ip_accounting_ingress_map_fd
));
4442 if (u
->ip_accounting_egress_map_fd
>= 0)
4443 RET_GATHER(r
, bpf_firewall_reset_accounting(u
->ip_accounting_egress_map_fd
));
4445 zero(u
->ip_accounting_extra
);
4450 void unit_reset_io_accounting_last(Unit
*u
) {
4453 FOREACH_ARRAY(i
, u
->io_accounting_last
, _CGROUP_IO_ACCOUNTING_METRIC_MAX
)
4457 int unit_reset_io_accounting(Unit
*u
) {
4462 unit_reset_io_accounting_last(u
);
4464 r
= unit_get_io_accounting_raw(u
, u
->io_accounting_base
);
4466 zero(u
->io_accounting_base
);
4473 int unit_reset_accounting(Unit
*u
) {
4478 RET_GATHER(r
, unit_reset_cpu_accounting(u
));
4479 RET_GATHER(r
, unit_reset_io_accounting(u
));
4480 RET_GATHER(r
, unit_reset_ip_accounting(u
));
4481 unit_reset_memory_accounting_last(u
);
4486 void unit_invalidate_cgroup(Unit
*u
, CGroupMask m
) {
4489 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
4495 /* always invalidate compat pairs together */
4496 if (m
& (CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
))
4497 m
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
4499 if (m
& (CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
))
4500 m
|= CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
;
4502 if (FLAGS_SET(u
->cgroup_invalidated_mask
, m
)) /* NOP? */
4505 u
->cgroup_invalidated_mask
|= m
;
4506 unit_add_to_cgroup_realize_queue(u
);
4509 void unit_invalidate_cgroup_bpf(Unit
*u
) {
4512 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
4515 if (u
->cgroup_invalidated_mask
& CGROUP_MASK_BPF_FIREWALL
) /* NOP? */
4518 u
->cgroup_invalidated_mask
|= CGROUP_MASK_BPF_FIREWALL
;
4519 unit_add_to_cgroup_realize_queue(u
);
4521 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
4522 * list of our children includes our own. */
4523 if (u
->type
== UNIT_SLICE
) {
4526 UNIT_FOREACH_DEPENDENCY(member
, u
, UNIT_ATOM_SLICE_OF
)
4527 unit_invalidate_cgroup_bpf(member
);
4531 void unit_cgroup_catchup(Unit
*u
) {
4534 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
4537 /* We dropped the inotify watch during reexec/reload, so we need to
4538 * check these as they may have changed.
4539 * Note that (currently) the kernel doesn't actually update cgroup
4540 * file modification times, so we can't just serialize and then check
4541 * the mtime for file(s) we are interested in. */
4542 (void) unit_check_cgroup_events(u
);
4543 unit_add_to_cgroup_oom_queue(u
);
4546 bool unit_cgroup_delegate(Unit
*u
) {
4551 if (!UNIT_VTABLE(u
)->can_delegate
)
4554 c
= unit_get_cgroup_context(u
);
4561 void manager_invalidate_startup_units(Manager
*m
) {
4566 SET_FOREACH(u
, m
->startup_units
)
4567 unit_invalidate_cgroup(u
, CGROUP_MASK_CPU
|CGROUP_MASK_IO
|CGROUP_MASK_BLKIO
|CGROUP_MASK_CPUSET
);
4570 int unit_cgroup_freezer_action(Unit
*u
, FreezerAction action
) {
4571 _cleanup_free_
char *path
= NULL
;
4572 FreezerState target
, kernel
= _FREEZER_STATE_INVALID
;
4576 assert(IN_SET(action
, FREEZER_FREEZE
, FREEZER_THAW
));
4578 if (!cg_freezer_supported())
4581 /* Ignore all requests to thaw init.scope or -.slice and reject all requests to freeze them */
4582 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
) || unit_has_name(u
, SPECIAL_INIT_SCOPE
))
4583 return action
== FREEZER_FREEZE
? -EPERM
: 0;
4585 if (!u
->cgroup_realized
)
4588 if (action
== FREEZER_THAW
) {
4589 Unit
*slice
= UNIT_GET_SLICE(u
);
4592 r
= unit_cgroup_freezer_action(slice
, FREEZER_THAW
);
4594 return log_unit_error_errno(u
, r
, "Failed to thaw slice %s of unit: %m", slice
->id
);
4598 target
= action
== FREEZER_FREEZE
? FREEZER_FROZEN
: FREEZER_RUNNING
;
4600 r
= unit_freezer_state_kernel(u
, &kernel
);
4602 log_unit_debug_errno(u
, r
, "Failed to obtain cgroup freezer state: %m");
4604 if (target
== kernel
) {
4605 u
->freezer_state
= target
;
4606 if (action
== FREEZER_FREEZE
)
4612 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.freeze", &path
);
4616 log_unit_debug(u
, "%s unit.", action
== FREEZER_FREEZE
? "Freezing" : "Thawing");
4618 if (target
!= kernel
) {
4619 if (action
== FREEZER_FREEZE
)
4620 u
->freezer_state
= FREEZER_FREEZING
;
4622 u
->freezer_state
= FREEZER_THAWING
;
4625 r
= write_string_file(path
, one_zero(action
== FREEZER_FREEZE
), WRITE_STRING_FILE_DISABLE_BUFFER
);
4632 int unit_get_cpuset(Unit
*u
, CPUSet
*cpus
, const char *name
) {
4633 _cleanup_free_
char *v
= NULL
;
4639 if (!u
->cgroup_path
)
4642 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPUSET
) == 0)
4645 r
= cg_all_unified();
4651 r
= cg_get_attribute("cpuset", u
->cgroup_path
, name
, &v
);
4657 return parse_cpu_set_full(v
, cpus
, false, NULL
, NULL
, 0, NULL
);
4660 static const char* const cgroup_device_policy_table
[_CGROUP_DEVICE_POLICY_MAX
] = {
4661 [CGROUP_DEVICE_POLICY_AUTO
] = "auto",
4662 [CGROUP_DEVICE_POLICY_CLOSED
] = "closed",
4663 [CGROUP_DEVICE_POLICY_STRICT
] = "strict",
4666 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy
, CGroupDevicePolicy
);
4668 static const char* const freezer_action_table
[_FREEZER_ACTION_MAX
] = {
4669 [FREEZER_FREEZE
] = "freeze",
4670 [FREEZER_THAW
] = "thaw",
4673 DEFINE_STRING_TABLE_LOOKUP(freezer_action
, FreezerAction
);
4675 static const char* const cgroup_pressure_watch_table
[_CGROUP_PRESSURE_WATCH_MAX
] = {
4676 [CGROUP_PRESSURE_WATCH_OFF
] = "off",
4677 [CGROUP_PRESSURE_WATCH_AUTO
] = "auto",
4678 [CGROUP_PRESSURE_WATCH_ON
] = "on",
4679 [CGROUP_PRESSURE_WATCH_SKIP
] = "skip",
4682 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(cgroup_pressure_watch
, CGroupPressureWatch
, CGROUP_PRESSURE_WATCH_ON
);
4684 static const char* const cgroup_ip_accounting_metric_table
[_CGROUP_IP_ACCOUNTING_METRIC_MAX
] = {
4685 [CGROUP_IP_INGRESS_BYTES
] = "IPIngressBytes",
4686 [CGROUP_IP_EGRESS_BYTES
] = "IPEgressBytes",
4687 [CGROUP_IP_INGRESS_PACKETS
] = "IPIngressPackets",
4688 [CGROUP_IP_EGRESS_PACKETS
] = "IPEgressPackets",
4691 DEFINE_STRING_TABLE_LOOKUP(cgroup_ip_accounting_metric
, CGroupIPAccountingMetric
);
4693 static const char* const cgroup_io_accounting_metric_table
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {
4694 [CGROUP_IO_READ_BYTES
] = "IOReadBytes",
4695 [CGROUP_IO_WRITE_BYTES
] = "IOWriteBytes",
4696 [CGROUP_IO_READ_OPERATIONS
] = "IOReadOperations",
4697 [CGROUP_IO_WRITE_OPERATIONS
] = "IOWriteOperations",
4700 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_accounting_metric
, CGroupIOAccountingMetric
);
4702 static const char* const cgroup_memory_accounting_metric_table
[_CGROUP_MEMORY_ACCOUNTING_METRIC_MAX
] = {
4703 [CGROUP_MEMORY_PEAK
] = "MemoryPeak",
4704 [CGROUP_MEMORY_SWAP_CURRENT
] = "MemorySwapCurrent",
4705 [CGROUP_MEMORY_SWAP_PEAK
] = "MemorySwapPeak",
4706 [CGROUP_MEMORY_ZSWAP_CURRENT
] = "MemoryZSwapCurrent",
4709 DEFINE_STRING_TABLE_LOOKUP(cgroup_memory_accounting_metric
, CGroupMemoryAccountingMetric
);
4711 static const char *const cgroup_limit_type_table
[_CGROUP_LIMIT_TYPE_MAX
] = {
4712 [CGROUP_LIMIT_MEMORY_MAX
] = "EffectiveMemoryMax",
4713 [CGROUP_LIMIT_MEMORY_HIGH
] = "EffectiveMemoryHigh",
4714 [CGROUP_LIMIT_TASKS_MAX
] = "EffectiveTasksMax",
4717 DEFINE_STRING_TABLE_LOOKUP(cgroup_limit_type
, CGroupLimitType
);