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 "stdio-util.h"
23 #include "string-table.h"
24 #include "string-util.h"
27 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
29 bool manager_owns_root_cgroup(Manager
*m
) {
32 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
33 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
34 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
35 * we run in any kind of container virtualization. */
37 if (detect_container() > 0)
40 return empty_or_root(m
->cgroup_root
);
43 bool unit_has_root_cgroup(Unit
*u
) {
46 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
47 * the manager manages the root cgroup. */
49 if (!manager_owns_root_cgroup(u
->manager
))
52 return unit_has_name(u
, SPECIAL_ROOT_SLICE
);
55 static void cgroup_compat_warn(void) {
56 static bool cgroup_compat_warned
= false;
58 if (cgroup_compat_warned
)
61 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
62 "See cgroup-compat debug messages for details.");
64 cgroup_compat_warned
= true;
67 #define log_cgroup_compat(unit, fmt, ...) do { \
68 cgroup_compat_warn(); \
69 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
72 void cgroup_context_init(CGroupContext
*c
) {
75 /* Initialize everything to the kernel defaults, assuming the
76 * structure is preinitialized to 0 */
78 c
->cpu_weight
= CGROUP_WEIGHT_INVALID
;
79 c
->startup_cpu_weight
= CGROUP_WEIGHT_INVALID
;
80 c
->cpu_quota_per_sec_usec
= USEC_INFINITY
;
82 c
->cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
83 c
->startup_cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
85 c
->memory_high
= CGROUP_LIMIT_MAX
;
86 c
->memory_max
= CGROUP_LIMIT_MAX
;
87 c
->memory_swap_max
= CGROUP_LIMIT_MAX
;
89 c
->memory_limit
= CGROUP_LIMIT_MAX
;
91 c
->io_weight
= CGROUP_WEIGHT_INVALID
;
92 c
->startup_io_weight
= CGROUP_WEIGHT_INVALID
;
94 c
->blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
95 c
->startup_blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
97 c
->tasks_max
= (uint64_t) -1;
100 void cgroup_context_free_device_allow(CGroupContext
*c
, CGroupDeviceAllow
*a
) {
104 LIST_REMOVE(device_allow
, c
->device_allow
, a
);
109 void cgroup_context_free_io_device_weight(CGroupContext
*c
, CGroupIODeviceWeight
*w
) {
113 LIST_REMOVE(device_weights
, c
->io_device_weights
, w
);
118 void cgroup_context_free_io_device_latency(CGroupContext
*c
, CGroupIODeviceLatency
*l
) {
122 LIST_REMOVE(device_latencies
, c
->io_device_latencies
, l
);
127 void cgroup_context_free_io_device_limit(CGroupContext
*c
, CGroupIODeviceLimit
*l
) {
131 LIST_REMOVE(device_limits
, c
->io_device_limits
, l
);
136 void cgroup_context_free_blockio_device_weight(CGroupContext
*c
, CGroupBlockIODeviceWeight
*w
) {
140 LIST_REMOVE(device_weights
, c
->blockio_device_weights
, w
);
145 void cgroup_context_free_blockio_device_bandwidth(CGroupContext
*c
, CGroupBlockIODeviceBandwidth
*b
) {
149 LIST_REMOVE(device_bandwidths
, c
->blockio_device_bandwidths
, b
);
154 void cgroup_context_done(CGroupContext
*c
) {
157 while (c
->io_device_weights
)
158 cgroup_context_free_io_device_weight(c
, c
->io_device_weights
);
160 while (c
->io_device_latencies
)
161 cgroup_context_free_io_device_latency(c
, c
->io_device_latencies
);
163 while (c
->io_device_limits
)
164 cgroup_context_free_io_device_limit(c
, c
->io_device_limits
);
166 while (c
->blockio_device_weights
)
167 cgroup_context_free_blockio_device_weight(c
, c
->blockio_device_weights
);
169 while (c
->blockio_device_bandwidths
)
170 cgroup_context_free_blockio_device_bandwidth(c
, c
->blockio_device_bandwidths
);
172 while (c
->device_allow
)
173 cgroup_context_free_device_allow(c
, c
->device_allow
);
175 c
->ip_address_allow
= ip_address_access_free_all(c
->ip_address_allow
);
176 c
->ip_address_deny
= ip_address_access_free_all(c
->ip_address_deny
);
179 void cgroup_context_dump(CGroupContext
*c
, FILE* f
, const char *prefix
) {
180 CGroupIODeviceLimit
*il
;
181 CGroupIODeviceWeight
*iw
;
182 CGroupIODeviceLatency
*l
;
183 CGroupBlockIODeviceBandwidth
*b
;
184 CGroupBlockIODeviceWeight
*w
;
185 CGroupDeviceAllow
*a
;
186 IPAddressAccessItem
*iaai
;
187 char u
[FORMAT_TIMESPAN_MAX
];
192 prefix
= strempty(prefix
);
195 "%sCPUAccounting=%s\n"
196 "%sIOAccounting=%s\n"
197 "%sBlockIOAccounting=%s\n"
198 "%sMemoryAccounting=%s\n"
199 "%sTasksAccounting=%s\n"
200 "%sIPAccounting=%s\n"
201 "%sCPUWeight=%" PRIu64
"\n"
202 "%sStartupCPUWeight=%" PRIu64
"\n"
203 "%sCPUShares=%" PRIu64
"\n"
204 "%sStartupCPUShares=%" PRIu64
"\n"
205 "%sCPUQuotaPerSecSec=%s\n"
206 "%sIOWeight=%" PRIu64
"\n"
207 "%sStartupIOWeight=%" PRIu64
"\n"
208 "%sBlockIOWeight=%" PRIu64
"\n"
209 "%sStartupBlockIOWeight=%" PRIu64
"\n"
210 "%sMemoryMin=%" PRIu64
"\n"
211 "%sMemoryLow=%" PRIu64
"\n"
212 "%sMemoryHigh=%" PRIu64
"\n"
213 "%sMemoryMax=%" PRIu64
"\n"
214 "%sMemorySwapMax=%" PRIu64
"\n"
215 "%sMemoryLimit=%" PRIu64
"\n"
216 "%sTasksMax=%" PRIu64
"\n"
217 "%sDevicePolicy=%s\n"
219 prefix
, yes_no(c
->cpu_accounting
),
220 prefix
, yes_no(c
->io_accounting
),
221 prefix
, yes_no(c
->blockio_accounting
),
222 prefix
, yes_no(c
->memory_accounting
),
223 prefix
, yes_no(c
->tasks_accounting
),
224 prefix
, yes_no(c
->ip_accounting
),
225 prefix
, c
->cpu_weight
,
226 prefix
, c
->startup_cpu_weight
,
227 prefix
, c
->cpu_shares
,
228 prefix
, c
->startup_cpu_shares
,
229 prefix
, format_timespan(u
, sizeof(u
), c
->cpu_quota_per_sec_usec
, 1),
230 prefix
, c
->io_weight
,
231 prefix
, c
->startup_io_weight
,
232 prefix
, c
->blockio_weight
,
233 prefix
, c
->startup_blockio_weight
,
234 prefix
, c
->memory_min
,
235 prefix
, c
->memory_low
,
236 prefix
, c
->memory_high
,
237 prefix
, c
->memory_max
,
238 prefix
, c
->memory_swap_max
,
239 prefix
, c
->memory_limit
,
240 prefix
, c
->tasks_max
,
241 prefix
, cgroup_device_policy_to_string(c
->device_policy
),
242 prefix
, yes_no(c
->delegate
));
245 _cleanup_free_
char *t
= NULL
;
247 (void) cg_mask_to_string(c
->delegate_controllers
, &t
);
249 fprintf(f
, "%sDelegateControllers=%s\n",
254 LIST_FOREACH(device_allow
, a
, c
->device_allow
)
256 "%sDeviceAllow=%s %s%s%s\n",
259 a
->r
? "r" : "", a
->w
? "w" : "", a
->m
? "m" : "");
261 LIST_FOREACH(device_weights
, iw
, c
->io_device_weights
)
263 "%sIODeviceWeight=%s %" PRIu64
"\n",
268 LIST_FOREACH(device_latencies
, l
, c
->io_device_latencies
)
270 "%sIODeviceLatencyTargetSec=%s %s\n",
273 format_timespan(u
, sizeof(u
), l
->target_usec
, 1));
275 LIST_FOREACH(device_limits
, il
, c
->io_device_limits
) {
276 char buf
[FORMAT_BYTES_MAX
];
277 CGroupIOLimitType type
;
279 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
280 if (il
->limits
[type
] != cgroup_io_limit_defaults
[type
])
284 cgroup_io_limit_type_to_string(type
),
286 format_bytes(buf
, sizeof(buf
), il
->limits
[type
]));
289 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
291 "%sBlockIODeviceWeight=%s %" PRIu64
,
296 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
297 char buf
[FORMAT_BYTES_MAX
];
299 if (b
->rbps
!= CGROUP_LIMIT_MAX
)
301 "%sBlockIOReadBandwidth=%s %s\n",
304 format_bytes(buf
, sizeof(buf
), b
->rbps
));
305 if (b
->wbps
!= CGROUP_LIMIT_MAX
)
307 "%sBlockIOWriteBandwidth=%s %s\n",
310 format_bytes(buf
, sizeof(buf
), b
->wbps
));
313 LIST_FOREACH(items
, iaai
, c
->ip_address_allow
) {
314 _cleanup_free_
char *k
= NULL
;
316 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
317 fprintf(f
, "%sIPAddressAllow=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
320 LIST_FOREACH(items
, iaai
, c
->ip_address_deny
) {
321 _cleanup_free_
char *k
= NULL
;
323 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
324 fprintf(f
, "%sIPAddressDeny=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
328 int cgroup_add_device_allow(CGroupContext
*c
, const char *dev
, const char *mode
) {
329 _cleanup_free_ CGroupDeviceAllow
*a
= NULL
;
330 _cleanup_free_
char *d
= NULL
;
334 assert(isempty(mode
) || in_charset(mode
, "rwm"));
336 a
= new(CGroupDeviceAllow
, 1);
344 *a
= (CGroupDeviceAllow
) {
346 .r
= isempty(mode
) || !!strchr(mode
, 'r'),
347 .w
= isempty(mode
) || !!strchr(mode
, 'w'),
348 .m
= isempty(mode
) || !!strchr(mode
, 'm'),
351 LIST_PREPEND(device_allow
, c
->device_allow
, a
);
357 static int lookup_block_device(const char *p
, dev_t
*ret
) {
364 if (stat(p
, &st
) < 0)
365 return log_warning_errno(errno
, "Couldn't stat device '%s': %m", p
);
367 if (S_ISBLK(st
.st_mode
))
369 else if (major(st
.st_dev
) != 0)
370 *ret
= st
.st_dev
; /* If this is not a device node then use the block device this file is stored on */
372 /* If this is btrfs, getting the backing block device is a bit harder */
373 r
= btrfs_get_block_device(p
, ret
);
374 if (r
< 0 && r
!= -ENOTTY
)
375 return log_warning_errno(r
, "Failed to determine block device backing btrfs file system '%s': %m", p
);
377 log_warning("'%s' is not a block device node, and file system block device cannot be determined or is not local.", p
);
382 /* If this is a LUKS device, try to get the originating block device */
383 (void) block_get_originating(*ret
, ret
);
385 /* If this is a partition, try to get the originating block device */
386 (void) block_get_whole_disk(*ret
, ret
);
390 static int whitelist_device(BPFProgram
*prog
, const char *path
, const char *node
, const char *acc
) {
392 bool ignore_notfound
;
398 if (node
[0] == '-') {
399 /* Non-existent paths starting with "-" must be silently ignored */
401 ignore_notfound
= true;
403 ignore_notfound
= false;
405 if (stat(node
, &st
) < 0) {
406 if (errno
== ENOENT
&& ignore_notfound
)
409 return log_warning_errno(errno
, "Couldn't stat device %s: %m", node
);
412 if (!S_ISCHR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
413 log_warning("%s is not a device.", node
);
417 if (cg_all_unified() > 0) {
421 cgroup_bpf_whitelist_device(prog
, S_ISCHR(st
.st_mode
) ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
,
422 major(st
.st_rdev
), minor(st
.st_rdev
), acc
);
424 char buf
[2+DECIMAL_STR_MAX(dev_t
)*2+2+4];
428 S_ISCHR(st
.st_mode
) ? 'c' : 'b',
429 major(st
.st_rdev
), minor(st
.st_rdev
),
432 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
434 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
,
435 r
, "Failed to set devices.allow on %s: %m", path
);
441 static int whitelist_major(BPFProgram
*prog
, const char *path
, const char *name
, char type
, const char *acc
) {
442 _cleanup_fclose_
FILE *f
= NULL
;
450 assert(IN_SET(type
, 'b', 'c'));
452 f
= fopen("/proc/devices", "re");
454 return log_warning_errno(errno
, "Cannot open /proc/devices to resolve %s (%c): %m", name
, type
);
456 FOREACH_LINE(line
, f
, goto fail
) {
461 if (type
== 'c' && streq(line
, "Character devices:")) {
466 if (type
== 'b' && streq(line
, "Block devices:")) {
481 w
= strpbrk(p
, WHITESPACE
);
486 r
= safe_atou(p
, &maj
);
493 w
+= strspn(w
, WHITESPACE
);
495 if (fnmatch(name
, w
, 0) != 0)
498 if (cg_all_unified() > 0) {
502 cgroup_bpf_whitelist_major(prog
,
503 type
== 'c' ? BPF_DEVCG_DEV_CHAR
: BPF_DEVCG_DEV_BLOCK
,
506 char buf
[2+DECIMAL_STR_MAX(unsigned)+3+4];
514 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
516 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
,
517 r
, "Failed to set devices.allow on %s: %m", path
);
524 return log_warning_errno(errno
, "Failed to read /proc/devices: %m");
527 static bool cgroup_context_has_cpu_weight(CGroupContext
*c
) {
528 return c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
||
529 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
;
532 static bool cgroup_context_has_cpu_shares(CGroupContext
*c
) {
533 return c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
534 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
;
537 static uint64_t cgroup_context_cpu_weight(CGroupContext
*c
, ManagerState state
) {
538 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
539 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
)
540 return c
->startup_cpu_weight
;
541 else if (c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
)
542 return c
->cpu_weight
;
544 return CGROUP_WEIGHT_DEFAULT
;
547 static uint64_t cgroup_context_cpu_shares(CGroupContext
*c
, ManagerState state
) {
548 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
549 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
550 return c
->startup_cpu_shares
;
551 else if (c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
552 return c
->cpu_shares
;
554 return CGROUP_CPU_SHARES_DEFAULT
;
557 static void cgroup_apply_unified_cpu_config(Unit
*u
, uint64_t weight
, uint64_t quota
) {
558 char buf
[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t
) + 1) * 2)];
561 xsprintf(buf
, "%" PRIu64
"\n", weight
);
562 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.weight", buf
);
564 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
565 "Failed to set cpu.weight: %m");
567 if (quota
!= USEC_INFINITY
)
568 xsprintf(buf
, USEC_FMT
" " USEC_FMT
"\n",
569 quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
, CGROUP_CPU_QUOTA_PERIOD_USEC
);
571 xsprintf(buf
, "max " USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
573 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.max", buf
);
576 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
577 "Failed to set cpu.max: %m");
580 static void cgroup_apply_legacy_cpu_config(Unit
*u
, uint64_t shares
, uint64_t quota
) {
581 char buf
[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t
)) + 1];
584 xsprintf(buf
, "%" PRIu64
"\n", shares
);
585 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.shares", buf
);
587 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
588 "Failed to set cpu.shares: %m");
590 xsprintf(buf
, USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
591 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_period_us", buf
);
593 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
594 "Failed to set cpu.cfs_period_us: %m");
596 if (quota
!= USEC_INFINITY
) {
597 xsprintf(buf
, USEC_FMT
"\n", quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
);
598 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", buf
);
600 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", "-1");
602 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
603 "Failed to set cpu.cfs_quota_us: %m");
606 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares
) {
607 return CLAMP(shares
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_CPU_SHARES_DEFAULT
,
608 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
611 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight
) {
612 return CLAMP(weight
* CGROUP_CPU_SHARES_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
613 CGROUP_CPU_SHARES_MIN
, CGROUP_CPU_SHARES_MAX
);
616 static bool cgroup_context_has_io_config(CGroupContext
*c
) {
617 return c
->io_accounting
||
618 c
->io_weight
!= CGROUP_WEIGHT_INVALID
||
619 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
620 c
->io_device_weights
||
621 c
->io_device_latencies
||
625 static bool cgroup_context_has_blockio_config(CGroupContext
*c
) {
626 return c
->blockio_accounting
||
627 c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
628 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
629 c
->blockio_device_weights
||
630 c
->blockio_device_bandwidths
;
633 static uint64_t cgroup_context_io_weight(CGroupContext
*c
, ManagerState state
) {
634 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
635 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
)
636 return c
->startup_io_weight
;
637 else if (c
->io_weight
!= CGROUP_WEIGHT_INVALID
)
640 return CGROUP_WEIGHT_DEFAULT
;
643 static uint64_t cgroup_context_blkio_weight(CGroupContext
*c
, ManagerState state
) {
644 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
645 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
646 return c
->startup_blockio_weight
;
647 else if (c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
648 return c
->blockio_weight
;
650 return CGROUP_BLKIO_WEIGHT_DEFAULT
;
653 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight
) {
654 return CLAMP(blkio_weight
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_BLKIO_WEIGHT_DEFAULT
,
655 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
658 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight
) {
659 return CLAMP(io_weight
* CGROUP_BLKIO_WEIGHT_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
660 CGROUP_BLKIO_WEIGHT_MIN
, CGROUP_BLKIO_WEIGHT_MAX
);
663 static void cgroup_apply_io_device_weight(Unit
*u
, const char *dev_path
, uint64_t io_weight
) {
664 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
668 r
= lookup_block_device(dev_path
, &dev
);
672 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), io_weight
);
673 r
= cg_set_attribute("io", u
->cgroup_path
, "io.weight", buf
);
675 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
676 "Failed to set io.weight: %m");
679 static void cgroup_apply_blkio_device_weight(Unit
*u
, const char *dev_path
, uint64_t blkio_weight
) {
680 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
684 r
= lookup_block_device(dev_path
, &dev
);
688 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), blkio_weight
);
689 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.weight_device", buf
);
691 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
692 "Failed to set blkio.weight_device: %m");
695 static void cgroup_apply_io_device_latency(Unit
*u
, const char *dev_path
, usec_t target
) {
696 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+7+DECIMAL_STR_MAX(uint64_t)+1];
700 r
= lookup_block_device(dev_path
, &dev
);
704 if (target
!= USEC_INFINITY
)
705 xsprintf(buf
, "%u:%u target=%" PRIu64
"\n", major(dev
), minor(dev
), target
);
707 xsprintf(buf
, "%u:%u target=max\n", major(dev
), minor(dev
));
709 r
= cg_set_attribute("io", u
->cgroup_path
, "io.latency", buf
);
711 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
712 "Failed to set io.latency on cgroup %s: %m", u
->cgroup_path
);
715 static void cgroup_apply_io_device_limit(Unit
*u
, const char *dev_path
, uint64_t *limits
) {
716 char limit_bufs
[_CGROUP_IO_LIMIT_TYPE_MAX
][DECIMAL_STR_MAX(uint64_t)];
717 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
718 CGroupIOLimitType type
;
722 r
= lookup_block_device(dev_path
, &dev
);
726 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
727 if (limits
[type
] != cgroup_io_limit_defaults
[type
])
728 xsprintf(limit_bufs
[type
], "%" PRIu64
, limits
[type
]);
730 xsprintf(limit_bufs
[type
], "%s", limits
[type
] == CGROUP_LIMIT_MAX
? "max" : "0");
732 xsprintf(buf
, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev
), minor(dev
),
733 limit_bufs
[CGROUP_IO_RBPS_MAX
], limit_bufs
[CGROUP_IO_WBPS_MAX
],
734 limit_bufs
[CGROUP_IO_RIOPS_MAX
], limit_bufs
[CGROUP_IO_WIOPS_MAX
]);
735 r
= cg_set_attribute("io", u
->cgroup_path
, "io.max", buf
);
737 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
738 "Failed to set io.max: %m");
741 static void cgroup_apply_blkio_device_limit(Unit
*u
, const char *dev_path
, uint64_t rbps
, uint64_t wbps
) {
742 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
746 r
= lookup_block_device(dev_path
, &dev
);
750 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), rbps
);
751 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.read_bps_device", buf
);
753 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
754 "Failed to set blkio.throttle.read_bps_device: %m");
756 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), wbps
);
757 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.write_bps_device", buf
);
759 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
760 "Failed to set blkio.throttle.write_bps_device: %m");
763 static bool cgroup_context_has_unified_memory_config(CGroupContext
*c
) {
764 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
;
767 static void cgroup_apply_unified_memory_limit(Unit
*u
, const char *file
, uint64_t v
) {
768 char buf
[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
771 if (v
!= CGROUP_LIMIT_MAX
)
772 xsprintf(buf
, "%" PRIu64
"\n", v
);
774 r
= cg_set_attribute("memory", u
->cgroup_path
, file
, buf
);
776 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
777 "Failed to set %s: %m", file
);
780 static void cgroup_apply_firewall(Unit
*u
) {
783 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
785 if (bpf_firewall_compile(u
) < 0)
788 (void) bpf_firewall_install(u
);
791 static void cgroup_context_apply(
793 CGroupMask apply_mask
,
794 ManagerState state
) {
803 /* Nothing to do? Exit early! */
807 /* Some cgroup attributes are not supported on the root cgroup, hence silently ignore */
808 is_root
= unit_has_root_cgroup(u
);
810 assert_se(c
= unit_get_cgroup_context(u
));
811 assert_se(path
= u
->cgroup_path
);
813 if (is_root
) /* Make sure we don't try to display messages with an empty path. */
816 /* We generally ignore errors caused by read-only mounted
817 * cgroup trees (assuming we are running in a container then),
818 * and missing cgroups, i.e. EROFS and ENOENT. */
820 if ((apply_mask
& CGROUP_MASK_CPU
) && !is_root
) {
821 bool has_weight
, has_shares
;
823 has_weight
= cgroup_context_has_cpu_weight(c
);
824 has_shares
= cgroup_context_has_cpu_shares(c
);
826 if (cg_all_unified() > 0) {
830 weight
= cgroup_context_cpu_weight(c
, state
);
831 else if (has_shares
) {
832 uint64_t shares
= cgroup_context_cpu_shares(c
, state
);
834 weight
= cgroup_cpu_shares_to_weight(shares
);
836 log_cgroup_compat(u
, "Applying [Startup]CpuShares %" PRIu64
" as [Startup]CpuWeight %" PRIu64
" on %s",
837 shares
, weight
, path
);
839 weight
= CGROUP_WEIGHT_DEFAULT
;
841 cgroup_apply_unified_cpu_config(u
, weight
, c
->cpu_quota_per_sec_usec
);
846 uint64_t weight
= cgroup_context_cpu_weight(c
, state
);
848 shares
= cgroup_cpu_weight_to_shares(weight
);
850 log_cgroup_compat(u
, "Applying [Startup]CpuWeight %" PRIu64
" as [Startup]CpuShares %" PRIu64
" on %s",
851 weight
, shares
, path
);
852 } else if (has_shares
)
853 shares
= cgroup_context_cpu_shares(c
, state
);
855 shares
= CGROUP_CPU_SHARES_DEFAULT
;
857 cgroup_apply_legacy_cpu_config(u
, shares
, c
->cpu_quota_per_sec_usec
);
861 if (apply_mask
& CGROUP_MASK_IO
) {
862 bool has_io
= cgroup_context_has_io_config(c
);
863 bool has_blockio
= cgroup_context_has_blockio_config(c
);
866 char buf
[8+DECIMAL_STR_MAX(uint64_t)+1];
870 weight
= cgroup_context_io_weight(c
, state
);
871 else if (has_blockio
) {
872 uint64_t blkio_weight
= cgroup_context_blkio_weight(c
, state
);
874 weight
= cgroup_weight_blkio_to_io(blkio_weight
);
876 log_cgroup_compat(u
, "Applying [Startup]BlockIOWeight %" PRIu64
" as [Startup]IOWeight %" PRIu64
,
877 blkio_weight
, weight
);
879 weight
= CGROUP_WEIGHT_DEFAULT
;
881 xsprintf(buf
, "default %" PRIu64
"\n", weight
);
882 r
= cg_set_attribute("io", path
, "io.weight", buf
);
884 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
885 "Failed to set io.weight: %m");
888 CGroupIODeviceWeight
*w
;
890 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
)
891 cgroup_apply_io_device_weight(u
, w
->path
, w
->weight
);
892 } else if (has_blockio
) {
893 CGroupBlockIODeviceWeight
*w
;
895 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
) {
896 weight
= cgroup_weight_blkio_to_io(w
->weight
);
898 log_cgroup_compat(u
, "Applying BlockIODeviceWeight %" PRIu64
" as IODeviceWeight %" PRIu64
" for %s",
899 w
->weight
, weight
, w
->path
);
901 cgroup_apply_io_device_weight(u
, w
->path
, weight
);
906 CGroupIODeviceLatency
*l
;
908 LIST_FOREACH(device_latencies
, l
, c
->io_device_latencies
)
909 cgroup_apply_io_device_latency(u
, l
->path
, l
->target_usec
);
914 CGroupIODeviceLimit
*l
;
916 LIST_FOREACH(device_limits
, l
, c
->io_device_limits
)
917 cgroup_apply_io_device_limit(u
, l
->path
, l
->limits
);
919 } else if (has_blockio
) {
920 CGroupBlockIODeviceBandwidth
*b
;
922 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
923 uint64_t limits
[_CGROUP_IO_LIMIT_TYPE_MAX
];
924 CGroupIOLimitType type
;
926 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
927 limits
[type
] = cgroup_io_limit_defaults
[type
];
929 limits
[CGROUP_IO_RBPS_MAX
] = b
->rbps
;
930 limits
[CGROUP_IO_WBPS_MAX
] = b
->wbps
;
932 log_cgroup_compat(u
, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as IO{Read|Write}BandwidthMax for %s",
933 b
->rbps
, b
->wbps
, b
->path
);
935 cgroup_apply_io_device_limit(u
, b
->path
, limits
);
940 if (apply_mask
& CGROUP_MASK_BLKIO
) {
941 bool has_io
= cgroup_context_has_io_config(c
);
942 bool has_blockio
= cgroup_context_has_blockio_config(c
);
945 char buf
[DECIMAL_STR_MAX(uint64_t)+1];
949 uint64_t io_weight
= cgroup_context_io_weight(c
, state
);
951 weight
= cgroup_weight_io_to_blkio(cgroup_context_io_weight(c
, state
));
953 log_cgroup_compat(u
, "Applying [Startup]IOWeight %" PRIu64
" as [Startup]BlockIOWeight %" PRIu64
,
955 } else if (has_blockio
)
956 weight
= cgroup_context_blkio_weight(c
, state
);
958 weight
= CGROUP_BLKIO_WEIGHT_DEFAULT
;
960 xsprintf(buf
, "%" PRIu64
"\n", weight
);
961 r
= cg_set_attribute("blkio", path
, "blkio.weight", buf
);
963 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
964 "Failed to set blkio.weight: %m");
967 CGroupIODeviceWeight
*w
;
969 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
) {
970 weight
= cgroup_weight_io_to_blkio(w
->weight
);
972 log_cgroup_compat(u
, "Applying IODeviceWeight %" PRIu64
" as BlockIODeviceWeight %" PRIu64
" for %s",
973 w
->weight
, weight
, w
->path
);
975 cgroup_apply_blkio_device_weight(u
, w
->path
, weight
);
977 } else if (has_blockio
) {
978 CGroupBlockIODeviceWeight
*w
;
980 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
981 cgroup_apply_blkio_device_weight(u
, w
->path
, w
->weight
);
986 CGroupIODeviceLimit
*l
;
988 LIST_FOREACH(device_limits
, l
, c
->io_device_limits
) {
989 log_cgroup_compat(u
, "Applying IO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as BlockIO{Read|Write}BandwidthMax for %s",
990 l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
], l
->path
);
992 cgroup_apply_blkio_device_limit(u
, l
->path
, l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
]);
994 } else if (has_blockio
) {
995 CGroupBlockIODeviceBandwidth
*b
;
997 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
)
998 cgroup_apply_blkio_device_limit(u
, b
->path
, b
->rbps
, b
->wbps
);
1002 if ((apply_mask
& CGROUP_MASK_MEMORY
) && !is_root
) {
1003 if (cg_all_unified() > 0) {
1004 uint64_t max
, swap_max
= CGROUP_LIMIT_MAX
;
1006 if (cgroup_context_has_unified_memory_config(c
)) {
1007 max
= c
->memory_max
;
1008 swap_max
= c
->memory_swap_max
;
1010 max
= c
->memory_limit
;
1012 if (max
!= CGROUP_LIMIT_MAX
)
1013 log_cgroup_compat(u
, "Applying MemoryLimit %" PRIu64
" as MemoryMax", max
);
1016 cgroup_apply_unified_memory_limit(u
, "memory.min", c
->memory_min
);
1017 cgroup_apply_unified_memory_limit(u
, "memory.low", c
->memory_low
);
1018 cgroup_apply_unified_memory_limit(u
, "memory.high", c
->memory_high
);
1019 cgroup_apply_unified_memory_limit(u
, "memory.max", max
);
1020 cgroup_apply_unified_memory_limit(u
, "memory.swap.max", swap_max
);
1022 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
1025 if (cgroup_context_has_unified_memory_config(c
)) {
1026 val
= c
->memory_max
;
1027 log_cgroup_compat(u
, "Applying MemoryMax %" PRIi64
" as MemoryLimit", val
);
1029 val
= c
->memory_limit
;
1031 if (val
== CGROUP_LIMIT_MAX
)
1032 strncpy(buf
, "-1\n", sizeof(buf
));
1034 xsprintf(buf
, "%" PRIu64
"\n", val
);
1036 r
= cg_set_attribute("memory", path
, "memory.limit_in_bytes", buf
);
1038 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1039 "Failed to set memory.limit_in_bytes: %m");
1043 if ((apply_mask
& (CGROUP_MASK_DEVICES
| CGROUP_MASK_BPF_DEVICES
)) && !is_root
) {
1044 _cleanup_(bpf_program_unrefp
) BPFProgram
*prog
= NULL
;
1045 CGroupDeviceAllow
*a
;
1047 if (cg_all_unified() > 0) {
1048 r
= cgroup_init_device_bpf(&prog
, c
->device_policy
, c
->device_allow
);
1050 log_unit_warning_errno(u
, r
, "Failed to initialize device control bpf program: %m");
1052 /* Changing the devices list of a populated cgroup
1053 * might result in EINVAL, hence ignore EINVAL
1056 if (c
->device_allow
|| c
->device_policy
!= CGROUP_AUTO
)
1057 r
= cg_set_attribute("devices", path
, "devices.deny", "a");
1059 r
= cg_set_attribute("devices", path
, "devices.allow", "a");
1061 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1062 "Failed to reset devices.list: %m");
1065 if (c
->device_policy
== CGROUP_CLOSED
||
1066 (c
->device_policy
== CGROUP_AUTO
&& c
->device_allow
)) {
1067 static const char auto_devices
[] =
1068 "/dev/null\0" "rwm\0"
1069 "/dev/zero\0" "rwm\0"
1070 "/dev/full\0" "rwm\0"
1071 "/dev/random\0" "rwm\0"
1072 "/dev/urandom\0" "rwm\0"
1073 "/dev/tty\0" "rwm\0"
1074 "/dev/ptmx\0" "rwm\0"
1075 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
1076 "-/run/systemd/inaccessible/chr\0" "rwm\0"
1077 "-/run/systemd/inaccessible/blk\0" "rwm\0";
1081 NULSTR_FOREACH_PAIR(x
, y
, auto_devices
)
1082 whitelist_device(prog
, path
, x
, y
);
1084 /* PTS (/dev/pts) devices may not be duplicated, but accessed */
1085 whitelist_major(prog
, path
, "pts", 'c', "rw");
1088 LIST_FOREACH(device_allow
, a
, c
->device_allow
) {
1104 if (path_startswith(a
->path
, "/dev/"))
1105 whitelist_device(prog
, path
, a
->path
, acc
);
1106 else if ((val
= startswith(a
->path
, "block-")))
1107 whitelist_major(prog
, path
, val
, 'b', acc
);
1108 else if ((val
= startswith(a
->path
, "char-")))
1109 whitelist_major(prog
, path
, val
, 'c', acc
);
1111 log_unit_debug(u
, "Ignoring device %s while writing cgroup attribute.", a
->path
);
1114 r
= cgroup_apply_device_bpf(u
, prog
, c
->device_policy
, c
->device_allow
);
1116 static bool warned
= false;
1118 log_full_errno(warned
? LOG_DEBUG
: LOG_WARNING
, r
,
1119 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1120 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1121 "(This warning is only shown for the first loaded unit using device ACL.)", u
->id
);
1127 if (apply_mask
& CGROUP_MASK_PIDS
) {
1130 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1131 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1132 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1133 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1134 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1135 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1136 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1137 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1138 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1139 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1140 * which is desirable so that there's an offical way to release control of the sysctl from
1141 * systemd: set the limit to unbounded and reload. */
1143 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1144 u
->manager
->sysctl_pid_max_changed
= true;
1145 r
= procfs_tasks_set_limit(c
->tasks_max
);
1146 } else if (u
->manager
->sysctl_pid_max_changed
)
1147 r
= procfs_tasks_set_limit(TASKS_MAX
);
1152 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1153 "Failed to write to tasks limit sysctls: %m");
1156 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1157 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
1159 sprintf(buf
, "%" PRIu64
"\n", c
->tasks_max
);
1160 r
= cg_set_attribute("pids", path
, "pids.max", buf
);
1162 r
= cg_set_attribute("pids", path
, "pids.max", "max");
1164 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1165 "Failed to set pids.max: %m");
1169 if (apply_mask
& CGROUP_MASK_BPF_FIREWALL
)
1170 cgroup_apply_firewall(u
);
1173 CGroupMask
cgroup_context_get_mask(CGroupContext
*c
) {
1174 CGroupMask mask
= 0;
1176 /* Figure out which controllers we need */
1178 if (c
->cpu_accounting
||
1179 cgroup_context_has_cpu_weight(c
) ||
1180 cgroup_context_has_cpu_shares(c
) ||
1181 c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
)
1182 mask
|= CGROUP_MASK_CPUACCT
| CGROUP_MASK_CPU
;
1184 if (cgroup_context_has_io_config(c
) || cgroup_context_has_blockio_config(c
))
1185 mask
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
1187 if (c
->memory_accounting
||
1188 c
->memory_limit
!= CGROUP_LIMIT_MAX
||
1189 cgroup_context_has_unified_memory_config(c
))
1190 mask
|= CGROUP_MASK_MEMORY
;
1192 if (c
->device_allow
||
1193 c
->device_policy
!= CGROUP_AUTO
)
1194 mask
|= CGROUP_MASK_DEVICES
| CGROUP_MASK_BPF_DEVICES
;
1196 if (c
->tasks_accounting
||
1197 c
->tasks_max
!= CGROUP_LIMIT_MAX
)
1198 mask
|= CGROUP_MASK_PIDS
;
1203 CGroupMask
unit_get_bpf_mask(Unit
*u
) {
1204 CGroupMask mask
= 0;
1206 if (unit_get_needs_bpf_firewall(u
))
1207 mask
|= CGROUP_MASK_BPF_FIREWALL
;
1212 CGroupMask
unit_get_own_mask(Unit
*u
) {
1215 /* Returns the mask of controllers the unit needs for itself */
1217 c
= unit_get_cgroup_context(u
);
1221 return cgroup_context_get_mask(c
) | unit_get_bpf_mask(u
) | unit_get_delegate_mask(u
);
1224 CGroupMask
unit_get_delegate_mask(Unit
*u
) {
1227 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1228 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
1230 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1232 if (!unit_cgroup_delegate(u
))
1235 if (cg_all_unified() <= 0) {
1238 e
= unit_get_exec_context(u
);
1239 if (e
&& !exec_context_maintains_privileges(e
))
1243 assert_se(c
= unit_get_cgroup_context(u
));
1244 return c
->delegate_controllers
;
1247 CGroupMask
unit_get_members_mask(Unit
*u
) {
1250 /* Returns the mask of controllers all of the unit's children require, merged */
1252 if (u
->cgroup_members_mask_valid
)
1253 return u
->cgroup_members_mask
;
1255 u
->cgroup_members_mask
= 0;
1257 if (u
->type
== UNIT_SLICE
) {
1262 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
1267 if (UNIT_DEREF(member
->slice
) != u
)
1270 u
->cgroup_members_mask
|= unit_get_subtree_mask(member
); /* note that this calls ourselves again, for the children */
1274 u
->cgroup_members_mask_valid
= true;
1275 return u
->cgroup_members_mask
;
1278 CGroupMask
unit_get_siblings_mask(Unit
*u
) {
1281 /* Returns the mask of controllers all of the unit's siblings
1282 * require, i.e. the members mask of the unit's parent slice
1283 * if there is one. */
1285 if (UNIT_ISSET(u
->slice
))
1286 return unit_get_members_mask(UNIT_DEREF(u
->slice
));
1288 return unit_get_subtree_mask(u
); /* we are the top-level slice */
1291 CGroupMask
unit_get_subtree_mask(Unit
*u
) {
1293 /* Returns the mask of this subtree, meaning of the group
1294 * itself and its children. */
1296 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
1299 CGroupMask
unit_get_target_mask(Unit
*u
) {
1302 /* This returns the cgroup mask of all controllers to enable
1303 * for a specific cgroup, i.e. everything it needs itself,
1304 * plus all that its children need, plus all that its siblings
1305 * need. This is primarily useful on the legacy cgroup
1306 * hierarchy, where we need to duplicate each cgroup in each
1307 * hierarchy that shall be enabled for it. */
1309 mask
= unit_get_own_mask(u
) | unit_get_members_mask(u
) | unit_get_siblings_mask(u
);
1310 mask
&= u
->manager
->cgroup_supported
;
1315 CGroupMask
unit_get_enable_mask(Unit
*u
) {
1318 /* This returns the cgroup mask of all controllers to enable
1319 * for the children of a specific cgroup. This is primarily
1320 * useful for the unified cgroup hierarchy, where each cgroup
1321 * controls which controllers are enabled for its children. */
1323 mask
= unit_get_members_mask(u
);
1324 mask
&= u
->manager
->cgroup_supported
;
1329 bool unit_get_needs_bpf_firewall(Unit
*u
) {
1334 c
= unit_get_cgroup_context(u
);
1338 if (c
->ip_accounting
||
1339 c
->ip_address_allow
||
1343 /* If any parent slice has an IP access list defined, it applies too */
1344 for (p
= UNIT_DEREF(u
->slice
); p
; p
= UNIT_DEREF(p
->slice
)) {
1345 c
= unit_get_cgroup_context(p
);
1349 if (c
->ip_address_allow
||
1357 /* Recurse from a unit up through its containing slices, propagating
1358 * mask bits upward. A unit is also member of itself. */
1359 void unit_update_cgroup_members_masks(Unit
*u
) {
1365 /* Calculate subtree mask */
1366 m
= unit_get_subtree_mask(u
);
1368 /* See if anything changed from the previous invocation. If
1369 * not, we're done. */
1370 if (u
->cgroup_subtree_mask_valid
&& m
== u
->cgroup_subtree_mask
)
1374 u
->cgroup_subtree_mask_valid
&&
1375 ((m
& ~u
->cgroup_subtree_mask
) != 0) &&
1376 ((~m
& u
->cgroup_subtree_mask
) == 0);
1378 u
->cgroup_subtree_mask
= m
;
1379 u
->cgroup_subtree_mask_valid
= true;
1381 if (UNIT_ISSET(u
->slice
)) {
1382 Unit
*s
= UNIT_DEREF(u
->slice
);
1385 /* There's more set now than before. We
1386 * propagate the new mask to the parent's mask
1387 * (not caring if it actually was valid or
1390 s
->cgroup_members_mask
|= m
;
1393 /* There's less set now than before (or we
1394 * don't know), we need to recalculate
1395 * everything, so let's invalidate the
1396 * parent's members mask */
1398 s
->cgroup_members_mask_valid
= false;
1400 /* And now make sure that this change also hits our
1402 unit_update_cgroup_members_masks(s
);
1406 const char *unit_get_realized_cgroup_path(Unit
*u
, CGroupMask mask
) {
1408 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
1412 if (u
->cgroup_path
&&
1413 u
->cgroup_realized
&&
1414 FLAGS_SET(u
->cgroup_realized_mask
, mask
))
1415 return u
->cgroup_path
;
1417 u
= UNIT_DEREF(u
->slice
);
1423 static const char *migrate_callback(CGroupMask mask
, void *userdata
) {
1424 return unit_get_realized_cgroup_path(userdata
, mask
);
1427 char *unit_default_cgroup_path(Unit
*u
) {
1428 _cleanup_free_
char *escaped
= NULL
, *slice
= NULL
;
1433 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1434 return strdup(u
->manager
->cgroup_root
);
1436 if (UNIT_ISSET(u
->slice
) && !unit_has_name(UNIT_DEREF(u
->slice
), SPECIAL_ROOT_SLICE
)) {
1437 r
= cg_slice_to_path(UNIT_DEREF(u
->slice
)->id
, &slice
);
1442 escaped
= cg_escape(u
->id
);
1447 return strjoin(u
->manager
->cgroup_root
, "/", slice
, "/",
1450 return strjoin(u
->manager
->cgroup_root
, "/", escaped
);
1453 int unit_set_cgroup_path(Unit
*u
, const char *path
) {
1454 _cleanup_free_
char *p
= NULL
;
1466 if (streq_ptr(u
->cgroup_path
, p
))
1470 r
= hashmap_put(u
->manager
->cgroup_unit
, p
, u
);
1475 unit_release_cgroup(u
);
1477 u
->cgroup_path
= TAKE_PTR(p
);
1482 int unit_watch_cgroup(Unit
*u
) {
1483 _cleanup_free_
char *events
= NULL
;
1488 if (!u
->cgroup_path
)
1491 if (u
->cgroup_inotify_wd
>= 0)
1494 /* Only applies to the unified hierarchy */
1495 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
1497 return log_error_errno(r
, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1501 /* Don't watch the root slice, it's pointless. */
1502 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1505 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_inotify_wd_unit
, &trivial_hash_ops
);
1509 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events", &events
);
1513 u
->cgroup_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
1514 if (u
->cgroup_inotify_wd
< 0) {
1516 if (errno
== ENOENT
) /* If the directory is already
1517 * gone we don't need to track
1518 * it, so this is not an error */
1521 return log_unit_error_errno(u
, errno
, "Failed to add inotify watch descriptor for control group %s: %m", u
->cgroup_path
);
1524 r
= hashmap_put(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
), u
);
1526 return log_unit_error_errno(u
, r
, "Failed to add inotify watch descriptor to hash map: %m");
1531 int unit_pick_cgroup_path(Unit
*u
) {
1532 _cleanup_free_
char *path
= NULL
;
1540 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1543 path
= unit_default_cgroup_path(u
);
1547 r
= unit_set_cgroup_path(u
, path
);
1549 return log_unit_error_errno(u
, r
, "Control group %s exists already.", path
);
1551 return log_unit_error_errno(u
, r
, "Failed to set unit's control group path to %s: %m", path
);
1556 static int unit_create_cgroup(
1558 CGroupMask target_mask
,
1559 CGroupMask enable_mask
) {
1567 c
= unit_get_cgroup_context(u
);
1571 /* Figure out our cgroup path */
1572 r
= unit_pick_cgroup_path(u
);
1576 /* First, create our own group */
1577 r
= cg_create_everywhere(u
->manager
->cgroup_supported
, target_mask
, u
->cgroup_path
);
1579 return log_unit_error_errno(u
, r
, "Failed to create cgroup %s: %m", u
->cgroup_path
);
1582 /* Start watching it */
1583 (void) unit_watch_cgroup(u
);
1585 /* Preserve enabled controllers in delegated units, adjust others. */
1586 if (created
|| !unit_cgroup_delegate(u
)) {
1588 /* Enable all controllers we need */
1589 r
= cg_enable_everywhere(u
->manager
->cgroup_supported
, enable_mask
, u
->cgroup_path
);
1591 log_unit_warning_errno(u
, r
, "Failed to enable controllers on cgroup %s, ignoring: %m",
1595 /* Keep track that this is now realized */
1596 u
->cgroup_realized
= true;
1597 u
->cgroup_realized_mask
= target_mask
;
1598 u
->cgroup_enabled_mask
= enable_mask
;
1600 if (u
->type
!= UNIT_SLICE
&& !unit_cgroup_delegate(u
)) {
1602 /* Then, possibly move things over, but not if
1603 * subgroups may contain processes, which is the case
1604 * for slice and delegation units. */
1605 r
= cg_migrate_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->cgroup_path
, migrate_callback
, u
);
1607 log_unit_warning_errno(u
, r
, "Failed to migrate cgroup from to %s, ignoring: %m", u
->cgroup_path
);
1613 static int unit_attach_pid_to_cgroup_via_bus(Unit
*u
, pid_t pid
, const char *suffix_path
) {
1614 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1620 if (MANAGER_IS_SYSTEM(u
->manager
))
1623 if (!u
->manager
->system_bus
)
1626 if (!u
->cgroup_path
)
1629 /* Determine this unit's cgroup path relative to our cgroup root */
1630 pp
= path_startswith(u
->cgroup_path
, u
->manager
->cgroup_root
);
1634 pp
= strjoina("/", pp
, suffix_path
);
1635 path_simplify(pp
, false);
1637 r
= sd_bus_call_method(u
->manager
->system_bus
,
1638 "org.freedesktop.systemd1",
1639 "/org/freedesktop/systemd1",
1640 "org.freedesktop.systemd1.Manager",
1641 "AttachProcessesToUnit",
1644 NULL
/* empty unit name means client's unit, i.e. us */, pp
, 1, (uint32_t) pid
);
1646 return log_unit_debug_errno(u
, r
, "Failed to attach unit process " PID_FMT
" via the bus: %s", pid
, bus_error_message(&error
, r
));
1651 int unit_attach_pids_to_cgroup(Unit
*u
, Set
*pids
, const char *suffix_path
) {
1652 CGroupMask delegated_mask
;
1660 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1663 if (set_isempty(pids
))
1666 r
= unit_realize_cgroup(u
);
1670 if (isempty(suffix_path
))
1673 p
= strjoina(u
->cgroup_path
, "/", suffix_path
);
1675 delegated_mask
= unit_get_delegate_mask(u
);
1678 SET_FOREACH(pidp
, pids
, i
) {
1679 pid_t pid
= PTR_TO_PID(pidp
);
1682 /* First, attach the PID to the main cgroup hierarchy */
1683 q
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, p
, pid
);
1685 log_unit_debug_errno(u
, q
, "Couldn't move process " PID_FMT
" to requested cgroup '%s': %m", pid
, p
);
1687 if (MANAGER_IS_USER(u
->manager
) && IN_SET(q
, -EPERM
, -EACCES
)) {
1690 /* If we are in a user instance, and we can't move the process ourselves due to
1691 * permission problems, let's ask the system instance about it instead. Since it's more
1692 * privileged it might be able to move the process across the leaves of a subtree who's
1693 * top node is not owned by us. */
1695 z
= unit_attach_pid_to_cgroup_via_bus(u
, pid
, suffix_path
);
1697 log_unit_debug_errno(u
, z
, "Couldn't move process " PID_FMT
" to requested cgroup '%s' via the system bus either: %m", pid
, p
);
1699 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1703 r
= q
; /* Remember first error */
1708 q
= cg_all_unified();
1714 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
1715 * innermost realized one */
1717 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1718 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1719 const char *realized
;
1721 if (!(u
->manager
->cgroup_supported
& bit
))
1724 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
1725 if (delegated_mask
& u
->cgroup_realized_mask
& bit
) {
1726 q
= cg_attach(cgroup_controller_to_string(c
), p
, pid
);
1728 continue; /* Success! */
1730 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",
1731 pid
, p
, cgroup_controller_to_string(c
));
1734 /* So this controller is either not delegate or realized, or something else weird happened. In
1735 * that case let's attach the PID at least to the closest cgroup up the tree that is
1737 realized
= unit_get_realized_cgroup_path(u
, bit
);
1739 continue; /* Not even realized in the root slice? Then let's not bother */
1741 q
= cg_attach(cgroup_controller_to_string(c
), realized
, pid
);
1743 log_unit_debug_errno(u
, q
, "Failed to attach PID " PID_FMT
" to realized cgroup %s in controller %s, ignoring: %m",
1744 pid
, realized
, cgroup_controller_to_string(c
));
1751 static void cgroup_xattr_apply(Unit
*u
) {
1752 char ids
[SD_ID128_STRING_MAX
];
1757 if (!MANAGER_IS_SYSTEM(u
->manager
))
1760 if (sd_id128_is_null(u
->invocation_id
))
1763 r
= cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
1764 "trusted.invocation_id",
1765 sd_id128_to_string(u
->invocation_id
, ids
), 32,
1768 log_unit_debug_errno(u
, r
, "Failed to set invocation ID on control group %s, ignoring: %m", u
->cgroup_path
);
1771 static bool unit_has_mask_realized(
1773 CGroupMask target_mask
,
1774 CGroupMask enable_mask
) {
1778 return u
->cgroup_realized
&&
1779 u
->cgroup_realized_mask
== target_mask
&&
1780 u
->cgroup_enabled_mask
== enable_mask
&&
1781 u
->cgroup_invalidated_mask
== 0;
1784 static void unit_add_to_cgroup_realize_queue(Unit
*u
) {
1787 if (u
->in_cgroup_realize_queue
)
1790 LIST_PREPEND(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1791 u
->in_cgroup_realize_queue
= true;
1794 static void unit_remove_from_cgroup_realize_queue(Unit
*u
) {
1797 if (!u
->in_cgroup_realize_queue
)
1800 LIST_REMOVE(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1801 u
->in_cgroup_realize_queue
= false;
1804 /* Check if necessary controllers and attributes for a unit are in place.
1806 * If so, do nothing.
1807 * If not, create paths, move processes over, and set attributes.
1809 * Returns 0 on success and < 0 on failure. */
1810 static int unit_realize_cgroup_now(Unit
*u
, ManagerState state
) {
1811 CGroupMask target_mask
, enable_mask
;
1816 unit_remove_from_cgroup_realize_queue(u
);
1818 target_mask
= unit_get_target_mask(u
);
1819 enable_mask
= unit_get_enable_mask(u
);
1821 if (unit_has_mask_realized(u
, target_mask
, enable_mask
))
1824 /* First, realize parents */
1825 if (UNIT_ISSET(u
->slice
)) {
1826 r
= unit_realize_cgroup_now(UNIT_DEREF(u
->slice
), state
);
1831 /* And then do the real work */
1832 r
= unit_create_cgroup(u
, target_mask
, enable_mask
);
1836 /* Finally, apply the necessary attributes. */
1837 cgroup_context_apply(u
, target_mask
, state
);
1838 cgroup_xattr_apply(u
);
1843 unsigned manager_dispatch_cgroup_realize_queue(Manager
*m
) {
1851 state
= manager_state(m
);
1853 while ((i
= m
->cgroup_realize_queue
)) {
1854 assert(i
->in_cgroup_realize_queue
);
1856 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i
))) {
1857 /* Maybe things changed, and the unit is not actually active anymore? */
1858 unit_remove_from_cgroup_realize_queue(i
);
1862 r
= unit_realize_cgroup_now(i
, state
);
1864 log_warning_errno(r
, "Failed to realize cgroups for queued unit %s, ignoring: %m", i
->id
);
1872 static void unit_add_siblings_to_cgroup_realize_queue(Unit
*u
) {
1875 /* This adds the siblings of the specified unit and the
1876 * siblings of all parent units to the cgroup queue. (But
1877 * neither the specified unit itself nor the parents.) */
1879 while ((slice
= UNIT_DEREF(u
->slice
))) {
1884 HASHMAP_FOREACH_KEY(v
, m
, u
->dependencies
[UNIT_BEFORE
], i
) {
1888 /* Skip units that have a dependency on the slice
1889 * but aren't actually in it. */
1890 if (UNIT_DEREF(m
->slice
) != slice
)
1893 /* No point in doing cgroup application for units
1894 * without active processes. */
1895 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m
)))
1898 /* If the unit doesn't need any new controllers
1899 * and has current ones realized, it doesn't need
1901 if (unit_has_mask_realized(m
,
1902 unit_get_target_mask(m
),
1903 unit_get_enable_mask(m
)))
1906 unit_add_to_cgroup_realize_queue(m
);
1913 int unit_realize_cgroup(Unit
*u
) {
1916 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1919 /* So, here's the deal: when realizing the cgroups for this
1920 * unit, we need to first create all parents, but there's more
1921 * actually: for the weight-based controllers we also need to
1922 * make sure that all our siblings (i.e. units that are in the
1923 * same slice as we are) have cgroups, too. Otherwise, things
1924 * would become very uneven as each of their processes would
1925 * get as much resources as all our group together. This call
1926 * will synchronously create the parent cgroups, but will
1927 * defer work on the siblings to the next event loop
1930 /* Add all sibling slices to the cgroup queue. */
1931 unit_add_siblings_to_cgroup_realize_queue(u
);
1933 /* And realize this one now (and apply the values) */
1934 return unit_realize_cgroup_now(u
, manager_state(u
->manager
));
1937 void unit_release_cgroup(Unit
*u
) {
1940 /* Forgets all cgroup details for this cgroup */
1942 if (u
->cgroup_path
) {
1943 (void) hashmap_remove(u
->manager
->cgroup_unit
, u
->cgroup_path
);
1944 u
->cgroup_path
= mfree(u
->cgroup_path
);
1947 if (u
->cgroup_inotify_wd
>= 0) {
1948 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_inotify_wd
) < 0)
1949 log_unit_debug_errno(u
, errno
, "Failed to remove cgroup inotify watch %i for %s, ignoring", u
->cgroup_inotify_wd
, u
->id
);
1951 (void) hashmap_remove(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
));
1952 u
->cgroup_inotify_wd
= -1;
1956 void unit_prune_cgroup(Unit
*u
) {
1962 /* Removes the cgroup, if empty and possible, and stops watching it. */
1964 if (!u
->cgroup_path
)
1967 (void) unit_get_cpu_usage(u
, NULL
); /* Cache the last CPU usage value before we destroy the cgroup */
1969 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
1971 r
= cg_trim_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, !is_root_slice
);
1973 log_unit_debug_errno(u
, r
, "Failed to destroy cgroup %s, ignoring: %m", u
->cgroup_path
);
1980 unit_release_cgroup(u
);
1982 u
->cgroup_realized
= false;
1983 u
->cgroup_realized_mask
= 0;
1984 u
->cgroup_enabled_mask
= 0;
1986 u
->bpf_device_control_installed
= bpf_program_unref(u
->bpf_device_control_installed
);
1989 int unit_search_main_pid(Unit
*u
, pid_t
*ret
) {
1990 _cleanup_fclose_
FILE *f
= NULL
;
1991 pid_t pid
= 0, npid
, mypid
;
1997 if (!u
->cgroup_path
)
2000 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, &f
);
2004 mypid
= getpid_cached();
2005 while (cg_read_pid(f
, &npid
) > 0) {
2011 /* Ignore processes that aren't our kids */
2012 if (get_process_ppid(npid
, &ppid
) >= 0 && ppid
!= mypid
)
2016 /* Dang, there's more than one daemonized PID
2017 in this group, so we don't know what process
2018 is the main process. */
2029 static int unit_watch_pids_in_path(Unit
*u
, const char *path
) {
2030 _cleanup_closedir_
DIR *d
= NULL
;
2031 _cleanup_fclose_
FILE *f
= NULL
;
2037 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
);
2043 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
2044 r
= unit_watch_pid(u
, pid
);
2045 if (r
< 0 && ret
>= 0)
2049 if (r
< 0 && ret
>= 0)
2053 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
2060 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
2061 _cleanup_free_
char *p
= NULL
;
2063 p
= strjoin(path
, "/", fn
);
2069 r
= unit_watch_pids_in_path(u
, p
);
2070 if (r
< 0 && ret
>= 0)
2074 if (r
< 0 && ret
>= 0)
2081 int unit_synthesize_cgroup_empty_event(Unit
*u
) {
2086 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
2087 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
2088 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
2090 if (!u
->cgroup_path
)
2093 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2096 if (r
> 0) /* On unified we have reliable notifications, and don't need this */
2099 if (!set_isempty(u
->pids
))
2102 unit_add_to_cgroup_empty_queue(u
);
2106 int unit_watch_all_pids(Unit
*u
) {
2111 /* Adds all PIDs from our cgroup to the set of PIDs we
2112 * watch. This is a fallback logic for cases where we do not
2113 * get reliable cgroup empty notifications: we try to use
2114 * SIGCHLD as replacement. */
2116 if (!u
->cgroup_path
)
2119 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2122 if (r
> 0) /* On unified we can use proper notifications */
2125 return unit_watch_pids_in_path(u
, u
->cgroup_path
);
2128 static int on_cgroup_empty_event(sd_event_source
*s
, void *userdata
) {
2129 Manager
*m
= userdata
;
2136 u
= m
->cgroup_empty_queue
;
2140 assert(u
->in_cgroup_empty_queue
);
2141 u
->in_cgroup_empty_queue
= false;
2142 LIST_REMOVE(cgroup_empty_queue
, m
->cgroup_empty_queue
, u
);
2144 if (m
->cgroup_empty_queue
) {
2145 /* More stuff queued, let's make sure we remain enabled */
2146 r
= sd_event_source_set_enabled(s
, SD_EVENT_ONESHOT
);
2148 log_debug_errno(r
, "Failed to reenable cgroup empty event source, ignoring: %m");
2151 unit_add_to_gc_queue(u
);
2153 if (UNIT_VTABLE(u
)->notify_cgroup_empty
)
2154 UNIT_VTABLE(u
)->notify_cgroup_empty(u
);
2159 void unit_add_to_cgroup_empty_queue(Unit
*u
) {
2164 /* Note that there are four different ways how cgroup empty events reach us:
2166 * 1. On the unified hierarchy we get an inotify event on the cgroup
2168 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2170 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2172 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2173 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2175 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2176 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2177 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2178 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2179 * case for scope units). */
2181 if (u
->in_cgroup_empty_queue
)
2184 /* Let's verify that the cgroup is really empty */
2185 if (!u
->cgroup_path
)
2187 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
2189 log_unit_debug_errno(u
, r
, "Failed to determine whether cgroup %s is empty: %m", u
->cgroup_path
);
2195 LIST_PREPEND(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
2196 u
->in_cgroup_empty_queue
= true;
2198 /* Trigger the defer event */
2199 r
= sd_event_source_set_enabled(u
->manager
->cgroup_empty_event_source
, SD_EVENT_ONESHOT
);
2201 log_debug_errno(r
, "Failed to enable cgroup empty event source: %m");
2204 static int on_cgroup_inotify_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
2205 Manager
*m
= userdata
;
2212 union inotify_event_buffer buffer
;
2213 struct inotify_event
*e
;
2216 l
= read(fd
, &buffer
, sizeof(buffer
));
2218 if (IN_SET(errno
, EINTR
, EAGAIN
))
2221 return log_error_errno(errno
, "Failed to read control group inotify events: %m");
2224 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
2228 /* Queue overflow has no watch descriptor */
2231 if (e
->mask
& IN_IGNORED
)
2232 /* The watch was just removed */
2235 u
= hashmap_get(m
->cgroup_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
2236 if (!u
) /* Not that inotify might deliver
2237 * events for a watch even after it
2238 * was removed, because it was queued
2239 * before the removal. Let's ignore
2240 * this here safely. */
2243 unit_add_to_cgroup_empty_queue(u
);
2248 static int cg_bpf_mask_supported(CGroupMask
*ret
) {
2249 CGroupMask mask
= 0;
2252 /* BPF-based firewall */
2253 r
= bpf_firewall_supported();
2255 mask
|= CGROUP_MASK_BPF_FIREWALL
;
2257 /* BPF-based device access control */
2258 r
= bpf_devices_supported();
2260 mask
|= CGROUP_MASK_BPF_DEVICES
;
2266 int manager_setup_cgroup(Manager
*m
) {
2267 _cleanup_free_
char *path
= NULL
;
2268 const char *scope_path
;
2276 /* 1. Determine hierarchy */
2277 m
->cgroup_root
= mfree(m
->cgroup_root
);
2278 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &m
->cgroup_root
);
2280 return log_error_errno(r
, "Cannot determine cgroup we are running in: %m");
2282 /* Chop off the init scope, if we are already located in it */
2283 e
= endswith(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2285 /* LEGACY: Also chop off the system slice if we are in
2286 * it. This is to support live upgrades from older systemd
2287 * versions where PID 1 was moved there. Also see
2288 * cg_get_root_path(). */
2289 if (!e
&& MANAGER_IS_SYSTEM(m
)) {
2290 e
= endswith(m
->cgroup_root
, "/" SPECIAL_SYSTEM_SLICE
);
2292 e
= endswith(m
->cgroup_root
, "/system"); /* even more legacy */
2297 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2298 * easily prepend it everywhere. */
2299 delete_trailing_chars(m
->cgroup_root
, "/");
2302 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, NULL
, &path
);
2304 return log_error_errno(r
, "Cannot find cgroup mount point: %m");
2306 r
= cg_unified_flush();
2308 return log_error_errno(r
, "Couldn't determine if we are running in the unified hierarchy: %m");
2310 all_unified
= cg_all_unified();
2311 if (all_unified
< 0)
2312 return log_error_errno(all_unified
, "Couldn't determine whether we are in all unified mode: %m");
2313 if (all_unified
> 0)
2314 log_debug("Unified cgroup hierarchy is located at %s.", path
);
2316 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2318 return log_error_errno(r
, "Failed to determine whether systemd's own controller is in unified mode: %m");
2320 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path
);
2322 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY
". File system hierarchy is at %s.", path
);
2325 /* 3. Allocate cgroup empty defer event source */
2326 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2327 r
= sd_event_add_defer(m
->event
, &m
->cgroup_empty_event_source
, on_cgroup_empty_event
, m
);
2329 return log_error_errno(r
, "Failed to create cgroup empty event source: %m");
2331 r
= sd_event_source_set_priority(m
->cgroup_empty_event_source
, SD_EVENT_PRIORITY_NORMAL
-5);
2333 return log_error_errno(r
, "Failed to set priority of cgroup empty event source: %m");
2335 r
= sd_event_source_set_enabled(m
->cgroup_empty_event_source
, SD_EVENT_OFF
);
2337 return log_error_errno(r
, "Failed to disable cgroup empty event source: %m");
2339 (void) sd_event_source_set_description(m
->cgroup_empty_event_source
, "cgroup-empty");
2341 /* 4. Install notifier inotify object, or agent */
2342 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0) {
2344 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2346 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2347 safe_close(m
->cgroup_inotify_fd
);
2349 m
->cgroup_inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
2350 if (m
->cgroup_inotify_fd
< 0)
2351 return log_error_errno(errno
, "Failed to create control group inotify object: %m");
2353 r
= sd_event_add_io(m
->event
, &m
->cgroup_inotify_event_source
, m
->cgroup_inotify_fd
, EPOLLIN
, on_cgroup_inotify_event
, m
);
2355 return log_error_errno(r
, "Failed to watch control group inotify object: %m");
2357 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
2358 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2359 r
= sd_event_source_set_priority(m
->cgroup_inotify_event_source
, SD_EVENT_PRIORITY_NORMAL
-4);
2361 return log_error_errno(r
, "Failed to set priority of inotify event source: %m");
2363 (void) sd_event_source_set_description(m
->cgroup_inotify_event_source
, "cgroup-inotify");
2365 } else if (MANAGER_IS_SYSTEM(m
) && m
->test_run_flags
== 0) {
2367 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2368 * since it does not generate events when control groups with children run empty. */
2370 r
= cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER
, SYSTEMD_CGROUP_AGENT_PATH
);
2372 log_warning_errno(r
, "Failed to install release agent, ignoring: %m");
2374 log_debug("Installed release agent.");
2376 log_debug("Release agent already installed.");
2379 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2380 scope_path
= strjoina(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2381 r
= cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2383 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2384 r
= cg_migrate(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2386 log_warning_errno(r
, "Couldn't move remaining userspace processes, ignoring: %m");
2388 /* 6. And pin it, so that it cannot be unmounted */
2389 safe_close(m
->pin_cgroupfs_fd
);
2390 m
->pin_cgroupfs_fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
2391 if (m
->pin_cgroupfs_fd
< 0)
2392 return log_error_errno(errno
, "Failed to open pin file: %m");
2394 } else if (!m
->test_run_flags
)
2395 return log_error_errno(r
, "Failed to create %s control group: %m", scope_path
);
2397 /* 7. Always enable hierarchical support if it exists... */
2398 if (!all_unified
&& m
->test_run_flags
== 0)
2399 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
2401 /* 8. Figure out which controllers are supported */
2402 r
= cg_mask_supported(&m
->cgroup_supported
);
2404 return log_error_errno(r
, "Failed to determine supported controllers: %m");
2406 /* 9. Figure out which bpf-based pseudo-controllers are supported */
2407 r
= cg_bpf_mask_supported(&mask
);
2409 return log_error_errno(r
, "Failed to determine supported bpf-based pseudo-controllers: %m");
2410 m
->cgroup_supported
|= mask
;
2412 /* 10. Log which controllers are supported */
2413 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++)
2414 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c
), yes_no(m
->cgroup_supported
& CGROUP_CONTROLLER_TO_MASK(c
)));
2419 void manager_shutdown_cgroup(Manager
*m
, bool delete) {
2422 /* We can't really delete the group, since we are in it. But
2424 if (delete && m
->cgroup_root
&& m
->test_run_flags
!= MANAGER_TEST_RUN_MINIMAL
)
2425 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, false);
2427 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2429 m
->cgroup_inotify_wd_unit
= hashmap_free(m
->cgroup_inotify_wd_unit
);
2431 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2432 m
->cgroup_inotify_fd
= safe_close(m
->cgroup_inotify_fd
);
2434 m
->pin_cgroupfs_fd
= safe_close(m
->pin_cgroupfs_fd
);
2436 m
->cgroup_root
= mfree(m
->cgroup_root
);
2439 Unit
* manager_get_unit_by_cgroup(Manager
*m
, const char *cgroup
) {
2446 u
= hashmap_get(m
->cgroup_unit
, cgroup
);
2450 p
= strdupa(cgroup
);
2454 e
= strrchr(p
, '/');
2456 return hashmap_get(m
->cgroup_unit
, SPECIAL_ROOT_SLICE
);
2460 u
= hashmap_get(m
->cgroup_unit
, p
);
2466 Unit
*manager_get_unit_by_pid_cgroup(Manager
*m
, pid_t pid
) {
2467 _cleanup_free_
char *cgroup
= NULL
;
2471 if (!pid_is_valid(pid
))
2474 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &cgroup
) < 0)
2477 return manager_get_unit_by_cgroup(m
, cgroup
);
2480 Unit
*manager_get_unit_by_pid(Manager
*m
, pid_t pid
) {
2485 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
2486 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
2487 * relevant one as children of the process will be assigned to that one, too, before all else. */
2489 if (!pid_is_valid(pid
))
2492 if (pid
== getpid_cached())
2493 return hashmap_get(m
->units
, SPECIAL_INIT_SCOPE
);
2495 u
= manager_get_unit_by_pid_cgroup(m
, pid
);
2499 u
= hashmap_get(m
->watch_pids
, PID_TO_PTR(pid
));
2503 array
= hashmap_get(m
->watch_pids
, PID_TO_PTR(-pid
));
2510 int manager_notify_cgroup_empty(Manager
*m
, const char *cgroup
) {
2516 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
2517 * or from the --system instance */
2519 log_debug("Got cgroup empty notification for: %s", cgroup
);
2521 u
= manager_get_unit_by_cgroup(m
, cgroup
);
2525 unit_add_to_cgroup_empty_queue(u
);
2529 int unit_get_memory_current(Unit
*u
, uint64_t *ret
) {
2530 _cleanup_free_
char *v
= NULL
;
2536 if (!UNIT_CGROUP_BOOL(u
, memory_accounting
))
2539 if (!u
->cgroup_path
)
2542 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2543 if (unit_has_root_cgroup(u
))
2544 return procfs_memory_get_current(ret
);
2546 if ((u
->cgroup_realized_mask
& CGROUP_MASK_MEMORY
) == 0)
2549 r
= cg_all_unified();
2553 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.current", &v
);
2555 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.usage_in_bytes", &v
);
2561 return safe_atou64(v
, ret
);
2564 int unit_get_tasks_current(Unit
*u
, uint64_t *ret
) {
2565 _cleanup_free_
char *v
= NULL
;
2571 if (!UNIT_CGROUP_BOOL(u
, tasks_accounting
))
2574 if (!u
->cgroup_path
)
2577 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2578 if (unit_has_root_cgroup(u
))
2579 return procfs_tasks_get_current(ret
);
2581 if ((u
->cgroup_realized_mask
& CGROUP_MASK_PIDS
) == 0)
2584 r
= cg_get_attribute("pids", u
->cgroup_path
, "pids.current", &v
);
2590 return safe_atou64(v
, ret
);
2593 static int unit_get_cpu_usage_raw(Unit
*u
, nsec_t
*ret
) {
2594 _cleanup_free_
char *v
= NULL
;
2601 if (!u
->cgroup_path
)
2604 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2605 if (unit_has_root_cgroup(u
))
2606 return procfs_cpu_get_usage(ret
);
2608 r
= cg_all_unified();
2612 _cleanup_free_
char *val
= NULL
;
2615 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPU
) == 0)
2618 r
= cg_get_keyed_attribute("cpu", u
->cgroup_path
, "cpu.stat", STRV_MAKE("usage_usec"), &val
);
2621 if (IN_SET(r
, -ENOENT
, -ENXIO
))
2624 r
= safe_atou64(val
, &us
);
2628 ns
= us
* NSEC_PER_USEC
;
2630 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPUACCT
) == 0)
2633 r
= cg_get_attribute("cpuacct", u
->cgroup_path
, "cpuacct.usage", &v
);
2639 r
= safe_atou64(v
, &ns
);
2648 int unit_get_cpu_usage(Unit
*u
, nsec_t
*ret
) {
2654 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2655 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2656 * call this function with a NULL return value. */
2658 if (!UNIT_CGROUP_BOOL(u
, cpu_accounting
))
2661 r
= unit_get_cpu_usage_raw(u
, &ns
);
2662 if (r
== -ENODATA
&& u
->cpu_usage_last
!= NSEC_INFINITY
) {
2663 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2667 *ret
= u
->cpu_usage_last
;
2673 if (ns
> u
->cpu_usage_base
)
2674 ns
-= u
->cpu_usage_base
;
2678 u
->cpu_usage_last
= ns
;
2685 int unit_get_ip_accounting(
2687 CGroupIPAccountingMetric metric
,
2694 assert(metric
>= 0);
2695 assert(metric
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
);
2698 if (!UNIT_CGROUP_BOOL(u
, ip_accounting
))
2701 fd
= IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_INGRESS_PACKETS
) ?
2702 u
->ip_accounting_ingress_map_fd
:
2703 u
->ip_accounting_egress_map_fd
;
2707 if (IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_EGRESS_BYTES
))
2708 r
= bpf_firewall_read_accounting(fd
, &value
, NULL
);
2710 r
= bpf_firewall_read_accounting(fd
, NULL
, &value
);
2714 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
2715 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
2716 * ip_accounting_extra[] field, and add them in here transparently. */
2718 *ret
= value
+ u
->ip_accounting_extra
[metric
];
2723 int unit_reset_cpu_accounting(Unit
*u
) {
2729 u
->cpu_usage_last
= NSEC_INFINITY
;
2731 r
= unit_get_cpu_usage_raw(u
, &ns
);
2733 u
->cpu_usage_base
= 0;
2737 u
->cpu_usage_base
= ns
;
2741 int unit_reset_ip_accounting(Unit
*u
) {
2746 if (u
->ip_accounting_ingress_map_fd
>= 0)
2747 r
= bpf_firewall_reset_accounting(u
->ip_accounting_ingress_map_fd
);
2749 if (u
->ip_accounting_egress_map_fd
>= 0)
2750 q
= bpf_firewall_reset_accounting(u
->ip_accounting_egress_map_fd
);
2752 zero(u
->ip_accounting_extra
);
2754 return r
< 0 ? r
: q
;
2757 void unit_invalidate_cgroup(Unit
*u
, CGroupMask m
) {
2760 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2766 /* always invalidate compat pairs together */
2767 if (m
& (CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
))
2768 m
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
2770 if (m
& (CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
))
2771 m
|= CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
;
2773 if ((u
->cgroup_realized_mask
& m
) == 0) /* NOP? */
2776 u
->cgroup_realized_mask
&= ~m
;
2777 unit_add_to_cgroup_realize_queue(u
);
2780 void unit_invalidate_cgroup_bpf(Unit
*u
) {
2783 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2786 if (u
->cgroup_invalidated_mask
& CGROUP_MASK_BPF_FIREWALL
) /* NOP? */
2789 u
->cgroup_invalidated_mask
|= CGROUP_MASK_BPF_FIREWALL
;
2790 unit_add_to_cgroup_realize_queue(u
);
2792 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
2793 * list of our children includes our own. */
2794 if (u
->type
== UNIT_SLICE
) {
2799 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
2803 if (UNIT_DEREF(member
->slice
) != u
)
2806 unit_invalidate_cgroup_bpf(member
);
2811 bool unit_cgroup_delegate(Unit
*u
) {
2816 if (!UNIT_VTABLE(u
)->can_delegate
)
2819 c
= unit_get_cgroup_context(u
);
2826 void manager_invalidate_startup_units(Manager
*m
) {
2832 SET_FOREACH(u
, m
->startup_units
, i
)
2833 unit_invalidate_cgroup(u
, CGROUP_MASK_CPU
|CGROUP_MASK_IO
|CGROUP_MASK_BLKIO
);
2836 static const char* const cgroup_device_policy_table
[_CGROUP_DEVICE_POLICY_MAX
] = {
2837 [CGROUP_AUTO
] = "auto",
2838 [CGROUP_CLOSED
] = "closed",
2839 [CGROUP_STRICT
] = "strict",
2842 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy
, CGroupDevicePolicy
);