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_DEFAULT_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
,
101 .cpu_quota_period_usec
= USEC_INFINITY
,
103 .cpu_shares
= CGROUP_CPU_SHARES_INVALID
,
104 .startup_cpu_shares
= CGROUP_CPU_SHARES_INVALID
,
106 .memory_high
= CGROUP_LIMIT_MAX
,
107 .memory_max
= CGROUP_LIMIT_MAX
,
108 .memory_swap_max
= CGROUP_LIMIT_MAX
,
110 .memory_limit
= CGROUP_LIMIT_MAX
,
112 .io_weight
= CGROUP_WEIGHT_INVALID
,
113 .startup_io_weight
= CGROUP_WEIGHT_INVALID
,
115 .blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
,
116 .startup_blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
,
118 .tasks_max
= CGROUP_LIMIT_MAX
,
122 void cgroup_context_free_device_allow(CGroupContext
*c
, CGroupDeviceAllow
*a
) {
126 LIST_REMOVE(device_allow
, c
->device_allow
, a
);
131 void cgroup_context_free_io_device_weight(CGroupContext
*c
, CGroupIODeviceWeight
*w
) {
135 LIST_REMOVE(device_weights
, c
->io_device_weights
, w
);
140 void cgroup_context_free_io_device_latency(CGroupContext
*c
, CGroupIODeviceLatency
*l
) {
144 LIST_REMOVE(device_latencies
, c
->io_device_latencies
, l
);
149 void cgroup_context_free_io_device_limit(CGroupContext
*c
, CGroupIODeviceLimit
*l
) {
153 LIST_REMOVE(device_limits
, c
->io_device_limits
, l
);
158 void cgroup_context_free_blockio_device_weight(CGroupContext
*c
, CGroupBlockIODeviceWeight
*w
) {
162 LIST_REMOVE(device_weights
, c
->blockio_device_weights
, w
);
167 void cgroup_context_free_blockio_device_bandwidth(CGroupContext
*c
, CGroupBlockIODeviceBandwidth
*b
) {
171 LIST_REMOVE(device_bandwidths
, c
->blockio_device_bandwidths
, b
);
176 void cgroup_context_done(CGroupContext
*c
) {
179 while (c
->io_device_weights
)
180 cgroup_context_free_io_device_weight(c
, c
->io_device_weights
);
182 while (c
->io_device_latencies
)
183 cgroup_context_free_io_device_latency(c
, c
->io_device_latencies
);
185 while (c
->io_device_limits
)
186 cgroup_context_free_io_device_limit(c
, c
->io_device_limits
);
188 while (c
->blockio_device_weights
)
189 cgroup_context_free_blockio_device_weight(c
, c
->blockio_device_weights
);
191 while (c
->blockio_device_bandwidths
)
192 cgroup_context_free_blockio_device_bandwidth(c
, c
->blockio_device_bandwidths
);
194 while (c
->device_allow
)
195 cgroup_context_free_device_allow(c
, c
->device_allow
);
197 c
->ip_address_allow
= ip_address_access_free_all(c
->ip_address_allow
);
198 c
->ip_address_deny
= ip_address_access_free_all(c
->ip_address_deny
);
201 void cgroup_context_dump(CGroupContext
*c
, FILE* f
, const char *prefix
) {
202 CGroupIODeviceLimit
*il
;
203 CGroupIODeviceWeight
*iw
;
204 CGroupIODeviceLatency
*l
;
205 CGroupBlockIODeviceBandwidth
*b
;
206 CGroupBlockIODeviceWeight
*w
;
207 CGroupDeviceAllow
*a
;
208 IPAddressAccessItem
*iaai
;
209 char u
[FORMAT_TIMESPAN_MAX
];
210 char v
[FORMAT_TIMESPAN_MAX
];
215 prefix
= strempty(prefix
);
218 "%sCPUAccounting=%s\n"
219 "%sIOAccounting=%s\n"
220 "%sBlockIOAccounting=%s\n"
221 "%sMemoryAccounting=%s\n"
222 "%sTasksAccounting=%s\n"
223 "%sIPAccounting=%s\n"
224 "%sCPUWeight=%" PRIu64
"\n"
225 "%sStartupCPUWeight=%" PRIu64
"\n"
226 "%sCPUShares=%" PRIu64
"\n"
227 "%sStartupCPUShares=%" PRIu64
"\n"
228 "%sCPUQuotaPerSecSec=%s\n"
229 "%sCPUQuotaPeriodSec=%s\n"
230 "%sIOWeight=%" PRIu64
"\n"
231 "%sStartupIOWeight=%" PRIu64
"\n"
232 "%sBlockIOWeight=%" PRIu64
"\n"
233 "%sStartupBlockIOWeight=%" PRIu64
"\n"
234 "%sMemoryMin=%" PRIu64
"\n"
235 "%sMemoryLow=%" PRIu64
"\n"
236 "%sMemoryHigh=%" PRIu64
"\n"
237 "%sMemoryMax=%" PRIu64
"\n"
238 "%sMemorySwapMax=%" PRIu64
"\n"
239 "%sMemoryLimit=%" PRIu64
"\n"
240 "%sTasksMax=%" PRIu64
"\n"
241 "%sDevicePolicy=%s\n"
243 prefix
, yes_no(c
->cpu_accounting
),
244 prefix
, yes_no(c
->io_accounting
),
245 prefix
, yes_no(c
->blockio_accounting
),
246 prefix
, yes_no(c
->memory_accounting
),
247 prefix
, yes_no(c
->tasks_accounting
),
248 prefix
, yes_no(c
->ip_accounting
),
249 prefix
, c
->cpu_weight
,
250 prefix
, c
->startup_cpu_weight
,
251 prefix
, c
->cpu_shares
,
252 prefix
, c
->startup_cpu_shares
,
253 prefix
, format_timespan(u
, sizeof(u
), c
->cpu_quota_per_sec_usec
, 1),
254 prefix
, format_timespan(v
, sizeof(v
), c
->cpu_quota_period_usec
, 1),
255 prefix
, c
->io_weight
,
256 prefix
, c
->startup_io_weight
,
257 prefix
, c
->blockio_weight
,
258 prefix
, c
->startup_blockio_weight
,
259 prefix
, c
->memory_min
,
260 prefix
, c
->memory_low
,
261 prefix
, c
->memory_high
,
262 prefix
, c
->memory_max
,
263 prefix
, c
->memory_swap_max
,
264 prefix
, c
->memory_limit
,
265 prefix
, c
->tasks_max
,
266 prefix
, cgroup_device_policy_to_string(c
->device_policy
),
267 prefix
, yes_no(c
->delegate
));
270 _cleanup_free_
char *t
= NULL
;
272 (void) cg_mask_to_string(c
->delegate_controllers
, &t
);
274 fprintf(f
, "%sDelegateControllers=%s\n",
279 LIST_FOREACH(device_allow
, a
, c
->device_allow
)
281 "%sDeviceAllow=%s %s%s%s\n",
284 a
->r
? "r" : "", a
->w
? "w" : "", a
->m
? "m" : "");
286 LIST_FOREACH(device_weights
, iw
, c
->io_device_weights
)
288 "%sIODeviceWeight=%s %" PRIu64
"\n",
293 LIST_FOREACH(device_latencies
, l
, c
->io_device_latencies
)
295 "%sIODeviceLatencyTargetSec=%s %s\n",
298 format_timespan(u
, sizeof(u
), l
->target_usec
, 1));
300 LIST_FOREACH(device_limits
, il
, c
->io_device_limits
) {
301 char buf
[FORMAT_BYTES_MAX
];
302 CGroupIOLimitType type
;
304 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
305 if (il
->limits
[type
] != cgroup_io_limit_defaults
[type
])
309 cgroup_io_limit_type_to_string(type
),
311 format_bytes(buf
, sizeof(buf
), il
->limits
[type
]));
314 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
316 "%sBlockIODeviceWeight=%s %" PRIu64
,
321 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
322 char buf
[FORMAT_BYTES_MAX
];
324 if (b
->rbps
!= CGROUP_LIMIT_MAX
)
326 "%sBlockIOReadBandwidth=%s %s\n",
329 format_bytes(buf
, sizeof(buf
), b
->rbps
));
330 if (b
->wbps
!= CGROUP_LIMIT_MAX
)
332 "%sBlockIOWriteBandwidth=%s %s\n",
335 format_bytes(buf
, sizeof(buf
), b
->wbps
));
338 LIST_FOREACH(items
, iaai
, c
->ip_address_allow
) {
339 _cleanup_free_
char *k
= NULL
;
341 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
342 fprintf(f
, "%sIPAddressAllow=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
345 LIST_FOREACH(items
, iaai
, c
->ip_address_deny
) {
346 _cleanup_free_
char *k
= NULL
;
348 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
349 fprintf(f
, "%sIPAddressDeny=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
353 int cgroup_add_device_allow(CGroupContext
*c
, const char *dev
, const char *mode
) {
354 _cleanup_free_ CGroupDeviceAllow
*a
= NULL
;
355 _cleanup_free_
char *d
= NULL
;
359 assert(isempty(mode
) || in_charset(mode
, "rwm"));
361 a
= new(CGroupDeviceAllow
, 1);
369 *a
= (CGroupDeviceAllow
) {
371 .r
= isempty(mode
) || strchr(mode
, 'r'),
372 .w
= isempty(mode
) || strchr(mode
, 'w'),
373 .m
= isempty(mode
) || strchr(mode
, 'm'),
376 LIST_PREPEND(device_allow
, c
->device_allow
, a
);
382 static void cgroup_xattr_apply(Unit
*u
) {
383 char ids
[SD_ID128_STRING_MAX
];
388 if (!MANAGER_IS_SYSTEM(u
->manager
))
391 if (sd_id128_is_null(u
->invocation_id
))
394 r
= cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
395 "trusted.invocation_id",
396 sd_id128_to_string(u
->invocation_id
, ids
), 32,
399 log_unit_debug_errno(u
, r
, "Failed to set invocation ID on control group %s, ignoring: %m", u
->cgroup_path
);
402 static int lookup_block_device(const char *p
, dev_t
*ret
) {
410 r
= device_path_parse_major_minor(p
, &mode
, &rdev
);
411 if (r
== -ENODEV
) { /* not a parsable device node, need to go to disk */
413 if (stat(p
, &st
) < 0)
414 return log_warning_errno(errno
, "Couldn't stat device '%s': %m", p
);
415 rdev
= (dev_t
)st
.st_rdev
;
416 dev
= (dev_t
)st
.st_dev
;
419 return log_warning_errno(r
, "Failed to parse major/minor from path '%s': %m", p
);
422 log_warning("Device node '%s' is a character device, but block device needed.", p
);
424 } else if (S_ISBLK(mode
))
426 else if (major(dev
) != 0)
427 *ret
= dev
; /* If this is not a device node then use the block device this file is stored on */
429 /* If this is btrfs, getting the backing block device is a bit harder */
430 r
= btrfs_get_block_device(p
, ret
);
431 if (r
< 0 && r
!= -ENOTTY
)
432 return log_warning_errno(r
, "Failed to determine block device backing btrfs file system '%s': %m", p
);
434 log_warning("'%s' is not a block device node, and file system block device cannot be determined or is not local.", p
);
439 /* If this is a LUKS device, try to get the originating block device */
440 (void) block_get_originating(*ret
, ret
);
442 /* If this is a partition, try to get the originating block device */
443 (void) block_get_whole_disk(*ret
, ret
);
447 static int whitelist_device(BPFProgram
*prog
, const char *path
, const char *node
, const char *acc
) {
455 /* Some special handling for /dev/block/%u:%u, /dev/char/%u:%u, /run/systemd/inaccessible/chr and
456 * /run/systemd/inaccessible/blk paths. Instead of stat()ing these we parse out the major/minor directly. This
457 * means clients can use these path without the device node actually around */
458 r
= device_path_parse_major_minor(node
, &mode
, &rdev
);
461 return log_warning_errno(r
, "Couldn't parse major/minor from device path '%s': %m", node
);
464 if (stat(node
, &st
) < 0)
465 return log_warning_errno(errno
, "Couldn't stat device %s: %m", node
);
467 if (!S_ISCHR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
468 log_warning("%s is not a device.", node
);
471 rdev
= (dev_t
) st
.st_rdev
;
475 if (cg_all_unified() > 0) {
479 return cgroup_bpf_whitelist_device(prog
, S_ISCHR(mode
) ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
,
480 major(rdev
), minor(rdev
), acc
);
483 char buf
[2+DECIMAL_STR_MAX(dev_t
)*2+2+4];
487 S_ISCHR(mode
) ? 'c' : 'b',
488 major(rdev
), minor(rdev
),
491 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore EINVAL here. */
493 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
495 return log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
, -EPERM
) ? LOG_DEBUG
: LOG_WARNING
,
496 r
, "Failed to set devices.allow on %s: %m", path
);
502 static int whitelist_major(BPFProgram
*prog
, const char *path
, const char *name
, char type
, const char *acc
) {
503 _cleanup_fclose_
FILE *f
= NULL
;
504 char buf
[2+DECIMAL_STR_MAX(unsigned)+3+4];
511 assert(IN_SET(type
, 'b', 'c'));
513 if (streq(name
, "*")) {
514 /* If the name is a wildcard, then apply this list to all devices of this type */
516 if (cg_all_unified() > 0) {
520 (void) cgroup_bpf_whitelist_class(prog
, type
== 'c' ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
, acc
);
522 xsprintf(buf
, "%c *:* %s", type
, acc
);
524 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
526 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
527 "Failed to set devices.allow on %s: %m", path
);
532 if (safe_atou(name
, &maj
) >= 0 && DEVICE_MAJOR_VALID(maj
)) {
533 /* The name is numeric and suitable as major. In that case, let's take is major, and create the entry
536 if (cg_all_unified() > 0) {
540 (void) cgroup_bpf_whitelist_major(prog
,
541 type
== 'c' ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
,
544 xsprintf(buf
, "%c %u:* %s", type
, maj
, acc
);
546 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
548 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
549 "Failed to set devices.allow on %s: %m", path
);
555 f
= fopen("/proc/devices", "re");
557 return log_warning_errno(errno
, "Cannot open /proc/devices to resolve %s (%c): %m", name
, type
);
560 _cleanup_free_
char *line
= NULL
;
563 r
= read_line(f
, LONG_LINE_MAX
, &line
);
565 return log_warning_errno(r
, "Failed to read /proc/devices: %m");
569 if (type
== 'c' && streq(line
, "Character devices:")) {
574 if (type
== 'b' && streq(line
, "Block devices:")) {
589 w
= strpbrk(p
, WHITESPACE
);
594 r
= safe_atou(p
, &maj
);
601 w
+= strspn(w
, WHITESPACE
);
603 if (fnmatch(name
, w
, 0) != 0)
606 if (cg_all_unified() > 0) {
610 (void) cgroup_bpf_whitelist_major(prog
,
611 type
== 'c' ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
,
620 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore EINVAL
623 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
625 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
, -EPERM
) ? LOG_DEBUG
: LOG_WARNING
,
626 r
, "Failed to set devices.allow on %s: %m", path
);
633 static bool cgroup_context_has_cpu_weight(CGroupContext
*c
) {
634 return c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
||
635 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
;
638 static bool cgroup_context_has_cpu_shares(CGroupContext
*c
) {
639 return c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
640 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
;
643 static uint64_t cgroup_context_cpu_weight(CGroupContext
*c
, ManagerState state
) {
644 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
645 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
)
646 return c
->startup_cpu_weight
;
647 else if (c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
)
648 return c
->cpu_weight
;
650 return CGROUP_WEIGHT_DEFAULT
;
653 static uint64_t cgroup_context_cpu_shares(CGroupContext
*c
, ManagerState state
) {
654 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
655 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
656 return c
->startup_cpu_shares
;
657 else if (c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
658 return c
->cpu_shares
;
660 return CGROUP_CPU_SHARES_DEFAULT
;
663 usec_t
cgroup_cpu_adjust_period(usec_t period
, usec_t quota
, usec_t resolution
, usec_t max_period
) {
664 /* kernel uses a minimum resolution of 1ms, so both period and (quota * period)
665 * need to be higher than that boundary. quota is specified in USecPerSec.
666 * Additionally, period must be at most max_period. */
669 return MIN(MAX3(period
, resolution
, resolution
* USEC_PER_SEC
/ quota
), max_period
);
672 static usec_t
cgroup_cpu_adjust_period_and_log(Unit
*u
, usec_t period
, usec_t quota
) {
675 if (quota
== USEC_INFINITY
)
676 /* Always use default period for infinity quota. */
677 return CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC
;
679 if (period
== USEC_INFINITY
)
680 /* Default period was requested. */
681 period
= CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC
;
683 /* Clamp to interval [1ms, 1s] */
684 new_period
= cgroup_cpu_adjust_period(period
, quota
, USEC_PER_MSEC
, USEC_PER_SEC
);
686 if (new_period
!= period
) {
687 char v
[FORMAT_TIMESPAN_MAX
];
688 log_unit_full(u
, u
->warned_clamping_cpu_quota_period
? LOG_DEBUG
: LOG_WARNING
, 0,
689 "Clamping CPU interval for cpu.max: period is now %s",
690 format_timespan(v
, sizeof(v
), new_period
, 1));
691 u
->warned_clamping_cpu_quota_period
= true;
697 static void cgroup_apply_unified_cpu_weight(Unit
*u
, uint64_t weight
) {
698 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
700 xsprintf(buf
, "%" PRIu64
"\n", weight
);
701 (void) set_attribute_and_warn(u
, "cpu", "cpu.weight", buf
);
704 static void cgroup_apply_unified_cpu_quota(Unit
*u
, usec_t quota
, usec_t period
) {
705 char buf
[(DECIMAL_STR_MAX(usec_t
) + 1) * 2 + 1];
707 period
= cgroup_cpu_adjust_period_and_log(u
, period
, quota
);
708 if (quota
!= USEC_INFINITY
)
709 xsprintf(buf
, USEC_FMT
" " USEC_FMT
"\n",
710 MAX(quota
* period
/ USEC_PER_SEC
, USEC_PER_MSEC
), period
);
712 xsprintf(buf
, "max " USEC_FMT
"\n", period
);
713 (void) set_attribute_and_warn(u
, "cpu", "cpu.max", buf
);
716 static void cgroup_apply_legacy_cpu_shares(Unit
*u
, uint64_t shares
) {
717 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
719 xsprintf(buf
, "%" PRIu64
"\n", shares
);
720 (void) set_attribute_and_warn(u
, "cpu", "cpu.shares", buf
);
723 static void cgroup_apply_legacy_cpu_quota(Unit
*u
, usec_t quota
, usec_t period
) {
724 char buf
[DECIMAL_STR_MAX(usec_t
) + 2];
726 period
= cgroup_cpu_adjust_period_and_log(u
, period
, quota
);
728 xsprintf(buf
, USEC_FMT
"\n", period
);
729 (void) set_attribute_and_warn(u
, "cpu", "cpu.cfs_period_us", buf
);
731 if (quota
!= USEC_INFINITY
) {
732 xsprintf(buf
, USEC_FMT
"\n", MAX(quota
* period
/ USEC_PER_SEC
, USEC_PER_MSEC
));
733 (void) set_attribute_and_warn(u
, "cpu", "cpu.cfs_quota_us", buf
);
735 (void) set_attribute_and_warn(u
, "cpu", "cpu.cfs_quota_us", "-1\n");
738 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares
) {
739 return CLAMP(shares
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_CPU_SHARES_DEFAULT
,
740 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
743 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight
) {
744 return CLAMP(weight
* CGROUP_CPU_SHARES_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
745 CGROUP_CPU_SHARES_MIN
, CGROUP_CPU_SHARES_MAX
);
748 static bool cgroup_context_has_io_config(CGroupContext
*c
) {
749 return c
->io_accounting
||
750 c
->io_weight
!= CGROUP_WEIGHT_INVALID
||
751 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
752 c
->io_device_weights
||
753 c
->io_device_latencies
||
757 static bool cgroup_context_has_blockio_config(CGroupContext
*c
) {
758 return c
->blockio_accounting
||
759 c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
760 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
761 c
->blockio_device_weights
||
762 c
->blockio_device_bandwidths
;
765 static uint64_t cgroup_context_io_weight(CGroupContext
*c
, ManagerState state
) {
766 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
767 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
)
768 return c
->startup_io_weight
;
769 else if (c
->io_weight
!= CGROUP_WEIGHT_INVALID
)
772 return CGROUP_WEIGHT_DEFAULT
;
775 static uint64_t cgroup_context_blkio_weight(CGroupContext
*c
, ManagerState state
) {
776 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
777 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
778 return c
->startup_blockio_weight
;
779 else if (c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
780 return c
->blockio_weight
;
782 return CGROUP_BLKIO_WEIGHT_DEFAULT
;
785 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight
) {
786 return CLAMP(blkio_weight
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_BLKIO_WEIGHT_DEFAULT
,
787 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
790 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight
) {
791 return CLAMP(io_weight
* CGROUP_BLKIO_WEIGHT_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
792 CGROUP_BLKIO_WEIGHT_MIN
, CGROUP_BLKIO_WEIGHT_MAX
);
795 static void cgroup_apply_io_device_weight(Unit
*u
, const char *dev_path
, uint64_t io_weight
) {
796 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
800 r
= lookup_block_device(dev_path
, &dev
);
804 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), io_weight
);
805 (void) set_attribute_and_warn(u
, "io", "io.weight", buf
);
808 static void cgroup_apply_blkio_device_weight(Unit
*u
, const char *dev_path
, uint64_t blkio_weight
) {
809 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
813 r
= lookup_block_device(dev_path
, &dev
);
817 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), blkio_weight
);
818 (void) set_attribute_and_warn(u
, "blkio", "blkio.weight_device", buf
);
821 static void cgroup_apply_io_device_latency(Unit
*u
, const char *dev_path
, usec_t target
) {
822 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+7+DECIMAL_STR_MAX(uint64_t)+1];
826 r
= lookup_block_device(dev_path
, &dev
);
830 if (target
!= USEC_INFINITY
)
831 xsprintf(buf
, "%u:%u target=%" PRIu64
"\n", major(dev
), minor(dev
), target
);
833 xsprintf(buf
, "%u:%u target=max\n", major(dev
), minor(dev
));
835 (void) set_attribute_and_warn(u
, "io", "io.latency", buf
);
838 static void cgroup_apply_io_device_limit(Unit
*u
, const char *dev_path
, uint64_t *limits
) {
839 char limit_bufs
[_CGROUP_IO_LIMIT_TYPE_MAX
][DECIMAL_STR_MAX(uint64_t)];
840 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
841 CGroupIOLimitType type
;
845 r
= lookup_block_device(dev_path
, &dev
);
849 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
850 if (limits
[type
] != cgroup_io_limit_defaults
[type
])
851 xsprintf(limit_bufs
[type
], "%" PRIu64
, limits
[type
]);
853 xsprintf(limit_bufs
[type
], "%s", limits
[type
] == CGROUP_LIMIT_MAX
? "max" : "0");
855 xsprintf(buf
, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev
), minor(dev
),
856 limit_bufs
[CGROUP_IO_RBPS_MAX
], limit_bufs
[CGROUP_IO_WBPS_MAX
],
857 limit_bufs
[CGROUP_IO_RIOPS_MAX
], limit_bufs
[CGROUP_IO_WIOPS_MAX
]);
858 (void) set_attribute_and_warn(u
, "io", "io.max", buf
);
861 static void cgroup_apply_blkio_device_limit(Unit
*u
, const char *dev_path
, uint64_t rbps
, uint64_t wbps
) {
862 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
866 r
= lookup_block_device(dev_path
, &dev
);
870 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), rbps
);
871 (void) set_attribute_and_warn(u
, "blkio", "blkio.throttle.read_bps_device", buf
);
873 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), wbps
);
874 (void) set_attribute_and_warn(u
, "blkio", "blkio.throttle.write_bps_device", buf
);
877 static bool cgroup_context_has_unified_memory_config(CGroupContext
*c
) {
878 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
;
881 static void cgroup_apply_unified_memory_limit(Unit
*u
, const char *file
, uint64_t v
) {
882 char buf
[DECIMAL_STR_MAX(uint64_t) + 1] = "max\n";
884 if (v
!= CGROUP_LIMIT_MAX
)
885 xsprintf(buf
, "%" PRIu64
"\n", v
);
887 (void) set_attribute_and_warn(u
, "memory", file
, buf
);
890 static void cgroup_apply_firewall(Unit
*u
) {
893 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
895 if (bpf_firewall_compile(u
) < 0)
898 (void) bpf_firewall_install(u
);
901 static void cgroup_context_apply(
903 CGroupMask apply_mask
,
904 ManagerState state
) {
908 bool is_host_root
, is_local_root
;
913 /* Nothing to do? Exit early! */
917 /* Some cgroup attributes are not supported on the host root cgroup, hence silently ignore them here. And other
918 * attributes should only be managed for cgroups further down the tree. */
919 is_local_root
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
920 is_host_root
= unit_has_host_root_cgroup(u
);
922 assert_se(c
= unit_get_cgroup_context(u
));
923 assert_se(path
= u
->cgroup_path
);
925 if (is_local_root
) /* Make sure we don't try to display messages with an empty path. */
928 /* We generally ignore errors caused by read-only mounted cgroup trees (assuming we are running in a container
929 * then), and missing cgroups, i.e. EROFS and ENOENT. */
931 /* In fully unified mode these attributes don't exist on the host cgroup root. On legacy the weights exist, but
932 * setting the weight makes very little sense on the host root cgroup, as there are no other cgroups at this
933 * level. The quota exists there too, but any attempt to write to it is refused with EINVAL. Inside of
934 * containers we want to leave control of these to the container manager (and if cgroup v2 delegation is used
935 * we couldn't even write to them if we wanted to). */
936 if ((apply_mask
& CGROUP_MASK_CPU
) && !is_local_root
) {
938 if (cg_all_unified() > 0) {
941 if (cgroup_context_has_cpu_weight(c
))
942 weight
= cgroup_context_cpu_weight(c
, state
);
943 else if (cgroup_context_has_cpu_shares(c
)) {
946 shares
= cgroup_context_cpu_shares(c
, state
);
947 weight
= cgroup_cpu_shares_to_weight(shares
);
949 log_cgroup_compat(u
, "Applying [Startup]CPUShares=%" PRIu64
" as [Startup]CPUWeight=%" PRIu64
" on %s",
950 shares
, weight
, path
);
952 weight
= CGROUP_WEIGHT_DEFAULT
;
954 cgroup_apply_unified_cpu_weight(u
, weight
);
955 cgroup_apply_unified_cpu_quota(u
, c
->cpu_quota_per_sec_usec
, c
->cpu_quota_period_usec
);
960 if (cgroup_context_has_cpu_weight(c
)) {
963 weight
= cgroup_context_cpu_weight(c
, state
);
964 shares
= cgroup_cpu_weight_to_shares(weight
);
966 log_cgroup_compat(u
, "Applying [Startup]CPUWeight=%" PRIu64
" as [Startup]CPUShares=%" PRIu64
" on %s",
967 weight
, shares
, path
);
968 } else if (cgroup_context_has_cpu_shares(c
))
969 shares
= cgroup_context_cpu_shares(c
, state
);
971 shares
= CGROUP_CPU_SHARES_DEFAULT
;
973 cgroup_apply_legacy_cpu_shares(u
, shares
);
974 cgroup_apply_legacy_cpu_quota(u
, c
->cpu_quota_per_sec_usec
, c
->cpu_quota_period_usec
);
978 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroup v2
979 * controller), and in case of containers we want to leave control of these attributes to the container manager
980 * (and we couldn't access that stuff anyway, even if we tried if proper delegation is used). */
981 if ((apply_mask
& CGROUP_MASK_IO
) && !is_local_root
) {
982 char buf
[8+DECIMAL_STR_MAX(uint64_t)+1];
983 bool has_io
, has_blockio
;
986 has_io
= cgroup_context_has_io_config(c
);
987 has_blockio
= cgroup_context_has_blockio_config(c
);
990 weight
= cgroup_context_io_weight(c
, state
);
991 else if (has_blockio
) {
992 uint64_t blkio_weight
;
994 blkio_weight
= cgroup_context_blkio_weight(c
, state
);
995 weight
= cgroup_weight_blkio_to_io(blkio_weight
);
997 log_cgroup_compat(u
, "Applying [Startup]BlockIOWeight=%" PRIu64
" as [Startup]IOWeight=%" PRIu64
,
998 blkio_weight
, weight
);
1000 weight
= CGROUP_WEIGHT_DEFAULT
;
1002 xsprintf(buf
, "default %" PRIu64
"\n", weight
);
1003 (void) set_attribute_and_warn(u
, "io", "io.weight", buf
);
1006 CGroupIODeviceLatency
*latency
;
1007 CGroupIODeviceLimit
*limit
;
1008 CGroupIODeviceWeight
*w
;
1010 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
)
1011 cgroup_apply_io_device_weight(u
, w
->path
, w
->weight
);
1013 LIST_FOREACH(device_limits
, limit
, c
->io_device_limits
)
1014 cgroup_apply_io_device_limit(u
, limit
->path
, limit
->limits
);
1016 LIST_FOREACH(device_latencies
, latency
, c
->io_device_latencies
)
1017 cgroup_apply_io_device_latency(u
, latency
->path
, latency
->target_usec
);
1019 } else if (has_blockio
) {
1020 CGroupBlockIODeviceWeight
*w
;
1021 CGroupBlockIODeviceBandwidth
*b
;
1023 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
) {
1024 weight
= cgroup_weight_blkio_to_io(w
->weight
);
1026 log_cgroup_compat(u
, "Applying BlockIODeviceWeight=%" PRIu64
" as IODeviceWeight=%" PRIu64
" for %s",
1027 w
->weight
, weight
, w
->path
);
1029 cgroup_apply_io_device_weight(u
, w
->path
, weight
);
1032 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
1033 uint64_t limits
[_CGROUP_IO_LIMIT_TYPE_MAX
];
1034 CGroupIOLimitType type
;
1036 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
1037 limits
[type
] = cgroup_io_limit_defaults
[type
];
1039 limits
[CGROUP_IO_RBPS_MAX
] = b
->rbps
;
1040 limits
[CGROUP_IO_WBPS_MAX
] = b
->wbps
;
1042 log_cgroup_compat(u
, "Applying BlockIO{Read|Write}Bandwidth=%" PRIu64
" %" PRIu64
" as IO{Read|Write}BandwidthMax= for %s",
1043 b
->rbps
, b
->wbps
, b
->path
);
1045 cgroup_apply_io_device_limit(u
, b
->path
, limits
);
1050 if (apply_mask
& CGROUP_MASK_BLKIO
) {
1051 bool has_io
, has_blockio
;
1053 has_io
= cgroup_context_has_io_config(c
);
1054 has_blockio
= cgroup_context_has_blockio_config(c
);
1056 /* Applying a 'weight' never makes sense for the host root cgroup, and for containers this should be
1057 * left to our container manager, too. */
1058 if (!is_local_root
) {
1059 char buf
[DECIMAL_STR_MAX(uint64_t)+1];
1065 io_weight
= cgroup_context_io_weight(c
, state
);
1066 weight
= cgroup_weight_io_to_blkio(cgroup_context_io_weight(c
, state
));
1068 log_cgroup_compat(u
, "Applying [Startup]IOWeight=%" PRIu64
" as [Startup]BlockIOWeight=%" PRIu64
,
1070 } else if (has_blockio
)
1071 weight
= cgroup_context_blkio_weight(c
, state
);
1073 weight
= CGROUP_BLKIO_WEIGHT_DEFAULT
;
1075 xsprintf(buf
, "%" PRIu64
"\n", weight
);
1076 (void) set_attribute_and_warn(u
, "blkio", "blkio.weight", buf
);
1079 CGroupIODeviceWeight
*w
;
1081 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
) {
1082 weight
= cgroup_weight_io_to_blkio(w
->weight
);
1084 log_cgroup_compat(u
, "Applying IODeviceWeight=%" PRIu64
" as BlockIODeviceWeight=%" PRIu64
" for %s",
1085 w
->weight
, weight
, w
->path
);
1087 cgroup_apply_blkio_device_weight(u
, w
->path
, weight
);
1089 } else if (has_blockio
) {
1090 CGroupBlockIODeviceWeight
*w
;
1092 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
1093 cgroup_apply_blkio_device_weight(u
, w
->path
, w
->weight
);
1097 /* The bandwith limits are something that make sense to be applied to the host's root but not container
1098 * roots, as there we want the container manager to handle it */
1099 if (is_host_root
|| !is_local_root
) {
1101 CGroupIODeviceLimit
*l
;
1103 LIST_FOREACH(device_limits
, l
, c
->io_device_limits
) {
1104 log_cgroup_compat(u
, "Applying IO{Read|Write}Bandwidth=%" PRIu64
" %" PRIu64
" as BlockIO{Read|Write}BandwidthMax= for %s",
1105 l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
], l
->path
);
1107 cgroup_apply_blkio_device_limit(u
, l
->path
, l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
]);
1109 } else if (has_blockio
) {
1110 CGroupBlockIODeviceBandwidth
*b
;
1112 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
)
1113 cgroup_apply_blkio_device_limit(u
, b
->path
, b
->rbps
, b
->wbps
);
1118 /* In unified mode 'memory' attributes do not exist on the root cgroup. In legacy mode 'memory.limit_in_bytes'
1119 * exists on the root cgroup, but any writes to it are refused with EINVAL. And if we run in a container we
1120 * want to leave control to the container manager (and if proper cgroup v2 delegation is used we couldn't even
1121 * write to this if we wanted to.) */
1122 if ((apply_mask
& CGROUP_MASK_MEMORY
) && !is_local_root
) {
1124 if (cg_all_unified() > 0) {
1125 uint64_t max
, swap_max
= CGROUP_LIMIT_MAX
;
1127 if (cgroup_context_has_unified_memory_config(c
)) {
1128 max
= c
->memory_max
;
1129 swap_max
= c
->memory_swap_max
;
1131 max
= c
->memory_limit
;
1133 if (max
!= CGROUP_LIMIT_MAX
)
1134 log_cgroup_compat(u
, "Applying MemoryLimit=%" PRIu64
" as MemoryMax=", max
);
1137 cgroup_apply_unified_memory_limit(u
, "memory.min", c
->memory_min
);
1138 cgroup_apply_unified_memory_limit(u
, "memory.low", c
->memory_low
);
1139 cgroup_apply_unified_memory_limit(u
, "memory.high", c
->memory_high
);
1140 cgroup_apply_unified_memory_limit(u
, "memory.max", max
);
1141 cgroup_apply_unified_memory_limit(u
, "memory.swap.max", swap_max
);
1144 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
1147 if (cgroup_context_has_unified_memory_config(c
)) {
1148 val
= c
->memory_max
;
1149 log_cgroup_compat(u
, "Applying MemoryMax=%" PRIi64
" as MemoryLimit=", val
);
1151 val
= c
->memory_limit
;
1153 if (val
== CGROUP_LIMIT_MAX
)
1154 strncpy(buf
, "-1\n", sizeof(buf
));
1156 xsprintf(buf
, "%" PRIu64
"\n", val
);
1158 (void) set_attribute_and_warn(u
, "memory", "memory.limit_in_bytes", buf
);
1162 /* On cgroup v2 we can apply BPF everywhere. On cgroup v1 we apply it everywhere except for the root of
1163 * containers, where we leave this to the manager */
1164 if ((apply_mask
& (CGROUP_MASK_DEVICES
| CGROUP_MASK_BPF_DEVICES
)) &&
1165 (is_host_root
|| cg_all_unified() > 0 || !is_local_root
)) {
1166 _cleanup_(bpf_program_unrefp
) BPFProgram
*prog
= NULL
;
1167 CGroupDeviceAllow
*a
;
1169 if (cg_all_unified() > 0) {
1170 r
= cgroup_init_device_bpf(&prog
, c
->device_policy
, c
->device_allow
);
1172 log_unit_warning_errno(u
, r
, "Failed to initialize device control bpf program: %m");
1174 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore EINVAL
1177 if (c
->device_allow
|| c
->device_policy
!= CGROUP_AUTO
)
1178 r
= cg_set_attribute("devices", path
, "devices.deny", "a");
1180 r
= cg_set_attribute("devices", path
, "devices.allow", "a");
1182 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
, -EPERM
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1183 "Failed to reset devices.allow/devices.deny: %m");
1186 if (c
->device_policy
== CGROUP_CLOSED
||
1187 (c
->device_policy
== CGROUP_AUTO
&& c
->device_allow
)) {
1188 static const char auto_devices
[] =
1189 "/dev/null\0" "rwm\0"
1190 "/dev/zero\0" "rwm\0"
1191 "/dev/full\0" "rwm\0"
1192 "/dev/random\0" "rwm\0"
1193 "/dev/urandom\0" "rwm\0"
1194 "/dev/tty\0" "rwm\0"
1195 "/dev/ptmx\0" "rwm\0"
1196 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
1197 "/run/systemd/inaccessible/chr\0" "rwm\0"
1198 "/run/systemd/inaccessible/blk\0" "rwm\0";
1202 NULSTR_FOREACH_PAIR(x
, y
, auto_devices
)
1203 (void) whitelist_device(prog
, path
, x
, y
);
1205 /* PTS (/dev/pts) devices may not be duplicated, but accessed */
1206 (void) whitelist_major(prog
, path
, "pts", 'c', "rw");
1209 LIST_FOREACH(device_allow
, a
, c
->device_allow
) {
1225 if (path_startswith(a
->path
, "/dev/"))
1226 (void) whitelist_device(prog
, path
, a
->path
, acc
);
1227 else if ((val
= startswith(a
->path
, "block-")))
1228 (void) whitelist_major(prog
, path
, val
, 'b', acc
);
1229 else if ((val
= startswith(a
->path
, "char-")))
1230 (void) whitelist_major(prog
, path
, val
, 'c', acc
);
1232 log_unit_debug(u
, "Ignoring device '%s' while writing cgroup attribute.", a
->path
);
1235 r
= cgroup_apply_device_bpf(u
, prog
, c
->device_policy
, c
->device_allow
);
1237 static bool warned
= false;
1239 log_full_errno(warned
? LOG_DEBUG
: LOG_WARNING
, r
,
1240 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1241 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1242 "(This warning is only shown for the first loaded unit using device ACL.)", u
->id
);
1248 if (apply_mask
& CGROUP_MASK_PIDS
) {
1251 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1252 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1253 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1254 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1255 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1256 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1257 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1258 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1259 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1260 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1261 * which is desirable so that there's an offical way to release control of the sysctl from
1262 * systemd: set the limit to unbounded and reload. */
1264 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1265 u
->manager
->sysctl_pid_max_changed
= true;
1266 r
= procfs_tasks_set_limit(c
->tasks_max
);
1267 } else if (u
->manager
->sysctl_pid_max_changed
)
1268 r
= procfs_tasks_set_limit(TASKS_MAX
);
1272 log_unit_full(u
, LOG_LEVEL_CGROUP_WRITE(r
), r
,
1273 "Failed to write to tasks limit sysctls: %m");
1276 /* The attribute itself is not available on the host root cgroup, and in the container case we want to
1277 * leave it for the container manager. */
1278 if (!is_local_root
) {
1279 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1280 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
1282 sprintf(buf
, "%" PRIu64
"\n", c
->tasks_max
);
1283 (void) set_attribute_and_warn(u
, "pids", "pids.max", buf
);
1285 (void) set_attribute_and_warn(u
, "pids", "pids.max", "max\n");
1289 if (apply_mask
& CGROUP_MASK_BPF_FIREWALL
)
1290 cgroup_apply_firewall(u
);
1293 static bool unit_get_needs_bpf_firewall(Unit
*u
) {
1298 c
= unit_get_cgroup_context(u
);
1302 if (c
->ip_accounting
||
1303 c
->ip_address_allow
||
1307 /* If any parent slice has an IP access list defined, it applies too */
1308 for (p
= UNIT_DEREF(u
->slice
); p
; p
= UNIT_DEREF(p
->slice
)) {
1309 c
= unit_get_cgroup_context(p
);
1313 if (c
->ip_address_allow
||
1321 static CGroupMask
cgroup_context_get_mask(CGroupContext
*c
) {
1322 CGroupMask mask
= 0;
1324 /* Figure out which controllers we need, based on the cgroup context object */
1326 if (c
->cpu_accounting
)
1327 mask
|= get_cpu_accounting_mask();
1329 if (cgroup_context_has_cpu_weight(c
) ||
1330 cgroup_context_has_cpu_shares(c
) ||
1331 c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
)
1332 mask
|= CGROUP_MASK_CPU
;
1334 if (cgroup_context_has_io_config(c
) || cgroup_context_has_blockio_config(c
))
1335 mask
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
1337 if (c
->memory_accounting
||
1338 c
->memory_limit
!= CGROUP_LIMIT_MAX
||
1339 cgroup_context_has_unified_memory_config(c
))
1340 mask
|= CGROUP_MASK_MEMORY
;
1342 if (c
->device_allow
||
1343 c
->device_policy
!= CGROUP_AUTO
)
1344 mask
|= CGROUP_MASK_DEVICES
| CGROUP_MASK_BPF_DEVICES
;
1346 if (c
->tasks_accounting
||
1347 c
->tasks_max
!= CGROUP_LIMIT_MAX
)
1348 mask
|= CGROUP_MASK_PIDS
;
1350 return CGROUP_MASK_EXTEND_JOINED(mask
);
1353 static CGroupMask
unit_get_bpf_mask(Unit
*u
) {
1354 CGroupMask mask
= 0;
1356 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
1359 if (unit_get_needs_bpf_firewall(u
))
1360 mask
|= CGROUP_MASK_BPF_FIREWALL
;
1365 CGroupMask
unit_get_own_mask(Unit
*u
) {
1368 /* Returns the mask of controllers the unit needs for itself. If a unit is not properly loaded, return an empty
1369 * mask, as we shouldn't reflect it in the cgroup hierarchy then. */
1371 if (u
->load_state
!= UNIT_LOADED
)
1374 c
= unit_get_cgroup_context(u
);
1378 return (cgroup_context_get_mask(c
) | unit_get_bpf_mask(u
) | unit_get_delegate_mask(u
)) & ~unit_get_ancestor_disable_mask(u
);
1381 CGroupMask
unit_get_delegate_mask(Unit
*u
) {
1384 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1385 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
1387 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1389 if (!unit_cgroup_delegate(u
))
1392 if (cg_all_unified() <= 0) {
1395 e
= unit_get_exec_context(u
);
1396 if (e
&& !exec_context_maintains_privileges(e
))
1400 assert_se(c
= unit_get_cgroup_context(u
));
1401 return CGROUP_MASK_EXTEND_JOINED(c
->delegate_controllers
);
1404 CGroupMask
unit_get_members_mask(Unit
*u
) {
1407 /* Returns the mask of controllers all of the unit's children require, merged */
1409 if (u
->cgroup_members_mask_valid
)
1410 return u
->cgroup_members_mask
; /* Use cached value if possible */
1412 u
->cgroup_members_mask
= 0;
1414 if (u
->type
== UNIT_SLICE
) {
1419 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
1420 if (UNIT_DEREF(member
->slice
) == u
)
1421 u
->cgroup_members_mask
|= unit_get_subtree_mask(member
); /* note that this calls ourselves again, for the children */
1425 u
->cgroup_members_mask_valid
= true;
1426 return u
->cgroup_members_mask
;
1429 CGroupMask
unit_get_siblings_mask(Unit
*u
) {
1432 /* Returns the mask of controllers all of the unit's siblings
1433 * require, i.e. the members mask of the unit's parent slice
1434 * if there is one. */
1436 if (UNIT_ISSET(u
->slice
))
1437 return unit_get_members_mask(UNIT_DEREF(u
->slice
));
1439 return unit_get_subtree_mask(u
); /* we are the top-level slice */
1442 CGroupMask
unit_get_disable_mask(Unit
*u
) {
1445 c
= unit_get_cgroup_context(u
);
1449 return c
->disable_controllers
;
1452 CGroupMask
unit_get_ancestor_disable_mask(Unit
*u
) {
1456 mask
= unit_get_disable_mask(u
);
1458 /* Returns the mask of controllers which are marked as forcibly
1459 * disabled in any ancestor unit or the unit in question. */
1461 if (UNIT_ISSET(u
->slice
))
1462 mask
|= unit_get_ancestor_disable_mask(UNIT_DEREF(u
->slice
));
1467 CGroupMask
unit_get_subtree_mask(Unit
*u
) {
1469 /* Returns the mask of this subtree, meaning of the group
1470 * itself and its children. */
1472 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
1475 CGroupMask
unit_get_target_mask(Unit
*u
) {
1478 /* This returns the cgroup mask of all controllers to enable
1479 * for a specific cgroup, i.e. everything it needs itself,
1480 * plus all that its children need, plus all that its siblings
1481 * need. This is primarily useful on the legacy cgroup
1482 * hierarchy, where we need to duplicate each cgroup in each
1483 * hierarchy that shall be enabled for it. */
1485 mask
= unit_get_own_mask(u
) | unit_get_members_mask(u
) | unit_get_siblings_mask(u
);
1486 mask
&= u
->manager
->cgroup_supported
;
1487 mask
&= ~unit_get_ancestor_disable_mask(u
);
1492 CGroupMask
unit_get_enable_mask(Unit
*u
) {
1495 /* This returns the cgroup mask of all controllers to enable
1496 * for the children of a specific cgroup. This is primarily
1497 * useful for the unified cgroup hierarchy, where each cgroup
1498 * controls which controllers are enabled for its children. */
1500 mask
= unit_get_members_mask(u
);
1501 mask
&= u
->manager
->cgroup_supported
;
1502 mask
&= ~unit_get_ancestor_disable_mask(u
);
1507 void unit_invalidate_cgroup_members_masks(Unit
*u
) {
1510 /* Recurse invalidate the member masks cache all the way up the tree */
1511 u
->cgroup_members_mask_valid
= false;
1513 if (UNIT_ISSET(u
->slice
))
1514 unit_invalidate_cgroup_members_masks(UNIT_DEREF(u
->slice
));
1517 const char *unit_get_realized_cgroup_path(Unit
*u
, CGroupMask mask
) {
1519 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
1523 if (u
->cgroup_path
&&
1524 u
->cgroup_realized
&&
1525 FLAGS_SET(u
->cgroup_realized_mask
, mask
))
1526 return u
->cgroup_path
;
1528 u
= UNIT_DEREF(u
->slice
);
1534 static const char *migrate_callback(CGroupMask mask
, void *userdata
) {
1535 return unit_get_realized_cgroup_path(userdata
, mask
);
1538 char *unit_default_cgroup_path(const Unit
*u
) {
1539 _cleanup_free_
char *escaped
= NULL
, *slice
= NULL
;
1544 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1545 return strdup(u
->manager
->cgroup_root
);
1547 if (UNIT_ISSET(u
->slice
) && !unit_has_name(UNIT_DEREF(u
->slice
), SPECIAL_ROOT_SLICE
)) {
1548 r
= cg_slice_to_path(UNIT_DEREF(u
->slice
)->id
, &slice
);
1553 escaped
= cg_escape(u
->id
);
1558 return strjoin(u
->manager
->cgroup_root
, "/", slice
, "/",
1561 return strjoin(u
->manager
->cgroup_root
, "/", escaped
);
1564 int unit_set_cgroup_path(Unit
*u
, const char *path
) {
1565 _cleanup_free_
char *p
= NULL
;
1577 if (streq_ptr(u
->cgroup_path
, p
))
1581 r
= hashmap_put(u
->manager
->cgroup_unit
, p
, u
);
1586 unit_release_cgroup(u
);
1588 u
->cgroup_path
= TAKE_PTR(p
);
1593 int unit_watch_cgroup(Unit
*u
) {
1594 _cleanup_free_
char *events
= NULL
;
1599 if (!u
->cgroup_path
)
1602 if (u
->cgroup_inotify_wd
>= 0)
1605 /* Only applies to the unified hierarchy */
1606 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
1608 return log_error_errno(r
, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1612 /* Don't watch the root slice, it's pointless. */
1613 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1616 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_inotify_wd_unit
, &trivial_hash_ops
);
1620 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events", &events
);
1624 u
->cgroup_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
1625 if (u
->cgroup_inotify_wd
< 0) {
1627 if (errno
== ENOENT
) /* If the directory is already
1628 * gone we don't need to track
1629 * it, so this is not an error */
1632 return log_unit_error_errno(u
, errno
, "Failed to add inotify watch descriptor for control group %s: %m", u
->cgroup_path
);
1635 r
= hashmap_put(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
), u
);
1637 return log_unit_error_errno(u
, r
, "Failed to add inotify watch descriptor to hash map: %m");
1642 int unit_pick_cgroup_path(Unit
*u
) {
1643 _cleanup_free_
char *path
= NULL
;
1651 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1654 path
= unit_default_cgroup_path(u
);
1658 r
= unit_set_cgroup_path(u
, path
);
1660 return log_unit_error_errno(u
, r
, "Control group %s exists already.", path
);
1662 return log_unit_error_errno(u
, r
, "Failed to set unit's control group path to %s: %m", path
);
1667 static int unit_create_cgroup(
1669 CGroupMask target_mask
,
1670 CGroupMask enable_mask
,
1671 ManagerState state
) {
1678 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1681 /* Figure out our cgroup path */
1682 r
= unit_pick_cgroup_path(u
);
1686 /* First, create our own group */
1687 r
= cg_create_everywhere(u
->manager
->cgroup_supported
, target_mask
, u
->cgroup_path
);
1689 return log_unit_error_errno(u
, r
, "Failed to create cgroup %s: %m", u
->cgroup_path
);
1692 /* Start watching it */
1693 (void) unit_watch_cgroup(u
);
1695 /* Preserve enabled controllers in delegated units, adjust others. */
1696 if (created
|| !u
->cgroup_realized
|| !unit_cgroup_delegate(u
)) {
1697 CGroupMask result_mask
= 0;
1699 /* Enable all controllers we need */
1700 r
= cg_enable_everywhere(u
->manager
->cgroup_supported
, enable_mask
, u
->cgroup_path
, &result_mask
);
1702 log_unit_warning_errno(u
, r
, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", u
->cgroup_path
);
1704 /* If we just turned off a controller, this might release the controller for our parent too, let's
1705 * enqueue the parent for re-realization in that case again. */
1706 if (UNIT_ISSET(u
->slice
)) {
1707 CGroupMask turned_off
;
1709 turned_off
= (u
->cgroup_realized
? u
->cgroup_enabled_mask
& ~result_mask
: 0);
1710 if (turned_off
!= 0) {
1713 /* Force the parent to propagate the enable mask to the kernel again, by invalidating
1714 * the controller we just turned off. */
1716 for (parent
= UNIT_DEREF(u
->slice
); parent
; parent
= UNIT_DEREF(parent
->slice
))
1717 unit_invalidate_cgroup(parent
, turned_off
);
1721 /* Remember what's actually enabled now */
1722 u
->cgroup_enabled_mask
= result_mask
;
1725 /* Keep track that this is now realized */
1726 u
->cgroup_realized
= true;
1727 u
->cgroup_realized_mask
= target_mask
;
1729 if (u
->type
!= UNIT_SLICE
&& !unit_cgroup_delegate(u
)) {
1731 /* Then, possibly move things over, but not if
1732 * subgroups may contain processes, which is the case
1733 * for slice and delegation units. */
1734 r
= cg_migrate_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->cgroup_path
, migrate_callback
, u
);
1736 log_unit_warning_errno(u
, r
, "Failed to migrate cgroup from to %s, ignoring: %m", u
->cgroup_path
);
1739 /* Set attributes */
1740 cgroup_context_apply(u
, target_mask
, state
);
1741 cgroup_xattr_apply(u
);
1746 static int unit_attach_pid_to_cgroup_via_bus(Unit
*u
, pid_t pid
, const char *suffix_path
) {
1747 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1753 if (MANAGER_IS_SYSTEM(u
->manager
))
1756 if (!u
->manager
->system_bus
)
1759 if (!u
->cgroup_path
)
1762 /* Determine this unit's cgroup path relative to our cgroup root */
1763 pp
= path_startswith(u
->cgroup_path
, u
->manager
->cgroup_root
);
1767 pp
= strjoina("/", pp
, suffix_path
);
1768 path_simplify(pp
, false);
1770 r
= sd_bus_call_method(u
->manager
->system_bus
,
1771 "org.freedesktop.systemd1",
1772 "/org/freedesktop/systemd1",
1773 "org.freedesktop.systemd1.Manager",
1774 "AttachProcessesToUnit",
1777 NULL
/* empty unit name means client's unit, i.e. us */, pp
, 1, (uint32_t) pid
);
1779 return log_unit_debug_errno(u
, r
, "Failed to attach unit process " PID_FMT
" via the bus: %s", pid
, bus_error_message(&error
, r
));
1784 int unit_attach_pids_to_cgroup(Unit
*u
, Set
*pids
, const char *suffix_path
) {
1785 CGroupMask delegated_mask
;
1793 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1796 if (set_isempty(pids
))
1799 r
= unit_realize_cgroup(u
);
1803 if (isempty(suffix_path
))
1806 p
= strjoina(u
->cgroup_path
, "/", suffix_path
);
1808 delegated_mask
= unit_get_delegate_mask(u
);
1811 SET_FOREACH(pidp
, pids
, i
) {
1812 pid_t pid
= PTR_TO_PID(pidp
);
1815 /* First, attach the PID to the main cgroup hierarchy */
1816 q
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, p
, pid
);
1818 log_unit_debug_errno(u
, q
, "Couldn't move process " PID_FMT
" to requested cgroup '%s': %m", pid
, p
);
1820 if (MANAGER_IS_USER(u
->manager
) && IN_SET(q
, -EPERM
, -EACCES
)) {
1823 /* If we are in a user instance, and we can't move the process ourselves due to
1824 * permission problems, let's ask the system instance about it instead. Since it's more
1825 * privileged it might be able to move the process across the leaves of a subtree who's
1826 * top node is not owned by us. */
1828 z
= unit_attach_pid_to_cgroup_via_bus(u
, pid
, suffix_path
);
1830 log_unit_debug_errno(u
, z
, "Couldn't move process " PID_FMT
" to requested cgroup '%s' via the system bus either: %m", pid
, p
);
1832 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1836 r
= q
; /* Remember first error */
1841 q
= cg_all_unified();
1847 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
1848 * innermost realized one */
1850 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1851 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1852 const char *realized
;
1854 if (!(u
->manager
->cgroup_supported
& bit
))
1857 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
1858 if (delegated_mask
& u
->cgroup_realized_mask
& bit
) {
1859 q
= cg_attach(cgroup_controller_to_string(c
), p
, pid
);
1861 continue; /* Success! */
1863 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",
1864 pid
, p
, cgroup_controller_to_string(c
));
1867 /* So this controller is either not delegate or realized, or something else weird happened. In
1868 * that case let's attach the PID at least to the closest cgroup up the tree that is
1870 realized
= unit_get_realized_cgroup_path(u
, bit
);
1872 continue; /* Not even realized in the root slice? Then let's not bother */
1874 q
= cg_attach(cgroup_controller_to_string(c
), realized
, pid
);
1876 log_unit_debug_errno(u
, q
, "Failed to attach PID " PID_FMT
" to realized cgroup %s in controller %s, ignoring: %m",
1877 pid
, realized
, cgroup_controller_to_string(c
));
1884 static bool unit_has_mask_realized(
1886 CGroupMask target_mask
,
1887 CGroupMask enable_mask
) {
1891 /* Returns true if this unit is fully realized. We check four things:
1893 * 1. Whether the cgroup was created at all
1894 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
1895 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
1896 * 4. Whether the invalidation mask is currently zero
1898 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
1899 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
1900 * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
1901 * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
1902 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
1903 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
1904 * simply don't matter. */
1906 return u
->cgroup_realized
&&
1907 ((u
->cgroup_realized_mask
^ target_mask
) & CGROUP_MASK_V1
) == 0 &&
1908 ((u
->cgroup_enabled_mask
^ enable_mask
) & CGROUP_MASK_V2
) == 0 &&
1909 u
->cgroup_invalidated_mask
== 0;
1912 static bool unit_has_mask_disables_realized(
1914 CGroupMask target_mask
,
1915 CGroupMask enable_mask
) {
1919 /* Returns true if all controllers which should be disabled are indeed disabled.
1921 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
1922 * already removed. */
1924 return !u
->cgroup_realized
||
1925 (FLAGS_SET(u
->cgroup_realized_mask
, target_mask
& CGROUP_MASK_V1
) &&
1926 FLAGS_SET(u
->cgroup_enabled_mask
, enable_mask
& CGROUP_MASK_V2
));
1929 static bool unit_has_mask_enables_realized(
1931 CGroupMask target_mask
,
1932 CGroupMask enable_mask
) {
1936 /* Returns true if all controllers which should be enabled are indeed enabled.
1938 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
1939 * we want to add is already added. */
1941 return u
->cgroup_realized
&&
1942 ((u
->cgroup_realized_mask
| target_mask
) & CGROUP_MASK_V1
) == (u
->cgroup_realized_mask
& CGROUP_MASK_V1
) &&
1943 ((u
->cgroup_enabled_mask
| enable_mask
) & CGROUP_MASK_V2
) == (u
->cgroup_enabled_mask
& CGROUP_MASK_V2
);
1946 void unit_add_to_cgroup_realize_queue(Unit
*u
) {
1949 if (u
->in_cgroup_realize_queue
)
1952 LIST_PREPEND(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1953 u
->in_cgroup_realize_queue
= true;
1956 static void unit_remove_from_cgroup_realize_queue(Unit
*u
) {
1959 if (!u
->in_cgroup_realize_queue
)
1962 LIST_REMOVE(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1963 u
->in_cgroup_realize_queue
= false;
1966 /* Controllers can only be enabled breadth-first, from the root of the
1967 * hierarchy downwards to the unit in question. */
1968 static int unit_realize_cgroup_now_enable(Unit
*u
, ManagerState state
) {
1969 CGroupMask target_mask
, enable_mask
, new_target_mask
, new_enable_mask
;
1974 /* First go deal with this unit's parent, or we won't be able to enable
1975 * any new controllers at this layer. */
1976 if (UNIT_ISSET(u
->slice
)) {
1977 r
= unit_realize_cgroup_now_enable(UNIT_DEREF(u
->slice
), state
);
1982 target_mask
= unit_get_target_mask(u
);
1983 enable_mask
= unit_get_enable_mask(u
);
1985 /* We can only enable in this direction, don't try to disable anything.
1987 if (unit_has_mask_enables_realized(u
, target_mask
, enable_mask
))
1990 new_target_mask
= u
->cgroup_realized_mask
| target_mask
;
1991 new_enable_mask
= u
->cgroup_enabled_mask
| enable_mask
;
1993 return unit_create_cgroup(u
, new_target_mask
, new_enable_mask
, state
);
1996 /* Controllers can only be disabled depth-first, from the leaves of the
1997 * hierarchy upwards to the unit in question. */
1998 static int unit_realize_cgroup_now_disable(Unit
*u
, ManagerState state
) {
2005 if (u
->type
!= UNIT_SLICE
)
2008 HASHMAP_FOREACH_KEY(v
, m
, u
->dependencies
[UNIT_BEFORE
], i
) {
2009 CGroupMask target_mask
, enable_mask
, new_target_mask
, new_enable_mask
;
2012 if (UNIT_DEREF(m
->slice
) != u
)
2015 /* The cgroup for this unit might not actually be fully
2016 * realised yet, in which case it isn't holding any controllers
2018 if (!m
->cgroup_path
)
2021 /* We must disable those below us first in order to release the
2023 if (m
->type
== UNIT_SLICE
)
2024 (void) unit_realize_cgroup_now_disable(m
, state
);
2026 target_mask
= unit_get_target_mask(m
);
2027 enable_mask
= unit_get_enable_mask(m
);
2029 /* We can only disable in this direction, don't try to enable
2031 if (unit_has_mask_disables_realized(m
, target_mask
, enable_mask
))
2034 new_target_mask
= m
->cgroup_realized_mask
& target_mask
;
2035 new_enable_mask
= m
->cgroup_enabled_mask
& enable_mask
;
2037 r
= unit_create_cgroup(m
, new_target_mask
, new_enable_mask
, state
);
2045 /* Check if necessary controllers and attributes for a unit are in place.
2047 * - If so, do nothing.
2048 * - If not, create paths, move processes over, and set attributes.
2050 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
2051 * a depth-first way. As such the process looks like this:
2053 * Suppose we have a cgroup hierarchy which looks like this:
2066 * 1. We want to realise cgroup "d" now.
2067 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
2068 * 3. cgroup "k" just started requesting the memory controller.
2070 * To make this work we must do the following in order:
2072 * 1. Disable CPU controller in k, j
2073 * 2. Disable CPU controller in d
2074 * 3. Enable memory controller in root
2075 * 4. Enable memory controller in a
2076 * 5. Enable memory controller in d
2077 * 6. Enable memory controller in k
2079 * Notice that we need to touch j in one direction, but not the other. We also
2080 * don't go beyond d when disabling -- it's up to "a" to get realized if it
2081 * wants to disable further. The basic rules are therefore:
2083 * - If you're disabling something, you need to realise all of the cgroups from
2084 * your recursive descendants to the root. This starts from the leaves.
2085 * - If you're enabling something, you need to realise from the root cgroup
2086 * downwards, but you don't need to iterate your recursive descendants.
2088 * Returns 0 on success and < 0 on failure. */
2089 static int unit_realize_cgroup_now(Unit
*u
, ManagerState state
) {
2090 CGroupMask target_mask
, enable_mask
;
2095 unit_remove_from_cgroup_realize_queue(u
);
2097 target_mask
= unit_get_target_mask(u
);
2098 enable_mask
= unit_get_enable_mask(u
);
2100 if (unit_has_mask_realized(u
, target_mask
, enable_mask
))
2103 /* Disable controllers below us, if there are any */
2104 r
= unit_realize_cgroup_now_disable(u
, state
);
2108 /* Enable controllers above us, if there are any */
2109 if (UNIT_ISSET(u
->slice
)) {
2110 r
= unit_realize_cgroup_now_enable(UNIT_DEREF(u
->slice
), state
);
2115 /* Now actually deal with the cgroup we were trying to realise and set attributes */
2116 r
= unit_create_cgroup(u
, target_mask
, enable_mask
, state
);
2120 /* Now, reset the invalidation mask */
2121 u
->cgroup_invalidated_mask
= 0;
2125 unsigned manager_dispatch_cgroup_realize_queue(Manager
*m
) {
2133 state
= manager_state(m
);
2135 while ((i
= m
->cgroup_realize_queue
)) {
2136 assert(i
->in_cgroup_realize_queue
);
2138 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i
))) {
2139 /* Maybe things changed, and the unit is not actually active anymore? */
2140 unit_remove_from_cgroup_realize_queue(i
);
2144 r
= unit_realize_cgroup_now(i
, state
);
2146 log_warning_errno(r
, "Failed to realize cgroups for queued unit %s, ignoring: %m", i
->id
);
2154 static void unit_add_siblings_to_cgroup_realize_queue(Unit
*u
) {
2157 /* This adds the siblings of the specified unit and the
2158 * siblings of all parent units to the cgroup queue. (But
2159 * neither the specified unit itself nor the parents.) */
2161 while ((slice
= UNIT_DEREF(u
->slice
))) {
2166 HASHMAP_FOREACH_KEY(v
, m
, u
->dependencies
[UNIT_BEFORE
], i
) {
2167 /* Skip units that have a dependency on the slice
2168 * but aren't actually in it. */
2169 if (UNIT_DEREF(m
->slice
) != slice
)
2172 /* No point in doing cgroup application for units
2173 * without active processes. */
2174 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m
)))
2177 /* If the unit doesn't need any new controllers
2178 * and has current ones realized, it doesn't need
2180 if (unit_has_mask_realized(m
,
2181 unit_get_target_mask(m
),
2182 unit_get_enable_mask(m
)))
2185 unit_add_to_cgroup_realize_queue(m
);
2192 int unit_realize_cgroup(Unit
*u
) {
2195 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2198 /* So, here's the deal: when realizing the cgroups for this
2199 * unit, we need to first create all parents, but there's more
2200 * actually: for the weight-based controllers we also need to
2201 * make sure that all our siblings (i.e. units that are in the
2202 * same slice as we are) have cgroups, too. Otherwise, things
2203 * would become very uneven as each of their processes would
2204 * get as much resources as all our group together. This call
2205 * will synchronously create the parent cgroups, but will
2206 * defer work on the siblings to the next event loop
2209 /* Add all sibling slices to the cgroup queue. */
2210 unit_add_siblings_to_cgroup_realize_queue(u
);
2212 /* And realize this one now (and apply the values) */
2213 return unit_realize_cgroup_now(u
, manager_state(u
->manager
));
2216 void unit_release_cgroup(Unit
*u
) {
2219 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
2220 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
2222 if (u
->cgroup_path
) {
2223 (void) hashmap_remove(u
->manager
->cgroup_unit
, u
->cgroup_path
);
2224 u
->cgroup_path
= mfree(u
->cgroup_path
);
2227 if (u
->cgroup_inotify_wd
>= 0) {
2228 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_inotify_wd
) < 0)
2229 log_unit_debug_errno(u
, errno
, "Failed to remove cgroup inotify watch %i for %s, ignoring: %m", u
->cgroup_inotify_wd
, u
->id
);
2231 (void) hashmap_remove(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
));
2232 u
->cgroup_inotify_wd
= -1;
2236 void unit_prune_cgroup(Unit
*u
) {
2242 /* Removes the cgroup, if empty and possible, and stops watching it. */
2244 if (!u
->cgroup_path
)
2247 (void) unit_get_cpu_usage(u
, NULL
); /* Cache the last CPU usage value before we destroy the cgroup */
2249 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
2251 r
= cg_trim_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, !is_root_slice
);
2253 log_unit_debug_errno(u
, r
, "Failed to destroy cgroup %s, ignoring: %m", u
->cgroup_path
);
2260 unit_release_cgroup(u
);
2262 u
->cgroup_realized
= false;
2263 u
->cgroup_realized_mask
= 0;
2264 u
->cgroup_enabled_mask
= 0;
2266 u
->bpf_device_control_installed
= bpf_program_unref(u
->bpf_device_control_installed
);
2269 int unit_search_main_pid(Unit
*u
, pid_t
*ret
) {
2270 _cleanup_fclose_
FILE *f
= NULL
;
2271 pid_t pid
= 0, npid
, mypid
;
2277 if (!u
->cgroup_path
)
2280 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, &f
);
2284 mypid
= getpid_cached();
2285 while (cg_read_pid(f
, &npid
) > 0) {
2291 /* Ignore processes that aren't our kids */
2292 if (get_process_ppid(npid
, &ppid
) >= 0 && ppid
!= mypid
)
2296 /* Dang, there's more than one daemonized PID
2297 in this group, so we don't know what process
2298 is the main process. */
2309 static int unit_watch_pids_in_path(Unit
*u
, const char *path
) {
2310 _cleanup_closedir_
DIR *d
= NULL
;
2311 _cleanup_fclose_
FILE *f
= NULL
;
2317 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
);
2323 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
2324 r
= unit_watch_pid(u
, pid
);
2325 if (r
< 0 && ret
>= 0)
2329 if (r
< 0 && ret
>= 0)
2333 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
2340 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
2341 _cleanup_free_
char *p
= NULL
;
2343 p
= strjoin(path
, "/", fn
);
2349 r
= unit_watch_pids_in_path(u
, p
);
2350 if (r
< 0 && ret
>= 0)
2354 if (r
< 0 && ret
>= 0)
2361 int unit_synthesize_cgroup_empty_event(Unit
*u
) {
2366 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
2367 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
2368 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
2370 if (!u
->cgroup_path
)
2373 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2376 if (r
> 0) /* On unified we have reliable notifications, and don't need this */
2379 if (!set_isempty(u
->pids
))
2382 unit_add_to_cgroup_empty_queue(u
);
2386 int unit_watch_all_pids(Unit
*u
) {
2391 /* Adds all PIDs from our cgroup to the set of PIDs we
2392 * watch. This is a fallback logic for cases where we do not
2393 * get reliable cgroup empty notifications: we try to use
2394 * SIGCHLD as replacement. */
2396 if (!u
->cgroup_path
)
2399 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2402 if (r
> 0) /* On unified we can use proper notifications */
2405 return unit_watch_pids_in_path(u
, u
->cgroup_path
);
2408 static int on_cgroup_empty_event(sd_event_source
*s
, void *userdata
) {
2409 Manager
*m
= userdata
;
2416 u
= m
->cgroup_empty_queue
;
2420 assert(u
->in_cgroup_empty_queue
);
2421 u
->in_cgroup_empty_queue
= false;
2422 LIST_REMOVE(cgroup_empty_queue
, m
->cgroup_empty_queue
, u
);
2424 if (m
->cgroup_empty_queue
) {
2425 /* More stuff queued, let's make sure we remain enabled */
2426 r
= sd_event_source_set_enabled(s
, SD_EVENT_ONESHOT
);
2428 log_debug_errno(r
, "Failed to reenable cgroup empty event source, ignoring: %m");
2431 unit_add_to_gc_queue(u
);
2433 if (UNIT_VTABLE(u
)->notify_cgroup_empty
)
2434 UNIT_VTABLE(u
)->notify_cgroup_empty(u
);
2439 void unit_add_to_cgroup_empty_queue(Unit
*u
) {
2444 /* Note that there are four different ways how cgroup empty events reach us:
2446 * 1. On the unified hierarchy we get an inotify event on the cgroup
2448 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2450 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2452 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2453 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2455 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2456 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2457 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2458 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2459 * case for scope units). */
2461 if (u
->in_cgroup_empty_queue
)
2464 /* Let's verify that the cgroup is really empty */
2465 if (!u
->cgroup_path
)
2467 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
2469 log_unit_debug_errno(u
, r
, "Failed to determine whether cgroup %s is empty: %m", u
->cgroup_path
);
2475 LIST_PREPEND(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
2476 u
->in_cgroup_empty_queue
= true;
2478 /* Trigger the defer event */
2479 r
= sd_event_source_set_enabled(u
->manager
->cgroup_empty_event_source
, SD_EVENT_ONESHOT
);
2481 log_debug_errno(r
, "Failed to enable cgroup empty event source: %m");
2484 static int on_cgroup_inotify_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
2485 Manager
*m
= userdata
;
2492 union inotify_event_buffer buffer
;
2493 struct inotify_event
*e
;
2496 l
= read(fd
, &buffer
, sizeof(buffer
));
2498 if (IN_SET(errno
, EINTR
, EAGAIN
))
2501 return log_error_errno(errno
, "Failed to read control group inotify events: %m");
2504 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
2508 /* Queue overflow has no watch descriptor */
2511 if (e
->mask
& IN_IGNORED
)
2512 /* The watch was just removed */
2515 u
= hashmap_get(m
->cgroup_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
2516 if (!u
) /* Not that inotify might deliver
2517 * events for a watch even after it
2518 * was removed, because it was queued
2519 * before the removal. Let's ignore
2520 * this here safely. */
2523 unit_add_to_cgroup_empty_queue(u
);
2528 static int cg_bpf_mask_supported(CGroupMask
*ret
) {
2529 CGroupMask mask
= 0;
2532 /* BPF-based firewall */
2533 r
= bpf_firewall_supported();
2535 mask
|= CGROUP_MASK_BPF_FIREWALL
;
2537 /* BPF-based device access control */
2538 r
= bpf_devices_supported();
2540 mask
|= CGROUP_MASK_BPF_DEVICES
;
2546 int manager_setup_cgroup(Manager
*m
) {
2547 _cleanup_free_
char *path
= NULL
;
2548 const char *scope_path
;
2556 /* 1. Determine hierarchy */
2557 m
->cgroup_root
= mfree(m
->cgroup_root
);
2558 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &m
->cgroup_root
);
2560 return log_error_errno(r
, "Cannot determine cgroup we are running in: %m");
2562 /* Chop off the init scope, if we are already located in it */
2563 e
= endswith(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2565 /* LEGACY: Also chop off the system slice if we are in
2566 * it. This is to support live upgrades from older systemd
2567 * versions where PID 1 was moved there. Also see
2568 * cg_get_root_path(). */
2569 if (!e
&& MANAGER_IS_SYSTEM(m
)) {
2570 e
= endswith(m
->cgroup_root
, "/" SPECIAL_SYSTEM_SLICE
);
2572 e
= endswith(m
->cgroup_root
, "/system"); /* even more legacy */
2577 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2578 * easily prepend it everywhere. */
2579 delete_trailing_chars(m
->cgroup_root
, "/");
2582 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, NULL
, &path
);
2584 return log_error_errno(r
, "Cannot find cgroup mount point: %m");
2586 r
= cg_unified_flush();
2588 return log_error_errno(r
, "Couldn't determine if we are running in the unified hierarchy: %m");
2590 all_unified
= cg_all_unified();
2591 if (all_unified
< 0)
2592 return log_error_errno(all_unified
, "Couldn't determine whether we are in all unified mode: %m");
2593 if (all_unified
> 0)
2594 log_debug("Unified cgroup hierarchy is located at %s.", path
);
2596 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2598 return log_error_errno(r
, "Failed to determine whether systemd's own controller is in unified mode: %m");
2600 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path
);
2602 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY
". File system hierarchy is at %s.", path
);
2605 /* 3. Allocate cgroup empty defer event source */
2606 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2607 r
= sd_event_add_defer(m
->event
, &m
->cgroup_empty_event_source
, on_cgroup_empty_event
, m
);
2609 return log_error_errno(r
, "Failed to create cgroup empty event source: %m");
2611 r
= sd_event_source_set_priority(m
->cgroup_empty_event_source
, SD_EVENT_PRIORITY_NORMAL
-5);
2613 return log_error_errno(r
, "Failed to set priority of cgroup empty event source: %m");
2615 r
= sd_event_source_set_enabled(m
->cgroup_empty_event_source
, SD_EVENT_OFF
);
2617 return log_error_errno(r
, "Failed to disable cgroup empty event source: %m");
2619 (void) sd_event_source_set_description(m
->cgroup_empty_event_source
, "cgroup-empty");
2621 /* 4. Install notifier inotify object, or agent */
2622 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0) {
2624 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2626 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2627 safe_close(m
->cgroup_inotify_fd
);
2629 m
->cgroup_inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
2630 if (m
->cgroup_inotify_fd
< 0)
2631 return log_error_errno(errno
, "Failed to create control group inotify object: %m");
2633 r
= sd_event_add_io(m
->event
, &m
->cgroup_inotify_event_source
, m
->cgroup_inotify_fd
, EPOLLIN
, on_cgroup_inotify_event
, m
);
2635 return log_error_errno(r
, "Failed to watch control group inotify object: %m");
2637 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
2638 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2639 r
= sd_event_source_set_priority(m
->cgroup_inotify_event_source
, SD_EVENT_PRIORITY_NORMAL
-4);
2641 return log_error_errno(r
, "Failed to set priority of inotify event source: %m");
2643 (void) sd_event_source_set_description(m
->cgroup_inotify_event_source
, "cgroup-inotify");
2645 } else if (MANAGER_IS_SYSTEM(m
) && manager_owns_host_root_cgroup(m
) && !MANAGER_IS_TEST_RUN(m
)) {
2647 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2648 * since it does not generate events when control groups with children run empty. */
2650 r
= cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER
, SYSTEMD_CGROUP_AGENT_PATH
);
2652 log_warning_errno(r
, "Failed to install release agent, ignoring: %m");
2654 log_debug("Installed release agent.");
2656 log_debug("Release agent already installed.");
2659 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2660 scope_path
= strjoina(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2661 r
= cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2663 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2664 r
= cg_migrate(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2666 log_warning_errno(r
, "Couldn't move remaining userspace processes, ignoring: %m");
2668 /* 6. And pin it, so that it cannot be unmounted */
2669 safe_close(m
->pin_cgroupfs_fd
);
2670 m
->pin_cgroupfs_fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
2671 if (m
->pin_cgroupfs_fd
< 0)
2672 return log_error_errno(errno
, "Failed to open pin file: %m");
2674 } else if (!MANAGER_IS_TEST_RUN(m
))
2675 return log_error_errno(r
, "Failed to create %s control group: %m", scope_path
);
2677 /* 7. Always enable hierarchical support if it exists... */
2678 if (!all_unified
&& !MANAGER_IS_TEST_RUN(m
))
2679 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
2681 /* 8. Figure out which controllers are supported */
2682 r
= cg_mask_supported(&m
->cgroup_supported
);
2684 return log_error_errno(r
, "Failed to determine supported controllers: %m");
2686 /* 9. Figure out which bpf-based pseudo-controllers are supported */
2687 r
= cg_bpf_mask_supported(&mask
);
2689 return log_error_errno(r
, "Failed to determine supported bpf-based pseudo-controllers: %m");
2690 m
->cgroup_supported
|= mask
;
2692 /* 10. Log which controllers are supported */
2693 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++)
2694 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c
), yes_no(m
->cgroup_supported
& CGROUP_CONTROLLER_TO_MASK(c
)));
2699 void manager_shutdown_cgroup(Manager
*m
, bool delete) {
2702 /* We can't really delete the group, since we are in it. But
2704 if (delete && m
->cgroup_root
&& m
->test_run_flags
!= MANAGER_TEST_RUN_MINIMAL
)
2705 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, false);
2707 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2709 m
->cgroup_inotify_wd_unit
= hashmap_free(m
->cgroup_inotify_wd_unit
);
2711 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2712 m
->cgroup_inotify_fd
= safe_close(m
->cgroup_inotify_fd
);
2714 m
->pin_cgroupfs_fd
= safe_close(m
->pin_cgroupfs_fd
);
2716 m
->cgroup_root
= mfree(m
->cgroup_root
);
2719 Unit
* manager_get_unit_by_cgroup(Manager
*m
, const char *cgroup
) {
2726 u
= hashmap_get(m
->cgroup_unit
, cgroup
);
2730 p
= strdupa(cgroup
);
2734 e
= strrchr(p
, '/');
2736 return hashmap_get(m
->cgroup_unit
, SPECIAL_ROOT_SLICE
);
2740 u
= hashmap_get(m
->cgroup_unit
, p
);
2746 Unit
*manager_get_unit_by_pid_cgroup(Manager
*m
, pid_t pid
) {
2747 _cleanup_free_
char *cgroup
= NULL
;
2751 if (!pid_is_valid(pid
))
2754 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &cgroup
) < 0)
2757 return manager_get_unit_by_cgroup(m
, cgroup
);
2760 Unit
*manager_get_unit_by_pid(Manager
*m
, pid_t pid
) {
2765 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
2766 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
2767 * relevant one as children of the process will be assigned to that one, too, before all else. */
2769 if (!pid_is_valid(pid
))
2772 if (pid
== getpid_cached())
2773 return hashmap_get(m
->units
, SPECIAL_INIT_SCOPE
);
2775 u
= manager_get_unit_by_pid_cgroup(m
, pid
);
2779 u
= hashmap_get(m
->watch_pids
, PID_TO_PTR(pid
));
2783 array
= hashmap_get(m
->watch_pids
, PID_TO_PTR(-pid
));
2790 int manager_notify_cgroup_empty(Manager
*m
, const char *cgroup
) {
2796 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
2797 * or from the --system instance */
2799 log_debug("Got cgroup empty notification for: %s", cgroup
);
2801 u
= manager_get_unit_by_cgroup(m
, cgroup
);
2805 unit_add_to_cgroup_empty_queue(u
);
2809 int unit_get_memory_current(Unit
*u
, uint64_t *ret
) {
2810 _cleanup_free_
char *v
= NULL
;
2816 if (!UNIT_CGROUP_BOOL(u
, memory_accounting
))
2819 if (!u
->cgroup_path
)
2822 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2823 if (unit_has_host_root_cgroup(u
))
2824 return procfs_memory_get_used(ret
);
2826 if ((u
->cgroup_realized_mask
& CGROUP_MASK_MEMORY
) == 0)
2829 r
= cg_all_unified();
2833 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.current", &v
);
2835 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.usage_in_bytes", &v
);
2841 return safe_atou64(v
, ret
);
2844 int unit_get_tasks_current(Unit
*u
, uint64_t *ret
) {
2845 _cleanup_free_
char *v
= NULL
;
2851 if (!UNIT_CGROUP_BOOL(u
, tasks_accounting
))
2854 if (!u
->cgroup_path
)
2857 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2858 if (unit_has_host_root_cgroup(u
))
2859 return procfs_tasks_get_current(ret
);
2861 if ((u
->cgroup_realized_mask
& CGROUP_MASK_PIDS
) == 0)
2864 r
= cg_get_attribute("pids", u
->cgroup_path
, "pids.current", &v
);
2870 return safe_atou64(v
, ret
);
2873 static int unit_get_cpu_usage_raw(Unit
*u
, nsec_t
*ret
) {
2874 _cleanup_free_
char *v
= NULL
;
2881 if (!u
->cgroup_path
)
2884 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2885 if (unit_has_host_root_cgroup(u
))
2886 return procfs_cpu_get_usage(ret
);
2888 /* Requisite controllers for CPU accounting are not enabled */
2889 if ((get_cpu_accounting_mask() & ~u
->cgroup_realized_mask
) != 0)
2892 r
= cg_all_unified();
2896 _cleanup_free_
char *val
= NULL
;
2899 r
= cg_get_keyed_attribute("cpu", u
->cgroup_path
, "cpu.stat", STRV_MAKE("usage_usec"), &val
);
2900 if (IN_SET(r
, -ENOENT
, -ENXIO
))
2905 r
= safe_atou64(val
, &us
);
2909 ns
= us
* NSEC_PER_USEC
;
2911 r
= cg_get_attribute("cpuacct", u
->cgroup_path
, "cpuacct.usage", &v
);
2917 r
= safe_atou64(v
, &ns
);
2926 int unit_get_cpu_usage(Unit
*u
, nsec_t
*ret
) {
2932 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2933 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2934 * call this function with a NULL return value. */
2936 if (!UNIT_CGROUP_BOOL(u
, cpu_accounting
))
2939 r
= unit_get_cpu_usage_raw(u
, &ns
);
2940 if (r
== -ENODATA
&& u
->cpu_usage_last
!= NSEC_INFINITY
) {
2941 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2945 *ret
= u
->cpu_usage_last
;
2951 if (ns
> u
->cpu_usage_base
)
2952 ns
-= u
->cpu_usage_base
;
2956 u
->cpu_usage_last
= ns
;
2963 int unit_get_ip_accounting(
2965 CGroupIPAccountingMetric metric
,
2972 assert(metric
>= 0);
2973 assert(metric
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
);
2976 if (!UNIT_CGROUP_BOOL(u
, ip_accounting
))
2979 fd
= IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_INGRESS_PACKETS
) ?
2980 u
->ip_accounting_ingress_map_fd
:
2981 u
->ip_accounting_egress_map_fd
;
2985 if (IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_EGRESS_BYTES
))
2986 r
= bpf_firewall_read_accounting(fd
, &value
, NULL
);
2988 r
= bpf_firewall_read_accounting(fd
, NULL
, &value
);
2992 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
2993 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
2994 * ip_accounting_extra[] field, and add them in here transparently. */
2996 *ret
= value
+ u
->ip_accounting_extra
[metric
];
3001 int unit_reset_cpu_accounting(Unit
*u
) {
3007 u
->cpu_usage_last
= NSEC_INFINITY
;
3009 r
= unit_get_cpu_usage_raw(u
, &ns
);
3011 u
->cpu_usage_base
= 0;
3015 u
->cpu_usage_base
= ns
;
3019 int unit_reset_ip_accounting(Unit
*u
) {
3024 if (u
->ip_accounting_ingress_map_fd
>= 0)
3025 r
= bpf_firewall_reset_accounting(u
->ip_accounting_ingress_map_fd
);
3027 if (u
->ip_accounting_egress_map_fd
>= 0)
3028 q
= bpf_firewall_reset_accounting(u
->ip_accounting_egress_map_fd
);
3030 zero(u
->ip_accounting_extra
);
3032 return r
< 0 ? r
: q
;
3035 void unit_invalidate_cgroup(Unit
*u
, CGroupMask m
) {
3038 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
3044 /* always invalidate compat pairs together */
3045 if (m
& (CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
))
3046 m
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
3048 if (m
& (CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
))
3049 m
|= CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
;
3051 if (FLAGS_SET(u
->cgroup_invalidated_mask
, m
)) /* NOP? */
3054 u
->cgroup_invalidated_mask
|= m
;
3055 unit_add_to_cgroup_realize_queue(u
);
3058 void unit_invalidate_cgroup_bpf(Unit
*u
) {
3061 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
3064 if (u
->cgroup_invalidated_mask
& CGROUP_MASK_BPF_FIREWALL
) /* NOP? */
3067 u
->cgroup_invalidated_mask
|= CGROUP_MASK_BPF_FIREWALL
;
3068 unit_add_to_cgroup_realize_queue(u
);
3070 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
3071 * list of our children includes our own. */
3072 if (u
->type
== UNIT_SLICE
) {
3077 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
3078 if (UNIT_DEREF(member
->slice
) == u
)
3079 unit_invalidate_cgroup_bpf(member
);
3084 bool unit_cgroup_delegate(Unit
*u
) {
3089 if (!UNIT_VTABLE(u
)->can_delegate
)
3092 c
= unit_get_cgroup_context(u
);
3099 void manager_invalidate_startup_units(Manager
*m
) {
3105 SET_FOREACH(u
, m
->startup_units
, i
)
3106 unit_invalidate_cgroup(u
, CGROUP_MASK_CPU
|CGROUP_MASK_IO
|CGROUP_MASK_BLKIO
);
3109 static const char* const cgroup_device_policy_table
[_CGROUP_DEVICE_POLICY_MAX
] = {
3110 [CGROUP_AUTO
] = "auto",
3111 [CGROUP_CLOSED
] = "closed",
3112 [CGROUP_STRICT
] = "strict",
3115 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy
, CGroupDevicePolicy
);