1 /* SPDX-License-Identifier: LGPL-2.1+ */
6 #include "alloc-util.h"
7 #include "blockdev-util.h"
8 #include "bpf-firewall.h"
9 #include "btrfs-util.h"
10 #include "bpf-devices.h"
11 #include "bus-error.h"
12 #include "cgroup-util.h"
17 #include "parse-util.h"
18 #include "path-util.h"
19 #include "process-util.h"
20 #include "procfs-util.h"
22 #include "stat-util.h"
23 #include "stdio-util.h"
24 #include "string-table.h"
25 #include "string-util.h"
28 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
30 /* Returns the log level to use when cgroup attribute writes fail. When an attribute is missing or we have access
31 * problems we downgrade to LOG_DEBUG. This is supposed to be nice to container managers and kernels which want to mask
32 * out specific attributes from us. */
33 #define LOG_LEVEL_CGROUP_WRITE(r) (IN_SET(abs(r), ENOENT, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING)
35 bool manager_owns_host_root_cgroup(Manager
*m
) {
38 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
39 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
40 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
41 * we run in any kind of container virtualization. */
43 if (MANAGER_IS_USER(m
))
46 if (detect_container() > 0)
49 return empty_or_root(m
->cgroup_root
);
52 bool unit_has_host_root_cgroup(Unit
*u
) {
55 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
56 * the manager manages the root cgroup. */
58 if (!manager_owns_host_root_cgroup(u
->manager
))
61 return unit_has_name(u
, SPECIAL_ROOT_SLICE
);
64 static int set_attribute_and_warn(Unit
*u
, const char *controller
, const char *attribute
, const char *value
) {
67 r
= cg_set_attribute(controller
, u
->cgroup_path
, attribute
, value
);
69 log_unit_full(u
, LOG_LEVEL_CGROUP_WRITE(r
), r
, "Failed to set '%s' attribute on '%s' to '%.*s': %m",
70 strna(attribute
), isempty(u
->cgroup_path
) ? "/" : u
->cgroup_path
, (int) strcspn(value
, NEWLINE
), value
);
75 static void cgroup_compat_warn(void) {
76 static bool cgroup_compat_warned
= false;
78 if (cgroup_compat_warned
)
81 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
82 "See cgroup-compat debug messages for details.");
84 cgroup_compat_warned
= true;
87 #define log_cgroup_compat(unit, fmt, ...) do { \
88 cgroup_compat_warn(); \
89 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
92 void cgroup_context_init(CGroupContext
*c
) {
95 /* Initialize everything to the kernel defaults. */
97 *c
= (CGroupContext
) {
98 .cpu_weight
= CGROUP_WEIGHT_INVALID
,
99 .startup_cpu_weight
= CGROUP_WEIGHT_INVALID
,
100 .cpu_quota_per_sec_usec
= USEC_INFINITY
,
102 .cpu_shares
= CGROUP_CPU_SHARES_INVALID
,
103 .startup_cpu_shares
= CGROUP_CPU_SHARES_INVALID
,
105 .memory_high
= CGROUP_LIMIT_MAX
,
106 .memory_max
= CGROUP_LIMIT_MAX
,
107 .memory_swap_max
= CGROUP_LIMIT_MAX
,
109 .memory_limit
= CGROUP_LIMIT_MAX
,
111 .io_weight
= CGROUP_WEIGHT_INVALID
,
112 .startup_io_weight
= CGROUP_WEIGHT_INVALID
,
114 .blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
,
115 .startup_blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
,
117 .tasks_max
= CGROUP_LIMIT_MAX
,
121 void cgroup_context_free_device_allow(CGroupContext
*c
, CGroupDeviceAllow
*a
) {
125 LIST_REMOVE(device_allow
, c
->device_allow
, a
);
130 void cgroup_context_free_io_device_weight(CGroupContext
*c
, CGroupIODeviceWeight
*w
) {
134 LIST_REMOVE(device_weights
, c
->io_device_weights
, w
);
139 void cgroup_context_free_io_device_latency(CGroupContext
*c
, CGroupIODeviceLatency
*l
) {
143 LIST_REMOVE(device_latencies
, c
->io_device_latencies
, l
);
148 void cgroup_context_free_io_device_limit(CGroupContext
*c
, CGroupIODeviceLimit
*l
) {
152 LIST_REMOVE(device_limits
, c
->io_device_limits
, l
);
157 void cgroup_context_free_blockio_device_weight(CGroupContext
*c
, CGroupBlockIODeviceWeight
*w
) {
161 LIST_REMOVE(device_weights
, c
->blockio_device_weights
, w
);
166 void cgroup_context_free_blockio_device_bandwidth(CGroupContext
*c
, CGroupBlockIODeviceBandwidth
*b
) {
170 LIST_REMOVE(device_bandwidths
, c
->blockio_device_bandwidths
, b
);
175 void cgroup_context_done(CGroupContext
*c
) {
178 while (c
->io_device_weights
)
179 cgroup_context_free_io_device_weight(c
, c
->io_device_weights
);
181 while (c
->io_device_latencies
)
182 cgroup_context_free_io_device_latency(c
, c
->io_device_latencies
);
184 while (c
->io_device_limits
)
185 cgroup_context_free_io_device_limit(c
, c
->io_device_limits
);
187 while (c
->blockio_device_weights
)
188 cgroup_context_free_blockio_device_weight(c
, c
->blockio_device_weights
);
190 while (c
->blockio_device_bandwidths
)
191 cgroup_context_free_blockio_device_bandwidth(c
, c
->blockio_device_bandwidths
);
193 while (c
->device_allow
)
194 cgroup_context_free_device_allow(c
, c
->device_allow
);
196 c
->ip_address_allow
= ip_address_access_free_all(c
->ip_address_allow
);
197 c
->ip_address_deny
= ip_address_access_free_all(c
->ip_address_deny
);
200 void cgroup_context_dump(CGroupContext
*c
, FILE* f
, const char *prefix
) {
201 CGroupIODeviceLimit
*il
;
202 CGroupIODeviceWeight
*iw
;
203 CGroupIODeviceLatency
*l
;
204 CGroupBlockIODeviceBandwidth
*b
;
205 CGroupBlockIODeviceWeight
*w
;
206 CGroupDeviceAllow
*a
;
207 IPAddressAccessItem
*iaai
;
208 char u
[FORMAT_TIMESPAN_MAX
];
213 prefix
= strempty(prefix
);
216 "%sCPUAccounting=%s\n"
217 "%sIOAccounting=%s\n"
218 "%sBlockIOAccounting=%s\n"
219 "%sMemoryAccounting=%s\n"
220 "%sTasksAccounting=%s\n"
221 "%sIPAccounting=%s\n"
222 "%sCPUWeight=%" PRIu64
"\n"
223 "%sStartupCPUWeight=%" PRIu64
"\n"
224 "%sCPUShares=%" PRIu64
"\n"
225 "%sStartupCPUShares=%" PRIu64
"\n"
226 "%sCPUQuotaPerSecSec=%s\n"
227 "%sIOWeight=%" PRIu64
"\n"
228 "%sStartupIOWeight=%" PRIu64
"\n"
229 "%sBlockIOWeight=%" PRIu64
"\n"
230 "%sStartupBlockIOWeight=%" PRIu64
"\n"
231 "%sMemoryMin=%" PRIu64
"\n"
232 "%sMemoryLow=%" PRIu64
"\n"
233 "%sMemoryHigh=%" PRIu64
"\n"
234 "%sMemoryMax=%" PRIu64
"\n"
235 "%sMemorySwapMax=%" PRIu64
"\n"
236 "%sMemoryLimit=%" PRIu64
"\n"
237 "%sTasksMax=%" PRIu64
"\n"
238 "%sDevicePolicy=%s\n"
240 prefix
, yes_no(c
->cpu_accounting
),
241 prefix
, yes_no(c
->io_accounting
),
242 prefix
, yes_no(c
->blockio_accounting
),
243 prefix
, yes_no(c
->memory_accounting
),
244 prefix
, yes_no(c
->tasks_accounting
),
245 prefix
, yes_no(c
->ip_accounting
),
246 prefix
, c
->cpu_weight
,
247 prefix
, c
->startup_cpu_weight
,
248 prefix
, c
->cpu_shares
,
249 prefix
, c
->startup_cpu_shares
,
250 prefix
, format_timespan(u
, sizeof(u
), c
->cpu_quota_per_sec_usec
, 1),
251 prefix
, c
->io_weight
,
252 prefix
, c
->startup_io_weight
,
253 prefix
, c
->blockio_weight
,
254 prefix
, c
->startup_blockio_weight
,
255 prefix
, c
->memory_min
,
256 prefix
, c
->memory_low
,
257 prefix
, c
->memory_high
,
258 prefix
, c
->memory_max
,
259 prefix
, c
->memory_swap_max
,
260 prefix
, c
->memory_limit
,
261 prefix
, c
->tasks_max
,
262 prefix
, cgroup_device_policy_to_string(c
->device_policy
),
263 prefix
, yes_no(c
->delegate
));
266 _cleanup_free_
char *t
= NULL
;
268 (void) cg_mask_to_string(c
->delegate_controllers
, &t
);
270 fprintf(f
, "%sDelegateControllers=%s\n",
275 LIST_FOREACH(device_allow
, a
, c
->device_allow
)
277 "%sDeviceAllow=%s %s%s%s\n",
280 a
->r
? "r" : "", a
->w
? "w" : "", a
->m
? "m" : "");
282 LIST_FOREACH(device_weights
, iw
, c
->io_device_weights
)
284 "%sIODeviceWeight=%s %" PRIu64
"\n",
289 LIST_FOREACH(device_latencies
, l
, c
->io_device_latencies
)
291 "%sIODeviceLatencyTargetSec=%s %s\n",
294 format_timespan(u
, sizeof(u
), l
->target_usec
, 1));
296 LIST_FOREACH(device_limits
, il
, c
->io_device_limits
) {
297 char buf
[FORMAT_BYTES_MAX
];
298 CGroupIOLimitType type
;
300 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
301 if (il
->limits
[type
] != cgroup_io_limit_defaults
[type
])
305 cgroup_io_limit_type_to_string(type
),
307 format_bytes(buf
, sizeof(buf
), il
->limits
[type
]));
310 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
312 "%sBlockIODeviceWeight=%s %" PRIu64
,
317 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
318 char buf
[FORMAT_BYTES_MAX
];
320 if (b
->rbps
!= CGROUP_LIMIT_MAX
)
322 "%sBlockIOReadBandwidth=%s %s\n",
325 format_bytes(buf
, sizeof(buf
), b
->rbps
));
326 if (b
->wbps
!= CGROUP_LIMIT_MAX
)
328 "%sBlockIOWriteBandwidth=%s %s\n",
331 format_bytes(buf
, sizeof(buf
), b
->wbps
));
334 LIST_FOREACH(items
, iaai
, c
->ip_address_allow
) {
335 _cleanup_free_
char *k
= NULL
;
337 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
338 fprintf(f
, "%sIPAddressAllow=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
341 LIST_FOREACH(items
, iaai
, c
->ip_address_deny
) {
342 _cleanup_free_
char *k
= NULL
;
344 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
345 fprintf(f
, "%sIPAddressDeny=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
349 int cgroup_add_device_allow(CGroupContext
*c
, const char *dev
, const char *mode
) {
350 _cleanup_free_ CGroupDeviceAllow
*a
= NULL
;
351 _cleanup_free_
char *d
= NULL
;
355 assert(isempty(mode
) || in_charset(mode
, "rwm"));
357 a
= new(CGroupDeviceAllow
, 1);
365 *a
= (CGroupDeviceAllow
) {
367 .r
= isempty(mode
) || strchr(mode
, 'r'),
368 .w
= isempty(mode
) || strchr(mode
, 'w'),
369 .m
= isempty(mode
) || strchr(mode
, 'm'),
372 LIST_PREPEND(device_allow
, c
->device_allow
, a
);
378 static void cgroup_xattr_apply(Unit
*u
) {
379 char ids
[SD_ID128_STRING_MAX
];
384 if (!MANAGER_IS_SYSTEM(u
->manager
))
387 if (sd_id128_is_null(u
->invocation_id
))
390 r
= cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
391 "trusted.invocation_id",
392 sd_id128_to_string(u
->invocation_id
, ids
), 32,
395 log_unit_debug_errno(u
, r
, "Failed to set invocation ID on control group %s, ignoring: %m", u
->cgroup_path
);
398 static int lookup_block_device(const char *p
, dev_t
*ret
) {
405 r
= device_path_parse_major_minor(p
, &st
.st_mode
, &st
.st_rdev
);
406 if (r
== -ENODEV
) { /* not a parsable device node, need to go to disk */
407 if (stat(p
, &st
) < 0)
408 return log_warning_errno(errno
, "Couldn't stat device '%s': %m", p
);
410 return log_warning_errno(r
, "Failed to parse major/minor from path '%s': %m", p
);
412 if (S_ISCHR(st
.st_mode
)) {
413 log_warning("Device node '%s' is a character device, but block device needed.", p
);
415 } else if (S_ISBLK(st
.st_mode
))
417 else if (major(st
.st_dev
) != 0)
418 *ret
= st
.st_dev
; /* If this is not a device node then use the block device this file is stored on */
420 /* If this is btrfs, getting the backing block device is a bit harder */
421 r
= btrfs_get_block_device(p
, ret
);
422 if (r
< 0 && r
!= -ENOTTY
)
423 return log_warning_errno(r
, "Failed to determine block device backing btrfs file system '%s': %m", p
);
425 log_warning("'%s' is not a block device node, and file system block device cannot be determined or is not local.", p
);
430 /* If this is a LUKS device, try to get the originating block device */
431 (void) block_get_originating(*ret
, ret
);
433 /* If this is a partition, try to get the originating block device */
434 (void) block_get_whole_disk(*ret
, ret
);
438 static int whitelist_device(BPFProgram
*prog
, const char *path
, const char *node
, const char *acc
) {
445 /* Some special handling for /dev/block/%u:%u, /dev/char/%u:%u, /run/systemd/inaccessible/chr and
446 * /run/systemd/inaccessible/blk paths. Instead of stat()ing these we parse out the major/minor directly. This
447 * means clients can use these path without the device node actually around */
448 r
= device_path_parse_major_minor(node
, &st
.st_mode
, &st
.st_rdev
);
451 return log_warning_errno(r
, "Couldn't parse major/minor from device path '%s': %m", node
);
453 if (stat(node
, &st
) < 0)
454 return log_warning_errno(errno
, "Couldn't stat device %s: %m", node
);
456 if (!S_ISCHR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
457 log_warning("%s is not a device.", node
);
462 if (cg_all_unified() > 0) {
466 return cgroup_bpf_whitelist_device(prog
, S_ISCHR(st
.st_mode
) ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
,
467 major(st
.st_rdev
), minor(st
.st_rdev
), acc
);
470 char buf
[2+DECIMAL_STR_MAX(dev_t
)*2+2+4];
474 S_ISCHR(st
.st_mode
) ? 'c' : 'b',
475 major(st
.st_rdev
), minor(st
.st_rdev
),
478 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore EINVAL here. */
480 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
482 return log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
, -EPERM
) ? LOG_DEBUG
: LOG_WARNING
,
483 r
, "Failed to set devices.allow on %s: %m", path
);
489 static int whitelist_major(BPFProgram
*prog
, const char *path
, const char *name
, char type
, const char *acc
) {
490 _cleanup_fclose_
FILE *f
= NULL
;
491 char buf
[2+DECIMAL_STR_MAX(unsigned)+3+4];
498 assert(IN_SET(type
, 'b', 'c'));
500 if (streq(name
, "*")) {
501 /* If the name is a wildcard, then apply this list to all devices of this type */
503 if (cg_all_unified() > 0) {
507 (void) cgroup_bpf_whitelist_class(prog
, type
== 'c' ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
, acc
);
509 xsprintf(buf
, "%c *:* %s", type
, acc
);
511 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
513 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
514 "Failed to set devices.allow on %s: %m", path
);
519 if (safe_atou(name
, &maj
) >= 0 && DEVICE_MAJOR_VALID(maj
)) {
520 /* The name is numeric and suitable as major. In that case, let's take is major, and create the entry
523 if (cg_all_unified() > 0) {
527 (void) cgroup_bpf_whitelist_major(prog
,
528 type
== 'c' ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
,
531 xsprintf(buf
, "%c %u:* %s", type
, maj
, acc
);
533 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
535 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
536 "Failed to set devices.allow on %s: %m", path
);
542 f
= fopen("/proc/devices", "re");
544 return log_warning_errno(errno
, "Cannot open /proc/devices to resolve %s (%c): %m", name
, type
);
547 _cleanup_free_
char *line
= NULL
;
550 r
= read_line(f
, LONG_LINE_MAX
, &line
);
552 return log_warning_errno(r
, "Failed to read /proc/devices: %m");
556 if (type
== 'c' && streq(line
, "Character devices:")) {
561 if (type
== 'b' && streq(line
, "Block devices:")) {
576 w
= strpbrk(p
, WHITESPACE
);
581 r
= safe_atou(p
, &maj
);
588 w
+= strspn(w
, WHITESPACE
);
590 if (fnmatch(name
, w
, 0) != 0)
593 if (cg_all_unified() > 0) {
597 (void) cgroup_bpf_whitelist_major(prog
,
598 type
== 'c' ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
,
607 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore EINVAL
610 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
612 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
, -EPERM
) ? LOG_DEBUG
: LOG_WARNING
,
613 r
, "Failed to set devices.allow on %s: %m", path
);
620 static bool cgroup_context_has_cpu_weight(CGroupContext
*c
) {
621 return c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
||
622 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
;
625 static bool cgroup_context_has_cpu_shares(CGroupContext
*c
) {
626 return c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
627 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
;
630 static uint64_t cgroup_context_cpu_weight(CGroupContext
*c
, ManagerState state
) {
631 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
632 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
)
633 return c
->startup_cpu_weight
;
634 else if (c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
)
635 return c
->cpu_weight
;
637 return CGROUP_WEIGHT_DEFAULT
;
640 static uint64_t cgroup_context_cpu_shares(CGroupContext
*c
, ManagerState state
) {
641 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
642 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
643 return c
->startup_cpu_shares
;
644 else if (c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
645 return c
->cpu_shares
;
647 return CGROUP_CPU_SHARES_DEFAULT
;
650 static void cgroup_apply_unified_cpu_weight(Unit
*u
, uint64_t weight
) {
651 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
653 xsprintf(buf
, "%" PRIu64
"\n", weight
);
654 (void) set_attribute_and_warn(u
, "cpu", "cpu.weight", buf
);
657 static void cgroup_apply_unified_cpu_quota(Unit
*u
, usec_t quota
) {
658 char buf
[(DECIMAL_STR_MAX(usec_t
) + 1) * 2 + 1];
660 if (quota
!= USEC_INFINITY
)
661 xsprintf(buf
, USEC_FMT
" " USEC_FMT
"\n",
662 quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
, CGROUP_CPU_QUOTA_PERIOD_USEC
);
664 xsprintf(buf
, "max " USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
665 (void) set_attribute_and_warn(u
, "cpu", "cpu.max", buf
);
668 static void cgroup_apply_legacy_cpu_shares(Unit
*u
, uint64_t shares
) {
669 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
671 xsprintf(buf
, "%" PRIu64
"\n", shares
);
672 (void) set_attribute_and_warn(u
, "cpu", "cpu.shares", buf
);
675 static void cgroup_apply_legacy_cpu_quota(Unit
*u
, usec_t quota
) {
676 char buf
[DECIMAL_STR_MAX(usec_t
) + 2];
678 xsprintf(buf
, USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
679 (void) set_attribute_and_warn(u
, "cpu", "cpu.cfs_period_us", buf
);
681 if (quota
!= USEC_INFINITY
) {
682 xsprintf(buf
, USEC_FMT
"\n", quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
);
683 (void) set_attribute_and_warn(u
, "cpu", "cpu.cfs_quota_us", buf
);
685 (void) set_attribute_and_warn(u
, "cpu", "cpu.cfs_quota_us", "-1\n");
688 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares
) {
689 return CLAMP(shares
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_CPU_SHARES_DEFAULT
,
690 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
693 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight
) {
694 return CLAMP(weight
* CGROUP_CPU_SHARES_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
695 CGROUP_CPU_SHARES_MIN
, CGROUP_CPU_SHARES_MAX
);
698 static bool cgroup_context_has_io_config(CGroupContext
*c
) {
699 return c
->io_accounting
||
700 c
->io_weight
!= CGROUP_WEIGHT_INVALID
||
701 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
702 c
->io_device_weights
||
703 c
->io_device_latencies
||
707 static bool cgroup_context_has_blockio_config(CGroupContext
*c
) {
708 return c
->blockio_accounting
||
709 c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
710 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
711 c
->blockio_device_weights
||
712 c
->blockio_device_bandwidths
;
715 static uint64_t cgroup_context_io_weight(CGroupContext
*c
, ManagerState state
) {
716 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
717 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
)
718 return c
->startup_io_weight
;
719 else if (c
->io_weight
!= CGROUP_WEIGHT_INVALID
)
722 return CGROUP_WEIGHT_DEFAULT
;
725 static uint64_t cgroup_context_blkio_weight(CGroupContext
*c
, ManagerState state
) {
726 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
727 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
728 return c
->startup_blockio_weight
;
729 else if (c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
730 return c
->blockio_weight
;
732 return CGROUP_BLKIO_WEIGHT_DEFAULT
;
735 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight
) {
736 return CLAMP(blkio_weight
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_BLKIO_WEIGHT_DEFAULT
,
737 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
740 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight
) {
741 return CLAMP(io_weight
* CGROUP_BLKIO_WEIGHT_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
742 CGROUP_BLKIO_WEIGHT_MIN
, CGROUP_BLKIO_WEIGHT_MAX
);
745 static void cgroup_apply_io_device_weight(Unit
*u
, const char *dev_path
, uint64_t io_weight
) {
746 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
750 r
= lookup_block_device(dev_path
, &dev
);
754 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), io_weight
);
755 (void) set_attribute_and_warn(u
, "io", "io.weight", buf
);
758 static void cgroup_apply_blkio_device_weight(Unit
*u
, const char *dev_path
, uint64_t blkio_weight
) {
759 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
763 r
= lookup_block_device(dev_path
, &dev
);
767 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), blkio_weight
);
768 (void) set_attribute_and_warn(u
, "blkio", "blkio.weight_device", buf
);
771 static void cgroup_apply_io_device_latency(Unit
*u
, const char *dev_path
, usec_t target
) {
772 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+7+DECIMAL_STR_MAX(uint64_t)+1];
776 r
= lookup_block_device(dev_path
, &dev
);
780 if (target
!= USEC_INFINITY
)
781 xsprintf(buf
, "%u:%u target=%" PRIu64
"\n", major(dev
), minor(dev
), target
);
783 xsprintf(buf
, "%u:%u target=max\n", major(dev
), minor(dev
));
785 (void) set_attribute_and_warn(u
, "io", "io.latency", buf
);
788 static void cgroup_apply_io_device_limit(Unit
*u
, const char *dev_path
, uint64_t *limits
) {
789 char limit_bufs
[_CGROUP_IO_LIMIT_TYPE_MAX
][DECIMAL_STR_MAX(uint64_t)];
790 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
791 CGroupIOLimitType type
;
795 r
= lookup_block_device(dev_path
, &dev
);
799 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
800 if (limits
[type
] != cgroup_io_limit_defaults
[type
])
801 xsprintf(limit_bufs
[type
], "%" PRIu64
, limits
[type
]);
803 xsprintf(limit_bufs
[type
], "%s", limits
[type
] == CGROUP_LIMIT_MAX
? "max" : "0");
805 xsprintf(buf
, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev
), minor(dev
),
806 limit_bufs
[CGROUP_IO_RBPS_MAX
], limit_bufs
[CGROUP_IO_WBPS_MAX
],
807 limit_bufs
[CGROUP_IO_RIOPS_MAX
], limit_bufs
[CGROUP_IO_WIOPS_MAX
]);
808 (void) set_attribute_and_warn(u
, "io", "io.max", buf
);
811 static void cgroup_apply_blkio_device_limit(Unit
*u
, const char *dev_path
, uint64_t rbps
, uint64_t wbps
) {
812 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
816 r
= lookup_block_device(dev_path
, &dev
);
820 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), rbps
);
821 (void) set_attribute_and_warn(u
, "blkio", "blkio.throttle.read_bps_device", buf
);
823 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), wbps
);
824 (void) set_attribute_and_warn(u
, "blkio", "blkio.throttle.write_bps_device", buf
);
827 static bool cgroup_context_has_unified_memory_config(CGroupContext
*c
) {
828 return c
->memory_min
> 0 || c
->memory_low
> 0 || c
->memory_high
!= CGROUP_LIMIT_MAX
|| c
->memory_max
!= CGROUP_LIMIT_MAX
|| c
->memory_swap_max
!= CGROUP_LIMIT_MAX
;
831 static void cgroup_apply_unified_memory_limit(Unit
*u
, const char *file
, uint64_t v
) {
832 char buf
[DECIMAL_STR_MAX(uint64_t) + 1] = "max\n";
834 if (v
!= CGROUP_LIMIT_MAX
)
835 xsprintf(buf
, "%" PRIu64
"\n", v
);
837 (void) set_attribute_and_warn(u
, "memory", file
, buf
);
840 static void cgroup_apply_firewall(Unit
*u
) {
843 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
845 if (bpf_firewall_compile(u
) < 0)
848 (void) bpf_firewall_install(u
);
851 static void cgroup_context_apply(
853 CGroupMask apply_mask
,
854 ManagerState state
) {
858 bool is_host_root
, is_local_root
;
863 /* Nothing to do? Exit early! */
867 /* Some cgroup attributes are not supported on the host root cgroup, hence silently ignore them here. And other
868 * attributes should only be managed for cgroups further down the tree. */
869 is_local_root
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
870 is_host_root
= unit_has_host_root_cgroup(u
);
872 assert_se(c
= unit_get_cgroup_context(u
));
873 assert_se(path
= u
->cgroup_path
);
875 if (is_local_root
) /* Make sure we don't try to display messages with an empty path. */
878 /* We generally ignore errors caused by read-only mounted cgroup trees (assuming we are running in a container
879 * then), and missing cgroups, i.e. EROFS and ENOENT. */
881 /* In fully unified mode these attributes don't exist on the host cgroup root. On legacy the weights exist, but
882 * setting the weight makes very little sense on the host root cgroup, as there are no other cgroups at this
883 * level. The quota exists there too, but any attempt to write to it is refused with EINVAL. Inside of
884 * containers we want to leave control of these to the container manager (and if cgroupsv2 delegation is used
885 * we couldn't even write to them if we wanted to). */
886 if ((apply_mask
& CGROUP_MASK_CPU
) && !is_local_root
) {
888 if (cg_all_unified() > 0) {
891 if (cgroup_context_has_cpu_weight(c
))
892 weight
= cgroup_context_cpu_weight(c
, state
);
893 else if (cgroup_context_has_cpu_shares(c
)) {
896 shares
= cgroup_context_cpu_shares(c
, state
);
897 weight
= cgroup_cpu_shares_to_weight(shares
);
899 log_cgroup_compat(u
, "Applying [Startup]CPUShares=%" PRIu64
" as [Startup]CPUWeight=%" PRIu64
" on %s",
900 shares
, weight
, path
);
902 weight
= CGROUP_WEIGHT_DEFAULT
;
904 cgroup_apply_unified_cpu_weight(u
, weight
);
905 cgroup_apply_unified_cpu_quota(u
, c
->cpu_quota_per_sec_usec
);
910 if (cgroup_context_has_cpu_weight(c
)) {
913 weight
= cgroup_context_cpu_weight(c
, state
);
914 shares
= cgroup_cpu_weight_to_shares(weight
);
916 log_cgroup_compat(u
, "Applying [Startup]CPUWeight=%" PRIu64
" as [Startup]CPUShares=%" PRIu64
" on %s",
917 weight
, shares
, path
);
918 } else if (cgroup_context_has_cpu_shares(c
))
919 shares
= cgroup_context_cpu_shares(c
, state
);
921 shares
= CGROUP_CPU_SHARES_DEFAULT
;
923 cgroup_apply_legacy_cpu_shares(u
, shares
);
924 cgroup_apply_legacy_cpu_quota(u
, c
->cpu_quota_per_sec_usec
);
928 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroupsv2
929 * controller), and in case of containers we want to leave control of these attributes to the container manager
930 * (and we couldn't access that stuff anyway, even if we tried if proper delegation is used). */
931 if ((apply_mask
& CGROUP_MASK_IO
) && !is_local_root
) {
932 char buf
[8+DECIMAL_STR_MAX(uint64_t)+1];
933 bool has_io
, has_blockio
;
936 has_io
= cgroup_context_has_io_config(c
);
937 has_blockio
= cgroup_context_has_blockio_config(c
);
940 weight
= cgroup_context_io_weight(c
, state
);
941 else if (has_blockio
) {
942 uint64_t blkio_weight
;
944 blkio_weight
= cgroup_context_blkio_weight(c
, state
);
945 weight
= cgroup_weight_blkio_to_io(blkio_weight
);
947 log_cgroup_compat(u
, "Applying [Startup]BlockIOWeight=%" PRIu64
" as [Startup]IOWeight=%" PRIu64
,
948 blkio_weight
, weight
);
950 weight
= CGROUP_WEIGHT_DEFAULT
;
952 xsprintf(buf
, "default %" PRIu64
"\n", weight
);
953 (void) set_attribute_and_warn(u
, "io", "io.weight", buf
);
956 CGroupIODeviceLatency
*latency
;
957 CGroupIODeviceLimit
*limit
;
958 CGroupIODeviceWeight
*w
;
960 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
)
961 cgroup_apply_io_device_weight(u
, w
->path
, w
->weight
);
963 LIST_FOREACH(device_limits
, limit
, c
->io_device_limits
)
964 cgroup_apply_io_device_limit(u
, limit
->path
, limit
->limits
);
966 LIST_FOREACH(device_latencies
, latency
, c
->io_device_latencies
)
967 cgroup_apply_io_device_latency(u
, latency
->path
, latency
->target_usec
);
969 } else if (has_blockio
) {
970 CGroupBlockIODeviceWeight
*w
;
971 CGroupBlockIODeviceBandwidth
*b
;
973 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
) {
974 weight
= cgroup_weight_blkio_to_io(w
->weight
);
976 log_cgroup_compat(u
, "Applying BlockIODeviceWeight=%" PRIu64
" as IODeviceWeight=%" PRIu64
" for %s",
977 w
->weight
, weight
, w
->path
);
979 cgroup_apply_io_device_weight(u
, w
->path
, weight
);
982 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
983 uint64_t limits
[_CGROUP_IO_LIMIT_TYPE_MAX
];
984 CGroupIOLimitType type
;
986 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
987 limits
[type
] = cgroup_io_limit_defaults
[type
];
989 limits
[CGROUP_IO_RBPS_MAX
] = b
->rbps
;
990 limits
[CGROUP_IO_WBPS_MAX
] = b
->wbps
;
992 log_cgroup_compat(u
, "Applying BlockIO{Read|Write}Bandwidth=%" PRIu64
" %" PRIu64
" as IO{Read|Write}BandwidthMax= for %s",
993 b
->rbps
, b
->wbps
, b
->path
);
995 cgroup_apply_io_device_limit(u
, b
->path
, limits
);
1000 if (apply_mask
& CGROUP_MASK_BLKIO
) {
1001 bool has_io
, has_blockio
;
1003 has_io
= cgroup_context_has_io_config(c
);
1004 has_blockio
= cgroup_context_has_blockio_config(c
);
1006 /* Applying a 'weight' never makes sense for the host root cgroup, and for containers this should be
1007 * left to our container manager, too. */
1008 if (!is_local_root
) {
1009 char buf
[DECIMAL_STR_MAX(uint64_t)+1];
1015 io_weight
= cgroup_context_io_weight(c
, state
);
1016 weight
= cgroup_weight_io_to_blkio(cgroup_context_io_weight(c
, state
));
1018 log_cgroup_compat(u
, "Applying [Startup]IOWeight=%" PRIu64
" as [Startup]BlockIOWeight=%" PRIu64
,
1020 } else if (has_blockio
)
1021 weight
= cgroup_context_blkio_weight(c
, state
);
1023 weight
= CGROUP_BLKIO_WEIGHT_DEFAULT
;
1025 xsprintf(buf
, "%" PRIu64
"\n", weight
);
1026 (void) set_attribute_and_warn(u
, "blkio", "blkio.weight", buf
);
1029 CGroupIODeviceWeight
*w
;
1031 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
) {
1032 weight
= cgroup_weight_io_to_blkio(w
->weight
);
1034 log_cgroup_compat(u
, "Applying IODeviceWeight=%" PRIu64
" as BlockIODeviceWeight=%" PRIu64
" for %s",
1035 w
->weight
, weight
, w
->path
);
1037 cgroup_apply_blkio_device_weight(u
, w
->path
, weight
);
1039 } else if (has_blockio
) {
1040 CGroupBlockIODeviceWeight
*w
;
1042 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
1043 cgroup_apply_blkio_device_weight(u
, w
->path
, w
->weight
);
1047 /* The bandwith limits are something that make sense to be applied to the host's root but not container
1048 * roots, as there we want the container manager to handle it */
1049 if (is_host_root
|| !is_local_root
) {
1051 CGroupIODeviceLimit
*l
;
1053 LIST_FOREACH(device_limits
, l
, c
->io_device_limits
) {
1054 log_cgroup_compat(u
, "Applying IO{Read|Write}Bandwidth=%" PRIu64
" %" PRIu64
" as BlockIO{Read|Write}BandwidthMax= for %s",
1055 l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
], l
->path
);
1057 cgroup_apply_blkio_device_limit(u
, l
->path
, l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
]);
1059 } else if (has_blockio
) {
1060 CGroupBlockIODeviceBandwidth
*b
;
1062 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
)
1063 cgroup_apply_blkio_device_limit(u
, b
->path
, b
->rbps
, b
->wbps
);
1068 /* In unified mode 'memory' attributes do not exist on the root cgroup. In legacy mode 'memory.limit_in_bytes'
1069 * exists on the root cgroup, but any writes to it are refused with EINVAL. And if we run in a container we
1070 * want to leave control to the container manager (and if proper cgroupsv2 delegation is used we couldn't even
1071 * write to this if we wanted to.) */
1072 if ((apply_mask
& CGROUP_MASK_MEMORY
) && !is_local_root
) {
1074 if (cg_all_unified() > 0) {
1075 uint64_t max
, swap_max
= CGROUP_LIMIT_MAX
;
1077 if (cgroup_context_has_unified_memory_config(c
)) {
1078 max
= c
->memory_max
;
1079 swap_max
= c
->memory_swap_max
;
1081 max
= c
->memory_limit
;
1083 if (max
!= CGROUP_LIMIT_MAX
)
1084 log_cgroup_compat(u
, "Applying MemoryLimit=%" PRIu64
" as MemoryMax=", max
);
1087 cgroup_apply_unified_memory_limit(u
, "memory.min", c
->memory_min
);
1088 cgroup_apply_unified_memory_limit(u
, "memory.low", c
->memory_low
);
1089 cgroup_apply_unified_memory_limit(u
, "memory.high", c
->memory_high
);
1090 cgroup_apply_unified_memory_limit(u
, "memory.max", max
);
1091 cgroup_apply_unified_memory_limit(u
, "memory.swap.max", swap_max
);
1094 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
1097 if (cgroup_context_has_unified_memory_config(c
)) {
1098 val
= c
->memory_max
;
1099 log_cgroup_compat(u
, "Applying MemoryMax=%" PRIi64
" as MemoryLimit=", val
);
1101 val
= c
->memory_limit
;
1103 if (val
== CGROUP_LIMIT_MAX
)
1104 strncpy(buf
, "-1\n", sizeof(buf
));
1106 xsprintf(buf
, "%" PRIu64
"\n", val
);
1108 (void) set_attribute_and_warn(u
, "memory", "memory.limit_in_bytes", buf
);
1112 /* On cgroupsv2 we can apply BPF everywhere. On cgroupsv1 we apply it everywhere except for the root of
1113 * containers, where we leave this to the manager */
1114 if ((apply_mask
& (CGROUP_MASK_DEVICES
| CGROUP_MASK_BPF_DEVICES
)) &&
1115 (is_host_root
|| cg_all_unified() > 0 || !is_local_root
)) {
1116 _cleanup_(bpf_program_unrefp
) BPFProgram
*prog
= NULL
;
1117 CGroupDeviceAllow
*a
;
1119 if (cg_all_unified() > 0) {
1120 r
= cgroup_init_device_bpf(&prog
, c
->device_policy
, c
->device_allow
);
1122 log_unit_warning_errno(u
, r
, "Failed to initialize device control bpf program: %m");
1124 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore EINVAL
1127 if (c
->device_allow
|| c
->device_policy
!= CGROUP_AUTO
)
1128 r
= cg_set_attribute("devices", path
, "devices.deny", "a");
1130 r
= cg_set_attribute("devices", path
, "devices.allow", "a");
1132 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
, -EPERM
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1133 "Failed to reset devices.allow/devices.deny: %m");
1136 if (c
->device_policy
== CGROUP_CLOSED
||
1137 (c
->device_policy
== CGROUP_AUTO
&& c
->device_allow
)) {
1138 static const char auto_devices
[] =
1139 "/dev/null\0" "rwm\0"
1140 "/dev/zero\0" "rwm\0"
1141 "/dev/full\0" "rwm\0"
1142 "/dev/random\0" "rwm\0"
1143 "/dev/urandom\0" "rwm\0"
1144 "/dev/tty\0" "rwm\0"
1145 "/dev/ptmx\0" "rwm\0"
1146 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
1147 "/run/systemd/inaccessible/chr\0" "rwm\0"
1148 "/run/systemd/inaccessible/blk\0" "rwm\0";
1152 NULSTR_FOREACH_PAIR(x
, y
, auto_devices
)
1153 (void) whitelist_device(prog
, path
, x
, y
);
1155 /* PTS (/dev/pts) devices may not be duplicated, but accessed */
1156 (void) whitelist_major(prog
, path
, "pts", 'c', "rw");
1159 LIST_FOREACH(device_allow
, a
, c
->device_allow
) {
1175 if (path_startswith(a
->path
, "/dev/"))
1176 (void) whitelist_device(prog
, path
, a
->path
, acc
);
1177 else if ((val
= startswith(a
->path
, "block-")))
1178 (void) whitelist_major(prog
, path
, val
, 'b', acc
);
1179 else if ((val
= startswith(a
->path
, "char-")))
1180 (void) whitelist_major(prog
, path
, val
, 'c', acc
);
1182 log_unit_debug(u
, "Ignoring device '%s' while writing cgroup attribute.", a
->path
);
1185 r
= cgroup_apply_device_bpf(u
, prog
, c
->device_policy
, c
->device_allow
);
1187 static bool warned
= false;
1189 log_full_errno(warned
? LOG_DEBUG
: LOG_WARNING
, r
,
1190 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1191 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1192 "(This warning is only shown for the first loaded unit using device ACL.)", u
->id
);
1198 if (apply_mask
& CGROUP_MASK_PIDS
) {
1201 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1202 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1203 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1204 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1205 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1206 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1207 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1208 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1209 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1210 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1211 * which is desirable so that there's an offical way to release control of the sysctl from
1212 * systemd: set the limit to unbounded and reload. */
1214 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1215 u
->manager
->sysctl_pid_max_changed
= true;
1216 r
= procfs_tasks_set_limit(c
->tasks_max
);
1217 } else if (u
->manager
->sysctl_pid_max_changed
)
1218 r
= procfs_tasks_set_limit(TASKS_MAX
);
1222 log_unit_full(u
, LOG_LEVEL_CGROUP_WRITE(r
), r
,
1223 "Failed to write to tasks limit sysctls: %m");
1226 /* The attribute itself is not available on the host root cgroup, and in the container case we want to
1227 * leave it for the container manager. */
1228 if (!is_local_root
) {
1229 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1230 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
1232 sprintf(buf
, "%" PRIu64
"\n", c
->tasks_max
);
1233 (void) set_attribute_and_warn(u
, "pids", "pids.max", buf
);
1235 (void) set_attribute_and_warn(u
, "pids", "pids.max", "max\n");
1239 if (apply_mask
& CGROUP_MASK_BPF_FIREWALL
)
1240 cgroup_apply_firewall(u
);
1243 static bool unit_get_needs_bpf_firewall(Unit
*u
) {
1248 c
= unit_get_cgroup_context(u
);
1252 if (c
->ip_accounting
||
1253 c
->ip_address_allow
||
1257 /* If any parent slice has an IP access list defined, it applies too */
1258 for (p
= UNIT_DEREF(u
->slice
); p
; p
= UNIT_DEREF(p
->slice
)) {
1259 c
= unit_get_cgroup_context(p
);
1263 if (c
->ip_address_allow
||
1271 static CGroupMask
cgroup_context_get_mask(CGroupContext
*c
) {
1272 CGroupMask mask
= 0;
1274 /* Figure out which controllers we need, based on the cgroup context object */
1276 if (c
->cpu_accounting
)
1277 mask
|= get_cpu_accounting_mask();
1279 if (cgroup_context_has_cpu_weight(c
) ||
1280 cgroup_context_has_cpu_shares(c
) ||
1281 c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
)
1282 mask
|= CGROUP_MASK_CPU
;
1284 if (cgroup_context_has_io_config(c
) || cgroup_context_has_blockio_config(c
))
1285 mask
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
1287 if (c
->memory_accounting
||
1288 c
->memory_limit
!= CGROUP_LIMIT_MAX
||
1289 cgroup_context_has_unified_memory_config(c
))
1290 mask
|= CGROUP_MASK_MEMORY
;
1292 if (c
->device_allow
||
1293 c
->device_policy
!= CGROUP_AUTO
)
1294 mask
|= CGROUP_MASK_DEVICES
| CGROUP_MASK_BPF_DEVICES
;
1296 if (c
->tasks_accounting
||
1297 c
->tasks_max
!= CGROUP_LIMIT_MAX
)
1298 mask
|= CGROUP_MASK_PIDS
;
1300 return CGROUP_MASK_EXTEND_JOINED(mask
);
1303 static CGroupMask
unit_get_bpf_mask(Unit
*u
) {
1304 CGroupMask mask
= 0;
1306 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
1309 if (unit_get_needs_bpf_firewall(u
))
1310 mask
|= CGROUP_MASK_BPF_FIREWALL
;
1315 CGroupMask
unit_get_own_mask(Unit
*u
) {
1318 /* Returns the mask of controllers the unit needs for itself. If a unit is not properly loaded, return an empty
1319 * mask, as we shouldn't reflect it in the cgroup hierarchy then. */
1321 if (u
->load_state
!= UNIT_LOADED
)
1324 c
= unit_get_cgroup_context(u
);
1328 return (cgroup_context_get_mask(c
) | unit_get_bpf_mask(u
) | unit_get_delegate_mask(u
)) & ~unit_get_ancestor_disable_mask(u
);
1331 CGroupMask
unit_get_delegate_mask(Unit
*u
) {
1334 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1335 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
1337 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1339 if (!unit_cgroup_delegate(u
))
1342 if (cg_all_unified() <= 0) {
1345 e
= unit_get_exec_context(u
);
1346 if (e
&& !exec_context_maintains_privileges(e
))
1350 assert_se(c
= unit_get_cgroup_context(u
));
1351 return CGROUP_MASK_EXTEND_JOINED(c
->delegate_controllers
);
1354 CGroupMask
unit_get_members_mask(Unit
*u
) {
1357 /* Returns the mask of controllers all of the unit's children require, merged */
1359 if (u
->cgroup_members_mask_valid
)
1360 return u
->cgroup_members_mask
; /* Use cached value if possible */
1362 u
->cgroup_members_mask
= 0;
1364 if (u
->type
== UNIT_SLICE
) {
1369 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
1370 if (UNIT_DEREF(member
->slice
) == u
)
1371 u
->cgroup_members_mask
|= unit_get_subtree_mask(member
); /* note that this calls ourselves again, for the children */
1375 u
->cgroup_members_mask_valid
= true;
1376 return u
->cgroup_members_mask
;
1379 CGroupMask
unit_get_siblings_mask(Unit
*u
) {
1382 /* Returns the mask of controllers all of the unit's siblings
1383 * require, i.e. the members mask of the unit's parent slice
1384 * if there is one. */
1386 if (UNIT_ISSET(u
->slice
))
1387 return unit_get_members_mask(UNIT_DEREF(u
->slice
));
1389 return unit_get_subtree_mask(u
); /* we are the top-level slice */
1392 CGroupMask
unit_get_disable_mask(Unit
*u
) {
1395 c
= unit_get_cgroup_context(u
);
1399 return c
->disable_controllers
;
1402 CGroupMask
unit_get_ancestor_disable_mask(Unit
*u
) {
1406 mask
= unit_get_disable_mask(u
);
1408 /* Returns the mask of controllers which are marked as forcibly
1409 * disabled in any ancestor unit or the unit in question. */
1411 if (UNIT_ISSET(u
->slice
))
1412 mask
|= unit_get_ancestor_disable_mask(UNIT_DEREF(u
->slice
));
1417 CGroupMask
unit_get_subtree_mask(Unit
*u
) {
1419 /* Returns the mask of this subtree, meaning of the group
1420 * itself and its children. */
1422 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
1425 CGroupMask
unit_get_target_mask(Unit
*u
) {
1428 /* This returns the cgroup mask of all controllers to enable
1429 * for a specific cgroup, i.e. everything it needs itself,
1430 * plus all that its children need, plus all that its siblings
1431 * need. This is primarily useful on the legacy cgroup
1432 * hierarchy, where we need to duplicate each cgroup in each
1433 * hierarchy that shall be enabled for it. */
1435 mask
= unit_get_own_mask(u
) | unit_get_members_mask(u
) | unit_get_siblings_mask(u
);
1436 mask
&= u
->manager
->cgroup_supported
;
1437 mask
&= ~unit_get_ancestor_disable_mask(u
);
1442 CGroupMask
unit_get_enable_mask(Unit
*u
) {
1445 /* This returns the cgroup mask of all controllers to enable
1446 * for the children of a specific cgroup. This is primarily
1447 * useful for the unified cgroup hierarchy, where each cgroup
1448 * controls which controllers are enabled for its children. */
1450 mask
= unit_get_members_mask(u
);
1451 mask
&= u
->manager
->cgroup_supported
;
1452 mask
&= ~unit_get_ancestor_disable_mask(u
);
1457 void unit_invalidate_cgroup_members_masks(Unit
*u
) {
1460 /* Recurse invalidate the member masks cache all the way up the tree */
1461 u
->cgroup_members_mask_valid
= false;
1463 if (UNIT_ISSET(u
->slice
))
1464 unit_invalidate_cgroup_members_masks(UNIT_DEREF(u
->slice
));
1467 const char *unit_get_realized_cgroup_path(Unit
*u
, CGroupMask mask
) {
1469 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
1473 if (u
->cgroup_path
&&
1474 u
->cgroup_realized
&&
1475 FLAGS_SET(u
->cgroup_realized_mask
, mask
))
1476 return u
->cgroup_path
;
1478 u
= UNIT_DEREF(u
->slice
);
1484 static const char *migrate_callback(CGroupMask mask
, void *userdata
) {
1485 return unit_get_realized_cgroup_path(userdata
, mask
);
1488 char *unit_default_cgroup_path(const Unit
*u
) {
1489 _cleanup_free_
char *escaped
= NULL
, *slice
= NULL
;
1494 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1495 return strdup(u
->manager
->cgroup_root
);
1497 if (UNIT_ISSET(u
->slice
) && !unit_has_name(UNIT_DEREF(u
->slice
), SPECIAL_ROOT_SLICE
)) {
1498 r
= cg_slice_to_path(UNIT_DEREF(u
->slice
)->id
, &slice
);
1503 escaped
= cg_escape(u
->id
);
1508 return strjoin(u
->manager
->cgroup_root
, "/", slice
, "/",
1511 return strjoin(u
->manager
->cgroup_root
, "/", escaped
);
1514 int unit_set_cgroup_path(Unit
*u
, const char *path
) {
1515 _cleanup_free_
char *p
= NULL
;
1527 if (streq_ptr(u
->cgroup_path
, p
))
1531 r
= hashmap_put(u
->manager
->cgroup_unit
, p
, u
);
1536 unit_release_cgroup(u
);
1538 u
->cgroup_path
= TAKE_PTR(p
);
1543 int unit_watch_cgroup(Unit
*u
) {
1544 _cleanup_free_
char *events
= NULL
;
1549 if (!u
->cgroup_path
)
1552 if (u
->cgroup_inotify_wd
>= 0)
1555 /* Only applies to the unified hierarchy */
1556 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
1558 return log_error_errno(r
, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1562 /* Don't watch the root slice, it's pointless. */
1563 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1566 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_inotify_wd_unit
, &trivial_hash_ops
);
1570 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events", &events
);
1574 u
->cgroup_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
1575 if (u
->cgroup_inotify_wd
< 0) {
1577 if (errno
== ENOENT
) /* If the directory is already
1578 * gone we don't need to track
1579 * it, so this is not an error */
1582 return log_unit_error_errno(u
, errno
, "Failed to add inotify watch descriptor for control group %s: %m", u
->cgroup_path
);
1585 r
= hashmap_put(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
), u
);
1587 return log_unit_error_errno(u
, r
, "Failed to add inotify watch descriptor to hash map: %m");
1592 int unit_pick_cgroup_path(Unit
*u
) {
1593 _cleanup_free_
char *path
= NULL
;
1601 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1604 path
= unit_default_cgroup_path(u
);
1608 r
= unit_set_cgroup_path(u
, path
);
1610 return log_unit_error_errno(u
, r
, "Control group %s exists already.", path
);
1612 return log_unit_error_errno(u
, r
, "Failed to set unit's control group path to %s: %m", path
);
1617 static int unit_create_cgroup(
1619 CGroupMask target_mask
,
1620 CGroupMask enable_mask
,
1621 ManagerState state
) {
1628 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1631 /* Figure out our cgroup path */
1632 r
= unit_pick_cgroup_path(u
);
1636 /* First, create our own group */
1637 r
= cg_create_everywhere(u
->manager
->cgroup_supported
, target_mask
, u
->cgroup_path
);
1639 return log_unit_error_errno(u
, r
, "Failed to create cgroup %s: %m", u
->cgroup_path
);
1642 /* Start watching it */
1643 (void) unit_watch_cgroup(u
);
1645 /* Preserve enabled controllers in delegated units, adjust others. */
1646 if (created
|| !u
->cgroup_realized
|| !unit_cgroup_delegate(u
)) {
1647 CGroupMask result_mask
= 0;
1649 /* Enable all controllers we need */
1650 r
= cg_enable_everywhere(u
->manager
->cgroup_supported
, enable_mask
, u
->cgroup_path
, &result_mask
);
1652 log_unit_warning_errno(u
, r
, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", u
->cgroup_path
);
1654 /* If we just turned off a controller, this might release the controller for our parent too, let's
1655 * enqueue the parent for re-realization in that case again. */
1656 if (UNIT_ISSET(u
->slice
)) {
1657 CGroupMask turned_off
;
1659 turned_off
= (u
->cgroup_realized
? u
->cgroup_enabled_mask
& ~result_mask
: 0);
1660 if (turned_off
!= 0) {
1663 /* Force the parent to propagate the enable mask to the kernel again, by invalidating
1664 * the controller we just turned off. */
1666 for (parent
= UNIT_DEREF(u
->slice
); parent
; parent
= UNIT_DEREF(parent
->slice
))
1667 unit_invalidate_cgroup(parent
, turned_off
);
1671 /* Remember what's actually enabled now */
1672 u
->cgroup_enabled_mask
= result_mask
;
1675 /* Keep track that this is now realized */
1676 u
->cgroup_realized
= true;
1677 u
->cgroup_realized_mask
= target_mask
;
1679 if (u
->type
!= UNIT_SLICE
&& !unit_cgroup_delegate(u
)) {
1681 /* Then, possibly move things over, but not if
1682 * subgroups may contain processes, which is the case
1683 * for slice and delegation units. */
1684 r
= cg_migrate_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->cgroup_path
, migrate_callback
, u
);
1686 log_unit_warning_errno(u
, r
, "Failed to migrate cgroup from to %s, ignoring: %m", u
->cgroup_path
);
1689 /* Set attributes */
1690 cgroup_context_apply(u
, target_mask
, state
);
1691 cgroup_xattr_apply(u
);
1696 static int unit_attach_pid_to_cgroup_via_bus(Unit
*u
, pid_t pid
, const char *suffix_path
) {
1697 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1703 if (MANAGER_IS_SYSTEM(u
->manager
))
1706 if (!u
->manager
->system_bus
)
1709 if (!u
->cgroup_path
)
1712 /* Determine this unit's cgroup path relative to our cgroup root */
1713 pp
= path_startswith(u
->cgroup_path
, u
->manager
->cgroup_root
);
1717 pp
= strjoina("/", pp
, suffix_path
);
1718 path_simplify(pp
, false);
1720 r
= sd_bus_call_method(u
->manager
->system_bus
,
1721 "org.freedesktop.systemd1",
1722 "/org/freedesktop/systemd1",
1723 "org.freedesktop.systemd1.Manager",
1724 "AttachProcessesToUnit",
1727 NULL
/* empty unit name means client's unit, i.e. us */, pp
, 1, (uint32_t) pid
);
1729 return log_unit_debug_errno(u
, r
, "Failed to attach unit process " PID_FMT
" via the bus: %s", pid
, bus_error_message(&error
, r
));
1734 int unit_attach_pids_to_cgroup(Unit
*u
, Set
*pids
, const char *suffix_path
) {
1735 CGroupMask delegated_mask
;
1743 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1746 if (set_isempty(pids
))
1749 r
= unit_realize_cgroup(u
);
1753 if (isempty(suffix_path
))
1756 p
= strjoina(u
->cgroup_path
, "/", suffix_path
);
1758 delegated_mask
= unit_get_delegate_mask(u
);
1761 SET_FOREACH(pidp
, pids
, i
) {
1762 pid_t pid
= PTR_TO_PID(pidp
);
1765 /* First, attach the PID to the main cgroup hierarchy */
1766 q
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, p
, pid
);
1768 log_unit_debug_errno(u
, q
, "Couldn't move process " PID_FMT
" to requested cgroup '%s': %m", pid
, p
);
1770 if (MANAGER_IS_USER(u
->manager
) && IN_SET(q
, -EPERM
, -EACCES
)) {
1773 /* If we are in a user instance, and we can't move the process ourselves due to
1774 * permission problems, let's ask the system instance about it instead. Since it's more
1775 * privileged it might be able to move the process across the leaves of a subtree who's
1776 * top node is not owned by us. */
1778 z
= unit_attach_pid_to_cgroup_via_bus(u
, pid
, suffix_path
);
1780 log_unit_debug_errno(u
, z
, "Couldn't move process " PID_FMT
" to requested cgroup '%s' via the system bus either: %m", pid
, p
);
1782 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1786 r
= q
; /* Remember first error */
1791 q
= cg_all_unified();
1797 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
1798 * innermost realized one */
1800 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1801 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1802 const char *realized
;
1804 if (!(u
->manager
->cgroup_supported
& bit
))
1807 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
1808 if (delegated_mask
& u
->cgroup_realized_mask
& bit
) {
1809 q
= cg_attach(cgroup_controller_to_string(c
), p
, pid
);
1811 continue; /* Success! */
1813 log_unit_debug_errno(u
, q
, "Failed to attach PID " PID_FMT
" to requested cgroup %s in controller %s, falling back to unit's cgroup: %m",
1814 pid
, p
, cgroup_controller_to_string(c
));
1817 /* So this controller is either not delegate or realized, or something else weird happened. In
1818 * that case let's attach the PID at least to the closest cgroup up the tree that is
1820 realized
= unit_get_realized_cgroup_path(u
, bit
);
1822 continue; /* Not even realized in the root slice? Then let's not bother */
1824 q
= cg_attach(cgroup_controller_to_string(c
), realized
, pid
);
1826 log_unit_debug_errno(u
, q
, "Failed to attach PID " PID_FMT
" to realized cgroup %s in controller %s, ignoring: %m",
1827 pid
, realized
, cgroup_controller_to_string(c
));
1834 static bool unit_has_mask_realized(
1836 CGroupMask target_mask
,
1837 CGroupMask enable_mask
) {
1841 /* Returns true if this unit is fully realized. We check four things:
1843 * 1. Whether the cgroup was created at all
1844 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroupsv1)
1845 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroupsv2)
1846 * 4. Whether the invalidation mask is currently zero
1848 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
1849 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroupv1 controllers), CGROUP_MASK_V2 (for
1850 * real cgroupv2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
1851 * is only matters for cgroupsv1 controllers, and cgroup_enabled_mask only used for cgroupsv2, and if they
1852 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
1853 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
1854 * simply don't matter. */
1856 return u
->cgroup_realized
&&
1857 ((u
->cgroup_realized_mask
^ target_mask
) & CGROUP_MASK_V1
) == 0 &&
1858 ((u
->cgroup_enabled_mask
^ enable_mask
) & CGROUP_MASK_V2
) == 0 &&
1859 u
->cgroup_invalidated_mask
== 0;
1862 static bool unit_has_mask_disables_realized(
1864 CGroupMask target_mask
,
1865 CGroupMask enable_mask
) {
1869 /* Returns true if all controllers which should be disabled are indeed disabled.
1871 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
1872 * already removed. */
1874 return !u
->cgroup_realized
||
1875 (FLAGS_SET(u
->cgroup_realized_mask
, target_mask
& CGROUP_MASK_V1
) &&
1876 FLAGS_SET(u
->cgroup_enabled_mask
, enable_mask
& CGROUP_MASK_V2
));
1879 static bool unit_has_mask_enables_realized(
1881 CGroupMask target_mask
,
1882 CGroupMask enable_mask
) {
1886 /* Returns true if all controllers which should be enabled are indeed enabled.
1888 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
1889 * we want to add is already added. */
1891 return u
->cgroup_realized
&&
1892 ((u
->cgroup_realized_mask
| target_mask
) & CGROUP_MASK_V1
) == (u
->cgroup_realized_mask
& CGROUP_MASK_V1
) &&
1893 ((u
->cgroup_enabled_mask
| enable_mask
) & CGROUP_MASK_V2
) == (u
->cgroup_enabled_mask
& CGROUP_MASK_V2
);
1896 void unit_add_to_cgroup_realize_queue(Unit
*u
) {
1899 if (u
->in_cgroup_realize_queue
)
1902 LIST_PREPEND(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1903 u
->in_cgroup_realize_queue
= true;
1906 static void unit_remove_from_cgroup_realize_queue(Unit
*u
) {
1909 if (!u
->in_cgroup_realize_queue
)
1912 LIST_REMOVE(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1913 u
->in_cgroup_realize_queue
= false;
1916 /* Controllers can only be enabled breadth-first, from the root of the
1917 * hierarchy downwards to the unit in question. */
1918 static int unit_realize_cgroup_now_enable(Unit
*u
, ManagerState state
) {
1919 CGroupMask target_mask
, enable_mask
, new_target_mask
, new_enable_mask
;
1924 /* First go deal with this unit's parent, or we won't be able to enable
1925 * any new controllers at this layer. */
1926 if (UNIT_ISSET(u
->slice
)) {
1927 r
= unit_realize_cgroup_now_enable(UNIT_DEREF(u
->slice
), state
);
1932 target_mask
= unit_get_target_mask(u
);
1933 enable_mask
= unit_get_enable_mask(u
);
1935 /* We can only enable in this direction, don't try to disable anything.
1937 if (unit_has_mask_enables_realized(u
, target_mask
, enable_mask
))
1940 new_target_mask
= u
->cgroup_realized_mask
| target_mask
;
1941 new_enable_mask
= u
->cgroup_enabled_mask
| enable_mask
;
1943 return unit_create_cgroup(u
, new_target_mask
, new_enable_mask
, state
);
1946 /* Controllers can only be disabled depth-first, from the leaves of the
1947 * hierarchy upwards to the unit in question. */
1948 static int unit_realize_cgroup_now_disable(Unit
*u
, ManagerState state
) {
1955 if (u
->type
!= UNIT_SLICE
)
1958 HASHMAP_FOREACH_KEY(v
, m
, u
->dependencies
[UNIT_BEFORE
], i
) {
1959 CGroupMask target_mask
, enable_mask
, new_target_mask
, new_enable_mask
;
1962 if (UNIT_DEREF(m
->slice
) != u
)
1965 /* The cgroup for this unit might not actually be fully
1966 * realised yet, in which case it isn't holding any controllers
1968 if (!m
->cgroup_path
)
1971 /* We must disable those below us first in order to release the
1973 if (m
->type
== UNIT_SLICE
)
1974 (void) unit_realize_cgroup_now_disable(m
, state
);
1976 target_mask
= unit_get_target_mask(m
);
1977 enable_mask
= unit_get_enable_mask(m
);
1979 /* We can only disable in this direction, don't try to enable
1981 if (unit_has_mask_disables_realized(m
, target_mask
, enable_mask
))
1984 new_target_mask
= m
->cgroup_realized_mask
& target_mask
;
1985 new_enable_mask
= m
->cgroup_enabled_mask
& enable_mask
;
1987 r
= unit_create_cgroup(m
, new_target_mask
, new_enable_mask
, state
);
1995 /* Check if necessary controllers and attributes for a unit are in place.
1997 * - If so, do nothing.
1998 * - If not, create paths, move processes over, and set attributes.
2000 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
2001 * a depth-first way. As such the process looks like this:
2003 * Suppose we have a cgroup hierarchy which looks like this:
2016 * 1. We want to realise cgroup "d" now.
2017 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
2018 * 3. cgroup "k" just started requesting the memory controller.
2020 * To make this work we must do the following in order:
2022 * 1. Disable CPU controller in k, j
2023 * 2. Disable CPU controller in d
2024 * 3. Enable memory controller in root
2025 * 4. Enable memory controller in a
2026 * 5. Enable memory controller in d
2027 * 6. Enable memory controller in k
2029 * Notice that we need to touch j in one direction, but not the other. We also
2030 * don't go beyond d when disabling -- it's up to "a" to get realized if it
2031 * wants to disable further. The basic rules are therefore:
2033 * - If you're disabling something, you need to realise all of the cgroups from
2034 * your recursive descendants to the root. This starts from the leaves.
2035 * - If you're enabling something, you need to realise from the root cgroup
2036 * downwards, but you don't need to iterate your recursive descendants.
2038 * Returns 0 on success and < 0 on failure. */
2039 static int unit_realize_cgroup_now(Unit
*u
, ManagerState state
) {
2040 CGroupMask target_mask
, enable_mask
;
2045 unit_remove_from_cgroup_realize_queue(u
);
2047 target_mask
= unit_get_target_mask(u
);
2048 enable_mask
= unit_get_enable_mask(u
);
2050 if (unit_has_mask_realized(u
, target_mask
, enable_mask
))
2053 /* Disable controllers below us, if there are any */
2054 r
= unit_realize_cgroup_now_disable(u
, state
);
2058 /* Enable controllers above us, if there are any */
2059 if (UNIT_ISSET(u
->slice
)) {
2060 r
= unit_realize_cgroup_now_enable(UNIT_DEREF(u
->slice
), state
);
2065 /* Now actually deal with the cgroup we were trying to realise and set attributes */
2066 r
= unit_create_cgroup(u
, target_mask
, enable_mask
, state
);
2070 /* Now, reset the invalidation mask */
2071 u
->cgroup_invalidated_mask
= 0;
2075 unsigned manager_dispatch_cgroup_realize_queue(Manager
*m
) {
2083 state
= manager_state(m
);
2085 while ((i
= m
->cgroup_realize_queue
)) {
2086 assert(i
->in_cgroup_realize_queue
);
2088 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i
))) {
2089 /* Maybe things changed, and the unit is not actually active anymore? */
2090 unit_remove_from_cgroup_realize_queue(i
);
2094 r
= unit_realize_cgroup_now(i
, state
);
2096 log_warning_errno(r
, "Failed to realize cgroups for queued unit %s, ignoring: %m", i
->id
);
2104 static void unit_add_siblings_to_cgroup_realize_queue(Unit
*u
) {
2107 /* This adds the siblings of the specified unit and the
2108 * siblings of all parent units to the cgroup queue. (But
2109 * neither the specified unit itself nor the parents.) */
2111 while ((slice
= UNIT_DEREF(u
->slice
))) {
2116 HASHMAP_FOREACH_KEY(v
, m
, u
->dependencies
[UNIT_BEFORE
], i
) {
2117 /* Skip units that have a dependency on the slice
2118 * but aren't actually in it. */
2119 if (UNIT_DEREF(m
->slice
) != slice
)
2122 /* No point in doing cgroup application for units
2123 * without active processes. */
2124 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m
)))
2127 /* If the unit doesn't need any new controllers
2128 * and has current ones realized, it doesn't need
2130 if (unit_has_mask_realized(m
,
2131 unit_get_target_mask(m
),
2132 unit_get_enable_mask(m
)))
2135 unit_add_to_cgroup_realize_queue(m
);
2142 int unit_realize_cgroup(Unit
*u
) {
2145 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2148 /* So, here's the deal: when realizing the cgroups for this
2149 * unit, we need to first create all parents, but there's more
2150 * actually: for the weight-based controllers we also need to
2151 * make sure that all our siblings (i.e. units that are in the
2152 * same slice as we are) have cgroups, too. Otherwise, things
2153 * would become very uneven as each of their processes would
2154 * get as much resources as all our group together. This call
2155 * will synchronously create the parent cgroups, but will
2156 * defer work on the siblings to the next event loop
2159 /* Add all sibling slices to the cgroup queue. */
2160 unit_add_siblings_to_cgroup_realize_queue(u
);
2162 /* And realize this one now (and apply the values) */
2163 return unit_realize_cgroup_now(u
, manager_state(u
->manager
));
2166 void unit_release_cgroup(Unit
*u
) {
2169 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
2170 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
2172 if (u
->cgroup_path
) {
2173 (void) hashmap_remove(u
->manager
->cgroup_unit
, u
->cgroup_path
);
2174 u
->cgroup_path
= mfree(u
->cgroup_path
);
2177 if (u
->cgroup_inotify_wd
>= 0) {
2178 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_inotify_wd
) < 0)
2179 log_unit_debug_errno(u
, errno
, "Failed to remove cgroup inotify watch %i for %s, ignoring: %m", u
->cgroup_inotify_wd
, u
->id
);
2181 (void) hashmap_remove(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
));
2182 u
->cgroup_inotify_wd
= -1;
2186 void unit_prune_cgroup(Unit
*u
) {
2192 /* Removes the cgroup, if empty and possible, and stops watching it. */
2194 if (!u
->cgroup_path
)
2197 (void) unit_get_cpu_usage(u
, NULL
); /* Cache the last CPU usage value before we destroy the cgroup */
2199 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
2201 r
= cg_trim_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, !is_root_slice
);
2203 log_unit_debug_errno(u
, r
, "Failed to destroy cgroup %s, ignoring: %m", u
->cgroup_path
);
2210 unit_release_cgroup(u
);
2212 u
->cgroup_realized
= false;
2213 u
->cgroup_realized_mask
= 0;
2214 u
->cgroup_enabled_mask
= 0;
2216 u
->bpf_device_control_installed
= bpf_program_unref(u
->bpf_device_control_installed
);
2219 int unit_search_main_pid(Unit
*u
, pid_t
*ret
) {
2220 _cleanup_fclose_
FILE *f
= NULL
;
2221 pid_t pid
= 0, npid
, mypid
;
2227 if (!u
->cgroup_path
)
2230 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, &f
);
2234 mypid
= getpid_cached();
2235 while (cg_read_pid(f
, &npid
) > 0) {
2241 /* Ignore processes that aren't our kids */
2242 if (get_process_ppid(npid
, &ppid
) >= 0 && ppid
!= mypid
)
2246 /* Dang, there's more than one daemonized PID
2247 in this group, so we don't know what process
2248 is the main process. */
2259 static int unit_watch_pids_in_path(Unit
*u
, const char *path
) {
2260 _cleanup_closedir_
DIR *d
= NULL
;
2261 _cleanup_fclose_
FILE *f
= NULL
;
2267 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
);
2273 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
2274 r
= unit_watch_pid(u
, pid
);
2275 if (r
< 0 && ret
>= 0)
2279 if (r
< 0 && ret
>= 0)
2283 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
2290 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
2291 _cleanup_free_
char *p
= NULL
;
2293 p
= strjoin(path
, "/", fn
);
2299 r
= unit_watch_pids_in_path(u
, p
);
2300 if (r
< 0 && ret
>= 0)
2304 if (r
< 0 && ret
>= 0)
2311 int unit_synthesize_cgroup_empty_event(Unit
*u
) {
2316 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
2317 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
2318 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
2320 if (!u
->cgroup_path
)
2323 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2326 if (r
> 0) /* On unified we have reliable notifications, and don't need this */
2329 if (!set_isempty(u
->pids
))
2332 unit_add_to_cgroup_empty_queue(u
);
2336 int unit_watch_all_pids(Unit
*u
) {
2341 /* Adds all PIDs from our cgroup to the set of PIDs we
2342 * watch. This is a fallback logic for cases where we do not
2343 * get reliable cgroup empty notifications: we try to use
2344 * SIGCHLD as replacement. */
2346 if (!u
->cgroup_path
)
2349 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2352 if (r
> 0) /* On unified we can use proper notifications */
2355 return unit_watch_pids_in_path(u
, u
->cgroup_path
);
2358 static int on_cgroup_empty_event(sd_event_source
*s
, void *userdata
) {
2359 Manager
*m
= userdata
;
2366 u
= m
->cgroup_empty_queue
;
2370 assert(u
->in_cgroup_empty_queue
);
2371 u
->in_cgroup_empty_queue
= false;
2372 LIST_REMOVE(cgroup_empty_queue
, m
->cgroup_empty_queue
, u
);
2374 if (m
->cgroup_empty_queue
) {
2375 /* More stuff queued, let's make sure we remain enabled */
2376 r
= sd_event_source_set_enabled(s
, SD_EVENT_ONESHOT
);
2378 log_debug_errno(r
, "Failed to reenable cgroup empty event source, ignoring: %m");
2381 unit_add_to_gc_queue(u
);
2383 if (UNIT_VTABLE(u
)->notify_cgroup_empty
)
2384 UNIT_VTABLE(u
)->notify_cgroup_empty(u
);
2389 void unit_add_to_cgroup_empty_queue(Unit
*u
) {
2394 /* Note that there are four different ways how cgroup empty events reach us:
2396 * 1. On the unified hierarchy we get an inotify event on the cgroup
2398 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2400 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2402 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2403 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2405 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2406 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2407 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2408 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2409 * case for scope units). */
2411 if (u
->in_cgroup_empty_queue
)
2414 /* Let's verify that the cgroup is really empty */
2415 if (!u
->cgroup_path
)
2417 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
2419 log_unit_debug_errno(u
, r
, "Failed to determine whether cgroup %s is empty: %m", u
->cgroup_path
);
2425 LIST_PREPEND(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
2426 u
->in_cgroup_empty_queue
= true;
2428 /* Trigger the defer event */
2429 r
= sd_event_source_set_enabled(u
->manager
->cgroup_empty_event_source
, SD_EVENT_ONESHOT
);
2431 log_debug_errno(r
, "Failed to enable cgroup empty event source: %m");
2434 static int on_cgroup_inotify_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
2435 Manager
*m
= userdata
;
2442 union inotify_event_buffer buffer
;
2443 struct inotify_event
*e
;
2446 l
= read(fd
, &buffer
, sizeof(buffer
));
2448 if (IN_SET(errno
, EINTR
, EAGAIN
))
2451 return log_error_errno(errno
, "Failed to read control group inotify events: %m");
2454 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
2458 /* Queue overflow has no watch descriptor */
2461 if (e
->mask
& IN_IGNORED
)
2462 /* The watch was just removed */
2465 u
= hashmap_get(m
->cgroup_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
2466 if (!u
) /* Not that inotify might deliver
2467 * events for a watch even after it
2468 * was removed, because it was queued
2469 * before the removal. Let's ignore
2470 * this here safely. */
2473 unit_add_to_cgroup_empty_queue(u
);
2478 static int cg_bpf_mask_supported(CGroupMask
*ret
) {
2479 CGroupMask mask
= 0;
2482 /* BPF-based firewall */
2483 r
= bpf_firewall_supported();
2485 mask
|= CGROUP_MASK_BPF_FIREWALL
;
2487 /* BPF-based device access control */
2488 r
= bpf_devices_supported();
2490 mask
|= CGROUP_MASK_BPF_DEVICES
;
2496 int manager_setup_cgroup(Manager
*m
) {
2497 _cleanup_free_
char *path
= NULL
;
2498 const char *scope_path
;
2506 /* 1. Determine hierarchy */
2507 m
->cgroup_root
= mfree(m
->cgroup_root
);
2508 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &m
->cgroup_root
);
2510 return log_error_errno(r
, "Cannot determine cgroup we are running in: %m");
2512 /* Chop off the init scope, if we are already located in it */
2513 e
= endswith(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2515 /* LEGACY: Also chop off the system slice if we are in
2516 * it. This is to support live upgrades from older systemd
2517 * versions where PID 1 was moved there. Also see
2518 * cg_get_root_path(). */
2519 if (!e
&& MANAGER_IS_SYSTEM(m
)) {
2520 e
= endswith(m
->cgroup_root
, "/" SPECIAL_SYSTEM_SLICE
);
2522 e
= endswith(m
->cgroup_root
, "/system"); /* even more legacy */
2527 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2528 * easily prepend it everywhere. */
2529 delete_trailing_chars(m
->cgroup_root
, "/");
2532 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, NULL
, &path
);
2534 return log_error_errno(r
, "Cannot find cgroup mount point: %m");
2536 r
= cg_unified_flush();
2538 return log_error_errno(r
, "Couldn't determine if we are running in the unified hierarchy: %m");
2540 all_unified
= cg_all_unified();
2541 if (all_unified
< 0)
2542 return log_error_errno(all_unified
, "Couldn't determine whether we are in all unified mode: %m");
2543 if (all_unified
> 0)
2544 log_debug("Unified cgroup hierarchy is located at %s.", path
);
2546 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2548 return log_error_errno(r
, "Failed to determine whether systemd's own controller is in unified mode: %m");
2550 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path
);
2552 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY
". File system hierarchy is at %s.", path
);
2555 /* 3. Allocate cgroup empty defer event source */
2556 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2557 r
= sd_event_add_defer(m
->event
, &m
->cgroup_empty_event_source
, on_cgroup_empty_event
, m
);
2559 return log_error_errno(r
, "Failed to create cgroup empty event source: %m");
2561 r
= sd_event_source_set_priority(m
->cgroup_empty_event_source
, SD_EVENT_PRIORITY_NORMAL
-5);
2563 return log_error_errno(r
, "Failed to set priority of cgroup empty event source: %m");
2565 r
= sd_event_source_set_enabled(m
->cgroup_empty_event_source
, SD_EVENT_OFF
);
2567 return log_error_errno(r
, "Failed to disable cgroup empty event source: %m");
2569 (void) sd_event_source_set_description(m
->cgroup_empty_event_source
, "cgroup-empty");
2571 /* 4. Install notifier inotify object, or agent */
2572 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0) {
2574 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2576 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2577 safe_close(m
->cgroup_inotify_fd
);
2579 m
->cgroup_inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
2580 if (m
->cgroup_inotify_fd
< 0)
2581 return log_error_errno(errno
, "Failed to create control group inotify object: %m");
2583 r
= sd_event_add_io(m
->event
, &m
->cgroup_inotify_event_source
, m
->cgroup_inotify_fd
, EPOLLIN
, on_cgroup_inotify_event
, m
);
2585 return log_error_errno(r
, "Failed to watch control group inotify object: %m");
2587 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
2588 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2589 r
= sd_event_source_set_priority(m
->cgroup_inotify_event_source
, SD_EVENT_PRIORITY_NORMAL
-4);
2591 return log_error_errno(r
, "Failed to set priority of inotify event source: %m");
2593 (void) sd_event_source_set_description(m
->cgroup_inotify_event_source
, "cgroup-inotify");
2595 } else if (MANAGER_IS_SYSTEM(m
) && manager_owns_host_root_cgroup(m
) && !MANAGER_IS_TEST_RUN(m
)) {
2597 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2598 * since it does not generate events when control groups with children run empty. */
2600 r
= cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER
, SYSTEMD_CGROUP_AGENT_PATH
);
2602 log_warning_errno(r
, "Failed to install release agent, ignoring: %m");
2604 log_debug("Installed release agent.");
2606 log_debug("Release agent already installed.");
2609 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2610 scope_path
= strjoina(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2611 r
= cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2613 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2614 r
= cg_migrate(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2616 log_warning_errno(r
, "Couldn't move remaining userspace processes, ignoring: %m");
2618 /* 6. And pin it, so that it cannot be unmounted */
2619 safe_close(m
->pin_cgroupfs_fd
);
2620 m
->pin_cgroupfs_fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
2621 if (m
->pin_cgroupfs_fd
< 0)
2622 return log_error_errno(errno
, "Failed to open pin file: %m");
2624 } else if (!MANAGER_IS_TEST_RUN(m
))
2625 return log_error_errno(r
, "Failed to create %s control group: %m", scope_path
);
2627 /* 7. Always enable hierarchical support if it exists... */
2628 if (!all_unified
&& !MANAGER_IS_TEST_RUN(m
))
2629 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
2631 /* 8. Figure out which controllers are supported */
2632 r
= cg_mask_supported(&m
->cgroup_supported
);
2634 return log_error_errno(r
, "Failed to determine supported controllers: %m");
2636 /* 9. Figure out which bpf-based pseudo-controllers are supported */
2637 r
= cg_bpf_mask_supported(&mask
);
2639 return log_error_errno(r
, "Failed to determine supported bpf-based pseudo-controllers: %m");
2640 m
->cgroup_supported
|= mask
;
2642 /* 10. Log which controllers are supported */
2643 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++)
2644 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c
), yes_no(m
->cgroup_supported
& CGROUP_CONTROLLER_TO_MASK(c
)));
2649 void manager_shutdown_cgroup(Manager
*m
, bool delete) {
2652 /* We can't really delete the group, since we are in it. But
2654 if (delete && m
->cgroup_root
&& m
->test_run_flags
!= MANAGER_TEST_RUN_MINIMAL
)
2655 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, false);
2657 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2659 m
->cgroup_inotify_wd_unit
= hashmap_free(m
->cgroup_inotify_wd_unit
);
2661 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2662 m
->cgroup_inotify_fd
= safe_close(m
->cgroup_inotify_fd
);
2664 m
->pin_cgroupfs_fd
= safe_close(m
->pin_cgroupfs_fd
);
2666 m
->cgroup_root
= mfree(m
->cgroup_root
);
2669 Unit
* manager_get_unit_by_cgroup(Manager
*m
, const char *cgroup
) {
2676 u
= hashmap_get(m
->cgroup_unit
, cgroup
);
2680 p
= strdupa(cgroup
);
2684 e
= strrchr(p
, '/');
2686 return hashmap_get(m
->cgroup_unit
, SPECIAL_ROOT_SLICE
);
2690 u
= hashmap_get(m
->cgroup_unit
, p
);
2696 Unit
*manager_get_unit_by_pid_cgroup(Manager
*m
, pid_t pid
) {
2697 _cleanup_free_
char *cgroup
= NULL
;
2701 if (!pid_is_valid(pid
))
2704 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &cgroup
) < 0)
2707 return manager_get_unit_by_cgroup(m
, cgroup
);
2710 Unit
*manager_get_unit_by_pid(Manager
*m
, pid_t pid
) {
2715 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
2716 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
2717 * relevant one as children of the process will be assigned to that one, too, before all else. */
2719 if (!pid_is_valid(pid
))
2722 if (pid
== getpid_cached())
2723 return hashmap_get(m
->units
, SPECIAL_INIT_SCOPE
);
2725 u
= manager_get_unit_by_pid_cgroup(m
, pid
);
2729 u
= hashmap_get(m
->watch_pids
, PID_TO_PTR(pid
));
2733 array
= hashmap_get(m
->watch_pids
, PID_TO_PTR(-pid
));
2740 int manager_notify_cgroup_empty(Manager
*m
, const char *cgroup
) {
2746 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
2747 * or from the --system instance */
2749 log_debug("Got cgroup empty notification for: %s", cgroup
);
2751 u
= manager_get_unit_by_cgroup(m
, cgroup
);
2755 unit_add_to_cgroup_empty_queue(u
);
2759 int unit_get_memory_current(Unit
*u
, uint64_t *ret
) {
2760 _cleanup_free_
char *v
= NULL
;
2766 if (!UNIT_CGROUP_BOOL(u
, memory_accounting
))
2769 if (!u
->cgroup_path
)
2772 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2773 if (unit_has_host_root_cgroup(u
))
2774 return procfs_memory_get_current(ret
);
2776 if ((u
->cgroup_realized_mask
& CGROUP_MASK_MEMORY
) == 0)
2779 r
= cg_all_unified();
2783 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.current", &v
);
2785 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.usage_in_bytes", &v
);
2791 return safe_atou64(v
, ret
);
2794 int unit_get_tasks_current(Unit
*u
, uint64_t *ret
) {
2795 _cleanup_free_
char *v
= NULL
;
2801 if (!UNIT_CGROUP_BOOL(u
, tasks_accounting
))
2804 if (!u
->cgroup_path
)
2807 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2808 if (unit_has_host_root_cgroup(u
))
2809 return procfs_tasks_get_current(ret
);
2811 if ((u
->cgroup_realized_mask
& CGROUP_MASK_PIDS
) == 0)
2814 r
= cg_get_attribute("pids", u
->cgroup_path
, "pids.current", &v
);
2820 return safe_atou64(v
, ret
);
2823 static int unit_get_cpu_usage_raw(Unit
*u
, nsec_t
*ret
) {
2824 _cleanup_free_
char *v
= NULL
;
2831 if (!u
->cgroup_path
)
2834 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2835 if (unit_has_host_root_cgroup(u
))
2836 return procfs_cpu_get_usage(ret
);
2838 /* Requisite controllers for CPU accounting are not enabled */
2839 if ((get_cpu_accounting_mask() & ~u
->cgroup_realized_mask
) != 0)
2842 r
= cg_all_unified();
2846 _cleanup_free_
char *val
= NULL
;
2849 r
= cg_get_keyed_attribute("cpu", u
->cgroup_path
, "cpu.stat", STRV_MAKE("usage_usec"), &val
);
2850 if (IN_SET(r
, -ENOENT
, -ENXIO
))
2855 r
= safe_atou64(val
, &us
);
2859 ns
= us
* NSEC_PER_USEC
;
2861 r
= cg_get_attribute("cpuacct", u
->cgroup_path
, "cpuacct.usage", &v
);
2867 r
= safe_atou64(v
, &ns
);
2876 int unit_get_cpu_usage(Unit
*u
, nsec_t
*ret
) {
2882 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2883 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2884 * call this function with a NULL return value. */
2886 if (!UNIT_CGROUP_BOOL(u
, cpu_accounting
))
2889 r
= unit_get_cpu_usage_raw(u
, &ns
);
2890 if (r
== -ENODATA
&& u
->cpu_usage_last
!= NSEC_INFINITY
) {
2891 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2895 *ret
= u
->cpu_usage_last
;
2901 if (ns
> u
->cpu_usage_base
)
2902 ns
-= u
->cpu_usage_base
;
2906 u
->cpu_usage_last
= ns
;
2913 int unit_get_ip_accounting(
2915 CGroupIPAccountingMetric metric
,
2922 assert(metric
>= 0);
2923 assert(metric
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
);
2926 if (!UNIT_CGROUP_BOOL(u
, ip_accounting
))
2929 fd
= IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_INGRESS_PACKETS
) ?
2930 u
->ip_accounting_ingress_map_fd
:
2931 u
->ip_accounting_egress_map_fd
;
2935 if (IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_EGRESS_BYTES
))
2936 r
= bpf_firewall_read_accounting(fd
, &value
, NULL
);
2938 r
= bpf_firewall_read_accounting(fd
, NULL
, &value
);
2942 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
2943 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
2944 * ip_accounting_extra[] field, and add them in here transparently. */
2946 *ret
= value
+ u
->ip_accounting_extra
[metric
];
2951 int unit_reset_cpu_accounting(Unit
*u
) {
2957 u
->cpu_usage_last
= NSEC_INFINITY
;
2959 r
= unit_get_cpu_usage_raw(u
, &ns
);
2961 u
->cpu_usage_base
= 0;
2965 u
->cpu_usage_base
= ns
;
2969 int unit_reset_ip_accounting(Unit
*u
) {
2974 if (u
->ip_accounting_ingress_map_fd
>= 0)
2975 r
= bpf_firewall_reset_accounting(u
->ip_accounting_ingress_map_fd
);
2977 if (u
->ip_accounting_egress_map_fd
>= 0)
2978 q
= bpf_firewall_reset_accounting(u
->ip_accounting_egress_map_fd
);
2980 zero(u
->ip_accounting_extra
);
2982 return r
< 0 ? r
: q
;
2985 void unit_invalidate_cgroup(Unit
*u
, CGroupMask m
) {
2988 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2994 /* always invalidate compat pairs together */
2995 if (m
& (CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
))
2996 m
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
2998 if (m
& (CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
))
2999 m
|= CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
;
3001 if (FLAGS_SET(u
->cgroup_invalidated_mask
, m
)) /* NOP? */
3004 u
->cgroup_invalidated_mask
|= m
;
3005 unit_add_to_cgroup_realize_queue(u
);
3008 void unit_invalidate_cgroup_bpf(Unit
*u
) {
3011 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
3014 if (u
->cgroup_invalidated_mask
& CGROUP_MASK_BPF_FIREWALL
) /* NOP? */
3017 u
->cgroup_invalidated_mask
|= CGROUP_MASK_BPF_FIREWALL
;
3018 unit_add_to_cgroup_realize_queue(u
);
3020 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
3021 * list of our children includes our own. */
3022 if (u
->type
== UNIT_SLICE
) {
3027 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
3028 if (UNIT_DEREF(member
->slice
) == u
)
3029 unit_invalidate_cgroup_bpf(member
);
3034 bool unit_cgroup_delegate(Unit
*u
) {
3039 if (!UNIT_VTABLE(u
)->can_delegate
)
3042 c
= unit_get_cgroup_context(u
);
3049 void manager_invalidate_startup_units(Manager
*m
) {
3055 SET_FOREACH(u
, m
->startup_units
, i
)
3056 unit_invalidate_cgroup(u
, CGROUP_MASK_CPU
|CGROUP_MASK_IO
|CGROUP_MASK_BLKIO
);
3059 static const char* const cgroup_device_policy_table
[_CGROUP_DEVICE_POLICY_MAX
] = {
3060 [CGROUP_AUTO
] = "auto",
3061 [CGROUP_CLOSED
] = "closed",
3062 [CGROUP_STRICT
] = "strict",
3065 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy
, CGroupDevicePolicy
);