1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2013 Lennart Poettering
9 #include "alloc-util.h"
10 #include "blockdev-util.h"
11 #include "bpf-firewall.h"
12 #include "btrfs-util.h"
13 #include "bus-error.h"
14 #include "cgroup-util.h"
19 #include "parse-util.h"
20 #include "path-util.h"
21 #include "process-util.h"
22 #include "procfs-util.h"
24 #include "stdio-util.h"
25 #include "string-table.h"
26 #include "string-util.h"
29 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
31 bool manager_owns_root_cgroup(Manager
*m
) {
34 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
35 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
36 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
37 * we run in any kind of container virtualization. */
39 if (detect_container() > 0)
42 return empty_or_root(m
->cgroup_root
);
45 bool unit_has_root_cgroup(Unit
*u
) {
48 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
49 * the manager manages the root cgroup. */
51 if (!manager_owns_root_cgroup(u
->manager
))
54 return unit_has_name(u
, SPECIAL_ROOT_SLICE
);
57 static void cgroup_compat_warn(void) {
58 static bool cgroup_compat_warned
= false;
60 if (cgroup_compat_warned
)
63 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
64 "See cgroup-compat debug messages for details.");
66 cgroup_compat_warned
= true;
69 #define log_cgroup_compat(unit, fmt, ...) do { \
70 cgroup_compat_warn(); \
71 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
74 void cgroup_context_init(CGroupContext
*c
) {
77 /* Initialize everything to the kernel defaults, assuming the
78 * structure is preinitialized to 0 */
80 c
->cpu_weight
= CGROUP_WEIGHT_INVALID
;
81 c
->startup_cpu_weight
= CGROUP_WEIGHT_INVALID
;
82 c
->cpu_quota_per_sec_usec
= USEC_INFINITY
;
84 c
->cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
85 c
->startup_cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
87 c
->memory_high
= CGROUP_LIMIT_MAX
;
88 c
->memory_max
= CGROUP_LIMIT_MAX
;
89 c
->memory_swap_max
= CGROUP_LIMIT_MAX
;
91 c
->memory_limit
= CGROUP_LIMIT_MAX
;
93 c
->io_weight
= CGROUP_WEIGHT_INVALID
;
94 c
->startup_io_weight
= CGROUP_WEIGHT_INVALID
;
96 c
->blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
97 c
->startup_blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
99 c
->tasks_max
= (uint64_t) -1;
102 void cgroup_context_free_device_allow(CGroupContext
*c
, CGroupDeviceAllow
*a
) {
106 LIST_REMOVE(device_allow
, c
->device_allow
, a
);
111 void cgroup_context_free_io_device_weight(CGroupContext
*c
, CGroupIODeviceWeight
*w
) {
115 LIST_REMOVE(device_weights
, c
->io_device_weights
, w
);
120 void cgroup_context_free_io_device_limit(CGroupContext
*c
, CGroupIODeviceLimit
*l
) {
124 LIST_REMOVE(device_limits
, c
->io_device_limits
, l
);
129 void cgroup_context_free_blockio_device_weight(CGroupContext
*c
, CGroupBlockIODeviceWeight
*w
) {
133 LIST_REMOVE(device_weights
, c
->blockio_device_weights
, w
);
138 void cgroup_context_free_blockio_device_bandwidth(CGroupContext
*c
, CGroupBlockIODeviceBandwidth
*b
) {
142 LIST_REMOVE(device_bandwidths
, c
->blockio_device_bandwidths
, b
);
147 void cgroup_context_done(CGroupContext
*c
) {
150 while (c
->io_device_weights
)
151 cgroup_context_free_io_device_weight(c
, c
->io_device_weights
);
153 while (c
->io_device_limits
)
154 cgroup_context_free_io_device_limit(c
, c
->io_device_limits
);
156 while (c
->blockio_device_weights
)
157 cgroup_context_free_blockio_device_weight(c
, c
->blockio_device_weights
);
159 while (c
->blockio_device_bandwidths
)
160 cgroup_context_free_blockio_device_bandwidth(c
, c
->blockio_device_bandwidths
);
162 while (c
->device_allow
)
163 cgroup_context_free_device_allow(c
, c
->device_allow
);
165 c
->ip_address_allow
= ip_address_access_free_all(c
->ip_address_allow
);
166 c
->ip_address_deny
= ip_address_access_free_all(c
->ip_address_deny
);
169 void cgroup_context_dump(CGroupContext
*c
, FILE* f
, const char *prefix
) {
170 CGroupIODeviceLimit
*il
;
171 CGroupIODeviceWeight
*iw
;
172 CGroupBlockIODeviceBandwidth
*b
;
173 CGroupBlockIODeviceWeight
*w
;
174 CGroupDeviceAllow
*a
;
175 IPAddressAccessItem
*iaai
;
176 char u
[FORMAT_TIMESPAN_MAX
];
181 prefix
= strempty(prefix
);
184 "%sCPUAccounting=%s\n"
185 "%sIOAccounting=%s\n"
186 "%sBlockIOAccounting=%s\n"
187 "%sMemoryAccounting=%s\n"
188 "%sTasksAccounting=%s\n"
189 "%sIPAccounting=%s\n"
190 "%sCPUWeight=%" PRIu64
"\n"
191 "%sStartupCPUWeight=%" PRIu64
"\n"
192 "%sCPUShares=%" PRIu64
"\n"
193 "%sStartupCPUShares=%" PRIu64
"\n"
194 "%sCPUQuotaPerSecSec=%s\n"
195 "%sIOWeight=%" PRIu64
"\n"
196 "%sStartupIOWeight=%" PRIu64
"\n"
197 "%sBlockIOWeight=%" PRIu64
"\n"
198 "%sStartupBlockIOWeight=%" PRIu64
"\n"
199 "%sMemoryLow=%" PRIu64
"\n"
200 "%sMemoryHigh=%" PRIu64
"\n"
201 "%sMemoryMax=%" PRIu64
"\n"
202 "%sMemorySwapMax=%" PRIu64
"\n"
203 "%sMemoryLimit=%" PRIu64
"\n"
204 "%sTasksMax=%" PRIu64
"\n"
205 "%sDevicePolicy=%s\n"
207 prefix
, yes_no(c
->cpu_accounting
),
208 prefix
, yes_no(c
->io_accounting
),
209 prefix
, yes_no(c
->blockio_accounting
),
210 prefix
, yes_no(c
->memory_accounting
),
211 prefix
, yes_no(c
->tasks_accounting
),
212 prefix
, yes_no(c
->ip_accounting
),
213 prefix
, c
->cpu_weight
,
214 prefix
, c
->startup_cpu_weight
,
215 prefix
, c
->cpu_shares
,
216 prefix
, c
->startup_cpu_shares
,
217 prefix
, format_timespan(u
, sizeof(u
), c
->cpu_quota_per_sec_usec
, 1),
218 prefix
, c
->io_weight
,
219 prefix
, c
->startup_io_weight
,
220 prefix
, c
->blockio_weight
,
221 prefix
, c
->startup_blockio_weight
,
222 prefix
, c
->memory_low
,
223 prefix
, c
->memory_high
,
224 prefix
, c
->memory_max
,
225 prefix
, c
->memory_swap_max
,
226 prefix
, c
->memory_limit
,
227 prefix
, c
->tasks_max
,
228 prefix
, cgroup_device_policy_to_string(c
->device_policy
),
229 prefix
, yes_no(c
->delegate
));
232 _cleanup_free_
char *t
= NULL
;
234 (void) cg_mask_to_string(c
->delegate_controllers
, &t
);
236 fprintf(f
, "%sDelegateControllers=%s\n",
241 LIST_FOREACH(device_allow
, a
, c
->device_allow
)
243 "%sDeviceAllow=%s %s%s%s\n",
246 a
->r
? "r" : "", a
->w
? "w" : "", a
->m
? "m" : "");
248 LIST_FOREACH(device_weights
, iw
, c
->io_device_weights
)
250 "%sIODeviceWeight=%s %" PRIu64
,
255 LIST_FOREACH(device_limits
, il
, c
->io_device_limits
) {
256 char buf
[FORMAT_BYTES_MAX
];
257 CGroupIOLimitType type
;
259 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
260 if (il
->limits
[type
] != cgroup_io_limit_defaults
[type
])
264 cgroup_io_limit_type_to_string(type
),
266 format_bytes(buf
, sizeof(buf
), il
->limits
[type
]));
269 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
271 "%sBlockIODeviceWeight=%s %" PRIu64
,
276 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
277 char buf
[FORMAT_BYTES_MAX
];
279 if (b
->rbps
!= CGROUP_LIMIT_MAX
)
281 "%sBlockIOReadBandwidth=%s %s\n",
284 format_bytes(buf
, sizeof(buf
), b
->rbps
));
285 if (b
->wbps
!= CGROUP_LIMIT_MAX
)
287 "%sBlockIOWriteBandwidth=%s %s\n",
290 format_bytes(buf
, sizeof(buf
), b
->wbps
));
293 LIST_FOREACH(items
, iaai
, c
->ip_address_allow
) {
294 _cleanup_free_
char *k
= NULL
;
296 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
297 fprintf(f
, "%sIPAddressAllow=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
300 LIST_FOREACH(items
, iaai
, c
->ip_address_deny
) {
301 _cleanup_free_
char *k
= NULL
;
303 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
304 fprintf(f
, "%sIPAddressDeny=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
308 static int lookup_block_device(const char *p
, dev_t
*ret
) {
315 if (stat(p
, &st
) < 0)
316 return log_warning_errno(errno
, "Couldn't stat device '%s': %m", p
);
318 if (S_ISBLK(st
.st_mode
))
320 else if (major(st
.st_dev
) != 0)
321 *ret
= st
.st_dev
; /* If this is not a device node then use the block device this file is stored on */
323 /* If this is btrfs, getting the backing block device is a bit harder */
324 r
= btrfs_get_block_device(p
, ret
);
325 if (r
< 0 && r
!= -ENOTTY
)
326 return log_warning_errno(r
, "Failed to determine block device backing btrfs file system '%s': %m", p
);
328 log_warning("'%s' is not a block device node, and file system block device cannot be determined or is not local.", p
);
333 /* If this is a LUKS device, try to get the originating block device */
334 (void) block_get_originating(*ret
, ret
);
336 /* If this is a partition, try to get the originating block device */
337 (void) block_get_whole_disk(*ret
, ret
);
341 static int whitelist_device(const char *path
, const char *node
, const char *acc
) {
342 char buf
[2+DECIMAL_STR_MAX(dev_t
)*2+2+4];
344 bool ignore_notfound
;
350 if (node
[0] == '-') {
351 /* Non-existent paths starting with "-" must be silently ignored */
353 ignore_notfound
= true;
355 ignore_notfound
= false;
357 if (stat(node
, &st
) < 0) {
358 if (errno
== ENOENT
&& ignore_notfound
)
361 return log_warning_errno(errno
, "Couldn't stat device %s: %m", node
);
364 if (!S_ISCHR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
365 log_warning("%s is not a device.", node
);
371 S_ISCHR(st
.st_mode
) ? 'c' : 'b',
372 major(st
.st_rdev
), minor(st
.st_rdev
),
375 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
377 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
378 "Failed to set devices.allow on %s: %m", path
);
383 static int whitelist_major(const char *path
, const char *name
, char type
, const char *acc
) {
384 _cleanup_fclose_
FILE *f
= NULL
;
391 assert(IN_SET(type
, 'b', 'c'));
393 f
= fopen("/proc/devices", "re");
395 return log_warning_errno(errno
, "Cannot open /proc/devices to resolve %s (%c): %m", name
, type
);
397 FOREACH_LINE(line
, f
, goto fail
) {
398 char buf
[2+DECIMAL_STR_MAX(unsigned)+3+4], *p
, *w
;
403 if (type
== 'c' && streq(line
, "Character devices:")) {
408 if (type
== 'b' && streq(line
, "Block devices:")) {
423 w
= strpbrk(p
, WHITESPACE
);
428 r
= safe_atou(p
, &maj
);
435 w
+= strspn(w
, WHITESPACE
);
437 if (fnmatch(name
, w
, 0) != 0)
446 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
448 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
449 "Failed to set devices.allow on %s: %m", path
);
455 return log_warning_errno(errno
, "Failed to read /proc/devices: %m");
458 static bool cgroup_context_has_cpu_weight(CGroupContext
*c
) {
459 return c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
||
460 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
;
463 static bool cgroup_context_has_cpu_shares(CGroupContext
*c
) {
464 return c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
465 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
;
468 static uint64_t cgroup_context_cpu_weight(CGroupContext
*c
, ManagerState state
) {
469 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
470 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
)
471 return c
->startup_cpu_weight
;
472 else if (c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
)
473 return c
->cpu_weight
;
475 return CGROUP_WEIGHT_DEFAULT
;
478 static uint64_t cgroup_context_cpu_shares(CGroupContext
*c
, ManagerState state
) {
479 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
480 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
481 return c
->startup_cpu_shares
;
482 else if (c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
483 return c
->cpu_shares
;
485 return CGROUP_CPU_SHARES_DEFAULT
;
488 static void cgroup_apply_unified_cpu_config(Unit
*u
, uint64_t weight
, uint64_t quota
) {
489 char buf
[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t
) + 1) * 2)];
492 xsprintf(buf
, "%" PRIu64
"\n", weight
);
493 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.weight", buf
);
495 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
496 "Failed to set cpu.weight: %m");
498 if (quota
!= USEC_INFINITY
)
499 xsprintf(buf
, USEC_FMT
" " USEC_FMT
"\n",
500 quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
, CGROUP_CPU_QUOTA_PERIOD_USEC
);
502 xsprintf(buf
, "max " USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
504 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.max", buf
);
507 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
508 "Failed to set cpu.max: %m");
511 static void cgroup_apply_legacy_cpu_config(Unit
*u
, uint64_t shares
, uint64_t quota
) {
512 char buf
[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t
)) + 1];
515 xsprintf(buf
, "%" PRIu64
"\n", shares
);
516 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.shares", buf
);
518 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
519 "Failed to set cpu.shares: %m");
521 xsprintf(buf
, USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
522 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_period_us", buf
);
524 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
525 "Failed to set cpu.cfs_period_us: %m");
527 if (quota
!= USEC_INFINITY
) {
528 xsprintf(buf
, USEC_FMT
"\n", quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
);
529 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", buf
);
531 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", "-1");
533 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
534 "Failed to set cpu.cfs_quota_us: %m");
537 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares
) {
538 return CLAMP(shares
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_CPU_SHARES_DEFAULT
,
539 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
542 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight
) {
543 return CLAMP(weight
* CGROUP_CPU_SHARES_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
544 CGROUP_CPU_SHARES_MIN
, CGROUP_CPU_SHARES_MAX
);
547 static bool cgroup_context_has_io_config(CGroupContext
*c
) {
548 return c
->io_accounting
||
549 c
->io_weight
!= CGROUP_WEIGHT_INVALID
||
550 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
551 c
->io_device_weights
||
555 static bool cgroup_context_has_blockio_config(CGroupContext
*c
) {
556 return c
->blockio_accounting
||
557 c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
558 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
559 c
->blockio_device_weights
||
560 c
->blockio_device_bandwidths
;
563 static uint64_t cgroup_context_io_weight(CGroupContext
*c
, ManagerState state
) {
564 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
565 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
)
566 return c
->startup_io_weight
;
567 else if (c
->io_weight
!= CGROUP_WEIGHT_INVALID
)
570 return CGROUP_WEIGHT_DEFAULT
;
573 static uint64_t cgroup_context_blkio_weight(CGroupContext
*c
, ManagerState state
) {
574 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
575 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
576 return c
->startup_blockio_weight
;
577 else if (c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
578 return c
->blockio_weight
;
580 return CGROUP_BLKIO_WEIGHT_DEFAULT
;
583 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight
) {
584 return CLAMP(blkio_weight
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_BLKIO_WEIGHT_DEFAULT
,
585 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
588 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight
) {
589 return CLAMP(io_weight
* CGROUP_BLKIO_WEIGHT_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
590 CGROUP_BLKIO_WEIGHT_MIN
, CGROUP_BLKIO_WEIGHT_MAX
);
593 static void cgroup_apply_io_device_weight(Unit
*u
, const char *dev_path
, uint64_t io_weight
) {
594 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
598 r
= lookup_block_device(dev_path
, &dev
);
602 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), io_weight
);
603 r
= cg_set_attribute("io", u
->cgroup_path
, "io.weight", buf
);
605 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
606 "Failed to set io.weight: %m");
609 static void cgroup_apply_blkio_device_weight(Unit
*u
, const char *dev_path
, uint64_t blkio_weight
) {
610 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
614 r
= lookup_block_device(dev_path
, &dev
);
618 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), blkio_weight
);
619 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.weight_device", buf
);
621 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
622 "Failed to set blkio.weight_device: %m");
625 static void cgroup_apply_io_device_limit(Unit
*u
, const char *dev_path
, uint64_t *limits
) {
626 char limit_bufs
[_CGROUP_IO_LIMIT_TYPE_MAX
][DECIMAL_STR_MAX(uint64_t)];
627 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
628 CGroupIOLimitType type
;
632 r
= lookup_block_device(dev_path
, &dev
);
636 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
637 if (limits
[type
] != cgroup_io_limit_defaults
[type
])
638 xsprintf(limit_bufs
[type
], "%" PRIu64
, limits
[type
]);
640 xsprintf(limit_bufs
[type
], "%s", limits
[type
] == CGROUP_LIMIT_MAX
? "max" : "0");
642 xsprintf(buf
, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev
), minor(dev
),
643 limit_bufs
[CGROUP_IO_RBPS_MAX
], limit_bufs
[CGROUP_IO_WBPS_MAX
],
644 limit_bufs
[CGROUP_IO_RIOPS_MAX
], limit_bufs
[CGROUP_IO_WIOPS_MAX
]);
645 r
= cg_set_attribute("io", u
->cgroup_path
, "io.max", buf
);
647 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
648 "Failed to set io.max: %m");
651 static void cgroup_apply_blkio_device_limit(Unit
*u
, const char *dev_path
, uint64_t rbps
, uint64_t wbps
) {
652 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
656 r
= lookup_block_device(dev_path
, &dev
);
660 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), rbps
);
661 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.read_bps_device", buf
);
663 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
664 "Failed to set blkio.throttle.read_bps_device: %m");
666 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), wbps
);
667 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.write_bps_device", buf
);
669 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
670 "Failed to set blkio.throttle.write_bps_device: %m");
673 static bool cgroup_context_has_unified_memory_config(CGroupContext
*c
) {
674 return c
->memory_low
> 0 || c
->memory_high
!= CGROUP_LIMIT_MAX
|| c
->memory_max
!= CGROUP_LIMIT_MAX
|| c
->memory_swap_max
!= CGROUP_LIMIT_MAX
;
677 static void cgroup_apply_unified_memory_limit(Unit
*u
, const char *file
, uint64_t v
) {
678 char buf
[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
681 if (v
!= CGROUP_LIMIT_MAX
)
682 xsprintf(buf
, "%" PRIu64
"\n", v
);
684 r
= cg_set_attribute("memory", u
->cgroup_path
, file
, buf
);
686 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
687 "Failed to set %s: %m", file
);
690 static void cgroup_apply_firewall(Unit
*u
) {
693 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
695 if (bpf_firewall_compile(u
) < 0)
698 (void) bpf_firewall_install(u
);
701 static void cgroup_context_apply(
703 CGroupMask apply_mask
,
705 ManagerState state
) {
714 /* Nothing to do? Exit early! */
715 if (apply_mask
== 0 && !apply_bpf
)
718 /* Some cgroup attributes are not supported on the root cgroup, hence silently ignore */
719 is_root
= unit_has_root_cgroup(u
);
721 assert_se(c
= unit_get_cgroup_context(u
));
722 assert_se(path
= u
->cgroup_path
);
724 if (is_root
) /* Make sure we don't try to display messages with an empty path. */
727 /* We generally ignore errors caused by read-only mounted
728 * cgroup trees (assuming we are running in a container then),
729 * and missing cgroups, i.e. EROFS and ENOENT. */
731 if ((apply_mask
& CGROUP_MASK_CPU
) && !is_root
) {
732 bool has_weight
, has_shares
;
734 has_weight
= cgroup_context_has_cpu_weight(c
);
735 has_shares
= cgroup_context_has_cpu_shares(c
);
737 if (cg_all_unified() > 0) {
741 weight
= cgroup_context_cpu_weight(c
, state
);
742 else if (has_shares
) {
743 uint64_t shares
= cgroup_context_cpu_shares(c
, state
);
745 weight
= cgroup_cpu_shares_to_weight(shares
);
747 log_cgroup_compat(u
, "Applying [Startup]CpuShares %" PRIu64
" as [Startup]CpuWeight %" PRIu64
" on %s",
748 shares
, weight
, path
);
750 weight
= CGROUP_WEIGHT_DEFAULT
;
752 cgroup_apply_unified_cpu_config(u
, weight
, c
->cpu_quota_per_sec_usec
);
757 uint64_t weight
= cgroup_context_cpu_weight(c
, state
);
759 shares
= cgroup_cpu_weight_to_shares(weight
);
761 log_cgroup_compat(u
, "Applying [Startup]CpuWeight %" PRIu64
" as [Startup]CpuShares %" PRIu64
" on %s",
762 weight
, shares
, path
);
763 } else if (has_shares
)
764 shares
= cgroup_context_cpu_shares(c
, state
);
766 shares
= CGROUP_CPU_SHARES_DEFAULT
;
768 cgroup_apply_legacy_cpu_config(u
, shares
, c
->cpu_quota_per_sec_usec
);
772 if (apply_mask
& CGROUP_MASK_IO
) {
773 bool has_io
= cgroup_context_has_io_config(c
);
774 bool has_blockio
= cgroup_context_has_blockio_config(c
);
777 char buf
[8+DECIMAL_STR_MAX(uint64_t)+1];
781 weight
= cgroup_context_io_weight(c
, state
);
782 else if (has_blockio
) {
783 uint64_t blkio_weight
= cgroup_context_blkio_weight(c
, state
);
785 weight
= cgroup_weight_blkio_to_io(blkio_weight
);
787 log_cgroup_compat(u
, "Applying [Startup]BlockIOWeight %" PRIu64
" as [Startup]IOWeight %" PRIu64
,
788 blkio_weight
, weight
);
790 weight
= CGROUP_WEIGHT_DEFAULT
;
792 xsprintf(buf
, "default %" PRIu64
"\n", weight
);
793 r
= cg_set_attribute("io", path
, "io.weight", buf
);
795 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
796 "Failed to set io.weight: %m");
799 CGroupIODeviceWeight
*w
;
801 /* FIXME: no way to reset this list */
802 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
)
803 cgroup_apply_io_device_weight(u
, w
->path
, w
->weight
);
804 } else if (has_blockio
) {
805 CGroupBlockIODeviceWeight
*w
;
807 /* FIXME: no way to reset this list */
808 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
) {
809 weight
= cgroup_weight_blkio_to_io(w
->weight
);
811 log_cgroup_compat(u
, "Applying BlockIODeviceWeight %" PRIu64
" as IODeviceWeight %" PRIu64
" for %s",
812 w
->weight
, weight
, w
->path
);
814 cgroup_apply_io_device_weight(u
, w
->path
, weight
);
819 /* Apply limits and free ones without config. */
821 CGroupIODeviceLimit
*l
;
823 LIST_FOREACH(device_limits
, l
, c
->io_device_limits
)
824 cgroup_apply_io_device_limit(u
, l
->path
, l
->limits
);
826 } else if (has_blockio
) {
827 CGroupBlockIODeviceBandwidth
*b
;
829 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
830 uint64_t limits
[_CGROUP_IO_LIMIT_TYPE_MAX
];
831 CGroupIOLimitType type
;
833 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
834 limits
[type
] = cgroup_io_limit_defaults
[type
];
836 limits
[CGROUP_IO_RBPS_MAX
] = b
->rbps
;
837 limits
[CGROUP_IO_WBPS_MAX
] = b
->wbps
;
839 log_cgroup_compat(u
, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as IO{Read|Write}BandwidthMax for %s",
840 b
->rbps
, b
->wbps
, b
->path
);
842 cgroup_apply_io_device_limit(u
, b
->path
, limits
);
847 if (apply_mask
& CGROUP_MASK_BLKIO
) {
848 bool has_io
= cgroup_context_has_io_config(c
);
849 bool has_blockio
= cgroup_context_has_blockio_config(c
);
852 char buf
[DECIMAL_STR_MAX(uint64_t)+1];
856 uint64_t io_weight
= cgroup_context_io_weight(c
, state
);
858 weight
= cgroup_weight_io_to_blkio(cgroup_context_io_weight(c
, state
));
860 log_cgroup_compat(u
, "Applying [Startup]IOWeight %" PRIu64
" as [Startup]BlockIOWeight %" PRIu64
,
862 } else if (has_blockio
)
863 weight
= cgroup_context_blkio_weight(c
, state
);
865 weight
= CGROUP_BLKIO_WEIGHT_DEFAULT
;
867 xsprintf(buf
, "%" PRIu64
"\n", weight
);
868 r
= cg_set_attribute("blkio", path
, "blkio.weight", buf
);
870 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
871 "Failed to set blkio.weight: %m");
874 CGroupIODeviceWeight
*w
;
876 /* FIXME: no way to reset this list */
877 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
) {
878 weight
= cgroup_weight_io_to_blkio(w
->weight
);
880 log_cgroup_compat(u
, "Applying IODeviceWeight %" PRIu64
" as BlockIODeviceWeight %" PRIu64
" for %s",
881 w
->weight
, weight
, w
->path
);
883 cgroup_apply_blkio_device_weight(u
, w
->path
, weight
);
885 } else if (has_blockio
) {
886 CGroupBlockIODeviceWeight
*w
;
888 /* FIXME: no way to reset this list */
889 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
890 cgroup_apply_blkio_device_weight(u
, w
->path
, w
->weight
);
894 /* Apply limits and free ones without config. */
896 CGroupIODeviceLimit
*l
;
898 LIST_FOREACH(device_limits
, l
, c
->io_device_limits
) {
899 log_cgroup_compat(u
, "Applying IO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as BlockIO{Read|Write}BandwidthMax for %s",
900 l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
], l
->path
);
902 cgroup_apply_blkio_device_limit(u
, l
->path
, l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
]);
904 } else if (has_blockio
) {
905 CGroupBlockIODeviceBandwidth
*b
;
907 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
)
908 cgroup_apply_blkio_device_limit(u
, b
->path
, b
->rbps
, b
->wbps
);
912 if ((apply_mask
& CGROUP_MASK_MEMORY
) && !is_root
) {
913 if (cg_all_unified() > 0) {
914 uint64_t max
, swap_max
= CGROUP_LIMIT_MAX
;
916 if (cgroup_context_has_unified_memory_config(c
)) {
918 swap_max
= c
->memory_swap_max
;
920 max
= c
->memory_limit
;
922 if (max
!= CGROUP_LIMIT_MAX
)
923 log_cgroup_compat(u
, "Applying MemoryLimit %" PRIu64
" as MemoryMax", max
);
926 cgroup_apply_unified_memory_limit(u
, "memory.low", c
->memory_low
);
927 cgroup_apply_unified_memory_limit(u
, "memory.high", c
->memory_high
);
928 cgroup_apply_unified_memory_limit(u
, "memory.max", max
);
929 cgroup_apply_unified_memory_limit(u
, "memory.swap.max", swap_max
);
931 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
934 if (cgroup_context_has_unified_memory_config(c
)) {
936 log_cgroup_compat(u
, "Applying MemoryMax %" PRIi64
" as MemoryLimit", val
);
938 val
= c
->memory_limit
;
940 if (val
== CGROUP_LIMIT_MAX
)
941 strncpy(buf
, "-1\n", sizeof(buf
));
943 xsprintf(buf
, "%" PRIu64
"\n", val
);
945 r
= cg_set_attribute("memory", path
, "memory.limit_in_bytes", buf
);
947 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
948 "Failed to set memory.limit_in_bytes: %m");
952 if ((apply_mask
& CGROUP_MASK_DEVICES
) && !is_root
) {
953 CGroupDeviceAllow
*a
;
955 /* Changing the devices list of a populated cgroup
956 * might result in EINVAL, hence ignore EINVAL
959 if (c
->device_allow
|| c
->device_policy
!= CGROUP_AUTO
)
960 r
= cg_set_attribute("devices", path
, "devices.deny", "a");
962 r
= cg_set_attribute("devices", path
, "devices.allow", "a");
964 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
965 "Failed to reset devices.list: %m");
967 if (c
->device_policy
== CGROUP_CLOSED
||
968 (c
->device_policy
== CGROUP_AUTO
&& c
->device_allow
)) {
969 static const char auto_devices
[] =
970 "/dev/null\0" "rwm\0"
971 "/dev/zero\0" "rwm\0"
972 "/dev/full\0" "rwm\0"
973 "/dev/random\0" "rwm\0"
974 "/dev/urandom\0" "rwm\0"
976 "/dev/ptmx\0" "rwm\0"
977 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
978 "-/run/systemd/inaccessible/chr\0" "rwm\0"
979 "-/run/systemd/inaccessible/blk\0" "rwm\0";
983 NULSTR_FOREACH_PAIR(x
, y
, auto_devices
)
984 whitelist_device(path
, x
, y
);
986 /* PTS (/dev/pts) devices may not be duplicated, but accessed */
987 whitelist_major(path
, "pts", 'c', "rw");
990 LIST_FOREACH(device_allow
, a
, c
->device_allow
) {
1006 if (path_startswith(a
->path
, "/dev/"))
1007 whitelist_device(path
, a
->path
, acc
);
1008 else if ((val
= startswith(a
->path
, "block-")))
1009 whitelist_major(path
, val
, 'b', acc
);
1010 else if ((val
= startswith(a
->path
, "char-")))
1011 whitelist_major(path
, val
, 'c', acc
);
1013 log_unit_debug(u
, "Ignoring device %s while writing cgroup attribute.", a
->path
);
1017 if (apply_mask
& CGROUP_MASK_PIDS
) {
1020 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1021 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1022 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1023 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1024 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1025 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1026 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1027 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1028 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1029 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1030 * which is desirable so that there's an offical way to release control of the sysctl from
1031 * systemd: set the limit to unbounded and reload. */
1033 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1034 u
->manager
->sysctl_pid_max_changed
= true;
1035 r
= procfs_tasks_set_limit(c
->tasks_max
);
1036 } else if (u
->manager
->sysctl_pid_max_changed
)
1037 r
= procfs_tasks_set_limit(TASKS_MAX
);
1042 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1043 "Failed to write to tasks limit sysctls: %m");
1046 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1047 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
1049 sprintf(buf
, "%" PRIu64
"\n", c
->tasks_max
);
1050 r
= cg_set_attribute("pids", path
, "pids.max", buf
);
1052 r
= cg_set_attribute("pids", path
, "pids.max", "max");
1054 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1055 "Failed to set pids.max: %m");
1060 cgroup_apply_firewall(u
);
1063 CGroupMask
cgroup_context_get_mask(CGroupContext
*c
) {
1064 CGroupMask mask
= 0;
1066 /* Figure out which controllers we need */
1068 if (c
->cpu_accounting
||
1069 cgroup_context_has_cpu_weight(c
) ||
1070 cgroup_context_has_cpu_shares(c
) ||
1071 c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
)
1072 mask
|= CGROUP_MASK_CPUACCT
| CGROUP_MASK_CPU
;
1074 if (cgroup_context_has_io_config(c
) || cgroup_context_has_blockio_config(c
))
1075 mask
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
1077 if (c
->memory_accounting
||
1078 c
->memory_limit
!= CGROUP_LIMIT_MAX
||
1079 cgroup_context_has_unified_memory_config(c
))
1080 mask
|= CGROUP_MASK_MEMORY
;
1082 if (c
->device_allow
||
1083 c
->device_policy
!= CGROUP_AUTO
)
1084 mask
|= CGROUP_MASK_DEVICES
;
1086 if (c
->tasks_accounting
||
1087 c
->tasks_max
!= CGROUP_LIMIT_MAX
)
1088 mask
|= CGROUP_MASK_PIDS
;
1093 CGroupMask
unit_get_own_mask(Unit
*u
) {
1096 /* Returns the mask of controllers the unit needs for itself */
1098 c
= unit_get_cgroup_context(u
);
1102 return cgroup_context_get_mask(c
) | unit_get_delegate_mask(u
);
1105 CGroupMask
unit_get_delegate_mask(Unit
*u
) {
1108 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1109 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
1111 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1113 if (!unit_cgroup_delegate(u
))
1116 if (cg_all_unified() <= 0) {
1119 e
= unit_get_exec_context(u
);
1120 if (e
&& !exec_context_maintains_privileges(e
))
1124 assert_se(c
= unit_get_cgroup_context(u
));
1125 return c
->delegate_controllers
;
1128 CGroupMask
unit_get_members_mask(Unit
*u
) {
1131 /* Returns the mask of controllers all of the unit's children require, merged */
1133 if (u
->cgroup_members_mask_valid
)
1134 return u
->cgroup_members_mask
;
1136 u
->cgroup_members_mask
= 0;
1138 if (u
->type
== UNIT_SLICE
) {
1143 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
1148 if (UNIT_DEREF(member
->slice
) != u
)
1151 u
->cgroup_members_mask
|= unit_get_subtree_mask(member
); /* note that this calls ourselves again, for the children */
1155 u
->cgroup_members_mask_valid
= true;
1156 return u
->cgroup_members_mask
;
1159 CGroupMask
unit_get_siblings_mask(Unit
*u
) {
1162 /* Returns the mask of controllers all of the unit's siblings
1163 * require, i.e. the members mask of the unit's parent slice
1164 * if there is one. */
1166 if (UNIT_ISSET(u
->slice
))
1167 return unit_get_members_mask(UNIT_DEREF(u
->slice
));
1169 return unit_get_subtree_mask(u
); /* we are the top-level slice */
1172 CGroupMask
unit_get_subtree_mask(Unit
*u
) {
1174 /* Returns the mask of this subtree, meaning of the group
1175 * itself and its children. */
1177 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
1180 CGroupMask
unit_get_target_mask(Unit
*u
) {
1183 /* This returns the cgroup mask of all controllers to enable
1184 * for a specific cgroup, i.e. everything it needs itself,
1185 * plus all that its children need, plus all that its siblings
1186 * need. This is primarily useful on the legacy cgroup
1187 * hierarchy, where we need to duplicate each cgroup in each
1188 * hierarchy that shall be enabled for it. */
1190 mask
= unit_get_own_mask(u
) | unit_get_members_mask(u
) | unit_get_siblings_mask(u
);
1191 mask
&= u
->manager
->cgroup_supported
;
1196 CGroupMask
unit_get_enable_mask(Unit
*u
) {
1199 /* This returns the cgroup mask of all controllers to enable
1200 * for the children of a specific cgroup. This is primarily
1201 * useful for the unified cgroup hierarchy, where each cgroup
1202 * controls which controllers are enabled for its children. */
1204 mask
= unit_get_members_mask(u
);
1205 mask
&= u
->manager
->cgroup_supported
;
1210 bool unit_get_needs_bpf(Unit
*u
) {
1215 c
= unit_get_cgroup_context(u
);
1219 if (c
->ip_accounting
||
1220 c
->ip_address_allow
||
1224 /* If any parent slice has an IP access list defined, it applies too */
1225 for (p
= UNIT_DEREF(u
->slice
); p
; p
= UNIT_DEREF(p
->slice
)) {
1226 c
= unit_get_cgroup_context(p
);
1230 if (c
->ip_address_allow
||
1238 /* Recurse from a unit up through its containing slices, propagating
1239 * mask bits upward. A unit is also member of itself. */
1240 void unit_update_cgroup_members_masks(Unit
*u
) {
1246 /* Calculate subtree mask */
1247 m
= unit_get_subtree_mask(u
);
1249 /* See if anything changed from the previous invocation. If
1250 * not, we're done. */
1251 if (u
->cgroup_subtree_mask_valid
&& m
== u
->cgroup_subtree_mask
)
1255 u
->cgroup_subtree_mask_valid
&&
1256 ((m
& ~u
->cgroup_subtree_mask
) != 0) &&
1257 ((~m
& u
->cgroup_subtree_mask
) == 0);
1259 u
->cgroup_subtree_mask
= m
;
1260 u
->cgroup_subtree_mask_valid
= true;
1262 if (UNIT_ISSET(u
->slice
)) {
1263 Unit
*s
= UNIT_DEREF(u
->slice
);
1266 /* There's more set now than before. We
1267 * propagate the new mask to the parent's mask
1268 * (not caring if it actually was valid or
1271 s
->cgroup_members_mask
|= m
;
1274 /* There's less set now than before (or we
1275 * don't know), we need to recalculate
1276 * everything, so let's invalidate the
1277 * parent's members mask */
1279 s
->cgroup_members_mask_valid
= false;
1281 /* And now make sure that this change also hits our
1283 unit_update_cgroup_members_masks(s
);
1287 const char *unit_get_realized_cgroup_path(Unit
*u
, CGroupMask mask
) {
1289 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
1293 if (u
->cgroup_path
&&
1294 u
->cgroup_realized
&&
1295 FLAGS_SET(u
->cgroup_realized_mask
, mask
))
1296 return u
->cgroup_path
;
1298 u
= UNIT_DEREF(u
->slice
);
1304 static const char *migrate_callback(CGroupMask mask
, void *userdata
) {
1305 return unit_get_realized_cgroup_path(userdata
, mask
);
1308 char *unit_default_cgroup_path(Unit
*u
) {
1309 _cleanup_free_
char *escaped
= NULL
, *slice
= NULL
;
1314 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1315 return strdup(u
->manager
->cgroup_root
);
1317 if (UNIT_ISSET(u
->slice
) && !unit_has_name(UNIT_DEREF(u
->slice
), SPECIAL_ROOT_SLICE
)) {
1318 r
= cg_slice_to_path(UNIT_DEREF(u
->slice
)->id
, &slice
);
1323 escaped
= cg_escape(u
->id
);
1328 return strjoin(u
->manager
->cgroup_root
, "/", slice
, "/",
1331 return strjoin(u
->manager
->cgroup_root
, "/", escaped
);
1334 int unit_set_cgroup_path(Unit
*u
, const char *path
) {
1335 _cleanup_free_
char *p
= NULL
;
1347 if (streq_ptr(u
->cgroup_path
, p
))
1351 r
= hashmap_put(u
->manager
->cgroup_unit
, p
, u
);
1356 unit_release_cgroup(u
);
1358 u
->cgroup_path
= TAKE_PTR(p
);
1363 int unit_watch_cgroup(Unit
*u
) {
1364 _cleanup_free_
char *events
= NULL
;
1369 if (!u
->cgroup_path
)
1372 if (u
->cgroup_inotify_wd
>= 0)
1375 /* Only applies to the unified hierarchy */
1376 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
1378 return log_error_errno(r
, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1382 /* Don't watch the root slice, it's pointless. */
1383 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1386 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_inotify_wd_unit
, &trivial_hash_ops
);
1390 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events", &events
);
1394 u
->cgroup_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
1395 if (u
->cgroup_inotify_wd
< 0) {
1397 if (errno
== ENOENT
) /* If the directory is already
1398 * gone we don't need to track
1399 * it, so this is not an error */
1402 return log_unit_error_errno(u
, errno
, "Failed to add inotify watch descriptor for control group %s: %m", u
->cgroup_path
);
1405 r
= hashmap_put(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
), u
);
1407 return log_unit_error_errno(u
, r
, "Failed to add inotify watch descriptor to hash map: %m");
1412 int unit_pick_cgroup_path(Unit
*u
) {
1413 _cleanup_free_
char *path
= NULL
;
1421 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1424 path
= unit_default_cgroup_path(u
);
1428 r
= unit_set_cgroup_path(u
, path
);
1430 return log_unit_error_errno(u
, r
, "Control group %s exists already.", path
);
1432 return log_unit_error_errno(u
, r
, "Failed to set unit's control group path to %s: %m", path
);
1437 static int unit_create_cgroup(
1439 CGroupMask target_mask
,
1440 CGroupMask enable_mask
,
1449 c
= unit_get_cgroup_context(u
);
1453 /* Figure out our cgroup path */
1454 r
= unit_pick_cgroup_path(u
);
1458 /* First, create our own group */
1459 r
= cg_create_everywhere(u
->manager
->cgroup_supported
, target_mask
, u
->cgroup_path
);
1461 return log_unit_error_errno(u
, r
, "Failed to create cgroup %s: %m", u
->cgroup_path
);
1464 /* Start watching it */
1465 (void) unit_watch_cgroup(u
);
1467 /* Preserve enabled controllers in delegated units, adjust others. */
1468 if (created
|| !unit_cgroup_delegate(u
)) {
1470 /* Enable all controllers we need */
1471 r
= cg_enable_everywhere(u
->manager
->cgroup_supported
, enable_mask
, u
->cgroup_path
);
1473 log_unit_warning_errno(u
, r
, "Failed to enable controllers on cgroup %s, ignoring: %m",
1477 /* Keep track that this is now realized */
1478 u
->cgroup_realized
= true;
1479 u
->cgroup_realized_mask
= target_mask
;
1480 u
->cgroup_enabled_mask
= enable_mask
;
1481 u
->cgroup_bpf_state
= needs_bpf
? UNIT_CGROUP_BPF_ON
: UNIT_CGROUP_BPF_OFF
;
1483 if (u
->type
!= UNIT_SLICE
&& !unit_cgroup_delegate(u
)) {
1485 /* Then, possibly move things over, but not if
1486 * subgroups may contain processes, which is the case
1487 * for slice and delegation units. */
1488 r
= cg_migrate_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->cgroup_path
, migrate_callback
, u
);
1490 log_unit_warning_errno(u
, r
, "Failed to migrate cgroup from to %s, ignoring: %m", u
->cgroup_path
);
1496 static int unit_attach_pid_to_cgroup_via_bus(Unit
*u
, pid_t pid
, const char *suffix_path
) {
1497 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1503 if (MANAGER_IS_SYSTEM(u
->manager
))
1506 if (!u
->manager
->system_bus
)
1509 if (!u
->cgroup_path
)
1512 /* Determine this unit's cgroup path relative to our cgroup root */
1513 pp
= path_startswith(u
->cgroup_path
, u
->manager
->cgroup_root
);
1517 pp
= strjoina("/", pp
, suffix_path
);
1518 path_simplify(pp
, false);
1520 r
= sd_bus_call_method(u
->manager
->system_bus
,
1521 "org.freedesktop.systemd1",
1522 "/org/freedesktop/systemd1",
1523 "org.freedesktop.systemd1.Manager",
1524 "AttachProcessesToUnit",
1527 NULL
/* empty unit name means client's unit, i.e. us */, pp
, 1, (uint32_t) pid
);
1529 return log_unit_debug_errno(u
, r
, "Failed to attach unit process " PID_FMT
" via the bus: %s", pid
, bus_error_message(&error
, r
));
1534 int unit_attach_pids_to_cgroup(Unit
*u
, Set
*pids
, const char *suffix_path
) {
1535 CGroupMask delegated_mask
;
1543 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1546 if (set_isempty(pids
))
1549 r
= unit_realize_cgroup(u
);
1553 if (isempty(suffix_path
))
1556 p
= strjoina(u
->cgroup_path
, "/", suffix_path
);
1558 delegated_mask
= unit_get_delegate_mask(u
);
1561 SET_FOREACH(pidp
, pids
, i
) {
1562 pid_t pid
= PTR_TO_PID(pidp
);
1565 /* First, attach the PID to the main cgroup hierarchy */
1566 q
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, p
, pid
);
1568 log_unit_debug_errno(u
, q
, "Couldn't move process " PID_FMT
" to requested cgroup '%s': %m", pid
, p
);
1570 if (MANAGER_IS_USER(u
->manager
) && IN_SET(q
, -EPERM
, -EACCES
)) {
1573 /* If we are in a user instance, and we can't move the process ourselves due to
1574 * permission problems, let's ask the system instance about it instead. Since it's more
1575 * privileged it might be able to move the process across the leaves of a subtree who's
1576 * top node is not owned by us. */
1578 z
= unit_attach_pid_to_cgroup_via_bus(u
, pid
, suffix_path
);
1580 log_unit_debug_errno(u
, z
, "Couldn't move process " PID_FMT
" to requested cgroup '%s' via the system bus either: %m", pid
, p
);
1582 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1586 r
= q
; /* Remember first error */
1591 q
= cg_all_unified();
1597 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
1598 * innermost realized one */
1600 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1601 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1602 const char *realized
;
1604 if (!(u
->manager
->cgroup_supported
& bit
))
1607 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
1608 if (delegated_mask
& u
->cgroup_realized_mask
& bit
) {
1609 q
= cg_attach(cgroup_controller_to_string(c
), p
, pid
);
1611 continue; /* Success! */
1613 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",
1614 pid
, p
, cgroup_controller_to_string(c
));
1617 /* So this controller is either not delegate or realized, or something else weird happened. In
1618 * that case let's attach the PID at least to the closest cgroup up the tree that is
1620 realized
= unit_get_realized_cgroup_path(u
, bit
);
1622 continue; /* Not even realized in the root slice? Then let's not bother */
1624 q
= cg_attach(cgroup_controller_to_string(c
), realized
, pid
);
1626 log_unit_debug_errno(u
, q
, "Failed to attach PID " PID_FMT
" to realized cgroup %s in controller %s, ignoring: %m",
1627 pid
, realized
, cgroup_controller_to_string(c
));
1634 static void cgroup_xattr_apply(Unit
*u
) {
1635 char ids
[SD_ID128_STRING_MAX
];
1640 if (!MANAGER_IS_SYSTEM(u
->manager
))
1643 if (sd_id128_is_null(u
->invocation_id
))
1646 r
= cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
1647 "trusted.invocation_id",
1648 sd_id128_to_string(u
->invocation_id
, ids
), 32,
1651 log_unit_debug_errno(u
, r
, "Failed to set invocation ID on control group %s, ignoring: %m", u
->cgroup_path
);
1654 static bool unit_has_mask_realized(
1656 CGroupMask target_mask
,
1657 CGroupMask enable_mask
,
1662 return u
->cgroup_realized
&&
1663 u
->cgroup_realized_mask
== target_mask
&&
1664 u
->cgroup_enabled_mask
== enable_mask
&&
1665 ((needs_bpf
&& u
->cgroup_bpf_state
== UNIT_CGROUP_BPF_ON
) ||
1666 (!needs_bpf
&& u
->cgroup_bpf_state
== UNIT_CGROUP_BPF_OFF
));
1669 static void unit_add_to_cgroup_realize_queue(Unit
*u
) {
1672 if (u
->in_cgroup_realize_queue
)
1675 LIST_PREPEND(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1676 u
->in_cgroup_realize_queue
= true;
1679 static void unit_remove_from_cgroup_realize_queue(Unit
*u
) {
1682 if (!u
->in_cgroup_realize_queue
)
1685 LIST_REMOVE(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1686 u
->in_cgroup_realize_queue
= false;
1689 /* Check if necessary controllers and attributes for a unit are in place.
1691 * If so, do nothing.
1692 * If not, create paths, move processes over, and set attributes.
1694 * Returns 0 on success and < 0 on failure. */
1695 static int unit_realize_cgroup_now(Unit
*u
, ManagerState state
) {
1696 CGroupMask target_mask
, enable_mask
;
1697 bool needs_bpf
, apply_bpf
;
1702 unit_remove_from_cgroup_realize_queue(u
);
1704 target_mask
= unit_get_target_mask(u
);
1705 enable_mask
= unit_get_enable_mask(u
);
1706 needs_bpf
= unit_get_needs_bpf(u
);
1708 if (unit_has_mask_realized(u
, target_mask
, enable_mask
, needs_bpf
))
1711 /* Make sure we apply the BPF filters either when one is configured, or if none is configured but previously
1712 * the state was anything but off. This way, if a unit with a BPF filter applied is reconfigured to lose it
1713 * this will trickle down properly to cgroupfs. */
1714 apply_bpf
= needs_bpf
|| u
->cgroup_bpf_state
!= UNIT_CGROUP_BPF_OFF
;
1716 /* First, realize parents */
1717 if (UNIT_ISSET(u
->slice
)) {
1718 r
= unit_realize_cgroup_now(UNIT_DEREF(u
->slice
), state
);
1723 /* And then do the real work */
1724 r
= unit_create_cgroup(u
, target_mask
, enable_mask
, needs_bpf
);
1728 /* Finally, apply the necessary attributes. */
1729 cgroup_context_apply(u
, target_mask
, apply_bpf
, state
);
1730 cgroup_xattr_apply(u
);
1735 unsigned manager_dispatch_cgroup_realize_queue(Manager
*m
) {
1743 state
= manager_state(m
);
1745 while ((i
= m
->cgroup_realize_queue
)) {
1746 assert(i
->in_cgroup_realize_queue
);
1748 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i
))) {
1749 /* Maybe things changed, and the unit is not actually active anymore? */
1750 unit_remove_from_cgroup_realize_queue(i
);
1754 r
= unit_realize_cgroup_now(i
, state
);
1756 log_warning_errno(r
, "Failed to realize cgroups for queued unit %s, ignoring: %m", i
->id
);
1764 static void unit_add_siblings_to_cgroup_realize_queue(Unit
*u
) {
1767 /* This adds the siblings of the specified unit and the
1768 * siblings of all parent units to the cgroup queue. (But
1769 * neither the specified unit itself nor the parents.) */
1771 while ((slice
= UNIT_DEREF(u
->slice
))) {
1776 HASHMAP_FOREACH_KEY(v
, m
, u
->dependencies
[UNIT_BEFORE
], i
) {
1780 /* Skip units that have a dependency on the slice
1781 * but aren't actually in it. */
1782 if (UNIT_DEREF(m
->slice
) != slice
)
1785 /* No point in doing cgroup application for units
1786 * without active processes. */
1787 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m
)))
1790 /* If the unit doesn't need any new controllers
1791 * and has current ones realized, it doesn't need
1793 if (unit_has_mask_realized(m
,
1794 unit_get_target_mask(m
),
1795 unit_get_enable_mask(m
),
1796 unit_get_needs_bpf(m
)))
1799 unit_add_to_cgroup_realize_queue(m
);
1806 int unit_realize_cgroup(Unit
*u
) {
1809 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1812 /* So, here's the deal: when realizing the cgroups for this
1813 * unit, we need to first create all parents, but there's more
1814 * actually: for the weight-based controllers we also need to
1815 * make sure that all our siblings (i.e. units that are in the
1816 * same slice as we are) have cgroups, too. Otherwise, things
1817 * would become very uneven as each of their processes would
1818 * get as much resources as all our group together. This call
1819 * will synchronously create the parent cgroups, but will
1820 * defer work on the siblings to the next event loop
1823 /* Add all sibling slices to the cgroup queue. */
1824 unit_add_siblings_to_cgroup_realize_queue(u
);
1826 /* And realize this one now (and apply the values) */
1827 return unit_realize_cgroup_now(u
, manager_state(u
->manager
));
1830 void unit_release_cgroup(Unit
*u
) {
1833 /* Forgets all cgroup details for this cgroup */
1835 if (u
->cgroup_path
) {
1836 (void) hashmap_remove(u
->manager
->cgroup_unit
, u
->cgroup_path
);
1837 u
->cgroup_path
= mfree(u
->cgroup_path
);
1840 if (u
->cgroup_inotify_wd
>= 0) {
1841 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_inotify_wd
) < 0)
1842 log_unit_debug_errno(u
, errno
, "Failed to remove cgroup inotify watch %i for %s, ignoring", u
->cgroup_inotify_wd
, u
->id
);
1844 (void) hashmap_remove(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
));
1845 u
->cgroup_inotify_wd
= -1;
1849 void unit_prune_cgroup(Unit
*u
) {
1855 /* Removes the cgroup, if empty and possible, and stops watching it. */
1857 if (!u
->cgroup_path
)
1860 (void) unit_get_cpu_usage(u
, NULL
); /* Cache the last CPU usage value before we destroy the cgroup */
1862 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
1864 r
= cg_trim_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, !is_root_slice
);
1866 log_unit_debug_errno(u
, r
, "Failed to destroy cgroup %s, ignoring: %m", u
->cgroup_path
);
1873 unit_release_cgroup(u
);
1875 u
->cgroup_realized
= false;
1876 u
->cgroup_realized_mask
= 0;
1877 u
->cgroup_enabled_mask
= 0;
1880 int unit_search_main_pid(Unit
*u
, pid_t
*ret
) {
1881 _cleanup_fclose_
FILE *f
= NULL
;
1882 pid_t pid
= 0, npid
, mypid
;
1888 if (!u
->cgroup_path
)
1891 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, &f
);
1895 mypid
= getpid_cached();
1896 while (cg_read_pid(f
, &npid
) > 0) {
1902 /* Ignore processes that aren't our kids */
1903 if (get_process_ppid(npid
, &ppid
) >= 0 && ppid
!= mypid
)
1907 /* Dang, there's more than one daemonized PID
1908 in this group, so we don't know what process
1909 is the main process. */
1920 static int unit_watch_pids_in_path(Unit
*u
, const char *path
) {
1921 _cleanup_closedir_
DIR *d
= NULL
;
1922 _cleanup_fclose_
FILE *f
= NULL
;
1928 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
);
1934 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
1935 r
= unit_watch_pid(u
, pid
);
1936 if (r
< 0 && ret
>= 0)
1940 if (r
< 0 && ret
>= 0)
1944 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
1951 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1952 _cleanup_free_
char *p
= NULL
;
1954 p
= strjoin(path
, "/", fn
);
1960 r
= unit_watch_pids_in_path(u
, p
);
1961 if (r
< 0 && ret
>= 0)
1965 if (r
< 0 && ret
>= 0)
1972 int unit_synthesize_cgroup_empty_event(Unit
*u
) {
1977 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
1978 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
1979 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
1981 if (!u
->cgroup_path
)
1984 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
1987 if (r
> 0) /* On unified we have reliable notifications, and don't need this */
1990 if (!set_isempty(u
->pids
))
1993 unit_add_to_cgroup_empty_queue(u
);
1997 int unit_watch_all_pids(Unit
*u
) {
2002 /* Adds all PIDs from our cgroup to the set of PIDs we
2003 * watch. This is a fallback logic for cases where we do not
2004 * get reliable cgroup empty notifications: we try to use
2005 * SIGCHLD as replacement. */
2007 if (!u
->cgroup_path
)
2010 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2013 if (r
> 0) /* On unified we can use proper notifications */
2016 return unit_watch_pids_in_path(u
, u
->cgroup_path
);
2019 static int on_cgroup_empty_event(sd_event_source
*s
, void *userdata
) {
2020 Manager
*m
= userdata
;
2027 u
= m
->cgroup_empty_queue
;
2031 assert(u
->in_cgroup_empty_queue
);
2032 u
->in_cgroup_empty_queue
= false;
2033 LIST_REMOVE(cgroup_empty_queue
, m
->cgroup_empty_queue
, u
);
2035 if (m
->cgroup_empty_queue
) {
2036 /* More stuff queued, let's make sure we remain enabled */
2037 r
= sd_event_source_set_enabled(s
, SD_EVENT_ONESHOT
);
2039 log_debug_errno(r
, "Failed to reenable cgroup empty event source, ignoring: %m");
2042 unit_add_to_gc_queue(u
);
2044 if (UNIT_VTABLE(u
)->notify_cgroup_empty
)
2045 UNIT_VTABLE(u
)->notify_cgroup_empty(u
);
2050 void unit_add_to_cgroup_empty_queue(Unit
*u
) {
2055 /* Note that there are four different ways how cgroup empty events reach us:
2057 * 1. On the unified hierarchy we get an inotify event on the cgroup
2059 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2061 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2063 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2064 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2066 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2067 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2068 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2069 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2070 * case for scope units). */
2072 if (u
->in_cgroup_empty_queue
)
2075 /* Let's verify that the cgroup is really empty */
2076 if (!u
->cgroup_path
)
2078 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
2080 log_unit_debug_errno(u
, r
, "Failed to determine whether cgroup %s is empty: %m", u
->cgroup_path
);
2086 LIST_PREPEND(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
2087 u
->in_cgroup_empty_queue
= true;
2089 /* Trigger the defer event */
2090 r
= sd_event_source_set_enabled(u
->manager
->cgroup_empty_event_source
, SD_EVENT_ONESHOT
);
2092 log_debug_errno(r
, "Failed to enable cgroup empty event source: %m");
2095 static int on_cgroup_inotify_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
2096 Manager
*m
= userdata
;
2103 union inotify_event_buffer buffer
;
2104 struct inotify_event
*e
;
2107 l
= read(fd
, &buffer
, sizeof(buffer
));
2109 if (IN_SET(errno
, EINTR
, EAGAIN
))
2112 return log_error_errno(errno
, "Failed to read control group inotify events: %m");
2115 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
2119 /* Queue overflow has no watch descriptor */
2122 if (e
->mask
& IN_IGNORED
)
2123 /* The watch was just removed */
2126 u
= hashmap_get(m
->cgroup_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
2127 if (!u
) /* Not that inotify might deliver
2128 * events for a watch even after it
2129 * was removed, because it was queued
2130 * before the removal. Let's ignore
2131 * this here safely. */
2134 unit_add_to_cgroup_empty_queue(u
);
2139 int manager_setup_cgroup(Manager
*m
) {
2140 _cleanup_free_
char *path
= NULL
;
2141 const char *scope_path
;
2148 /* 1. Determine hierarchy */
2149 m
->cgroup_root
= mfree(m
->cgroup_root
);
2150 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &m
->cgroup_root
);
2152 return log_error_errno(r
, "Cannot determine cgroup we are running in: %m");
2154 /* Chop off the init scope, if we are already located in it */
2155 e
= endswith(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2157 /* LEGACY: Also chop off the system slice if we are in
2158 * it. This is to support live upgrades from older systemd
2159 * versions where PID 1 was moved there. Also see
2160 * cg_get_root_path(). */
2161 if (!e
&& MANAGER_IS_SYSTEM(m
)) {
2162 e
= endswith(m
->cgroup_root
, "/" SPECIAL_SYSTEM_SLICE
);
2164 e
= endswith(m
->cgroup_root
, "/system"); /* even more legacy */
2169 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2170 * easily prepend it everywhere. */
2171 delete_trailing_chars(m
->cgroup_root
, "/");
2174 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, NULL
, &path
);
2176 return log_error_errno(r
, "Cannot find cgroup mount point: %m");
2178 r
= cg_unified_flush();
2180 return log_error_errno(r
, "Couldn't determine if we are running in the unified hierarchy: %m");
2182 all_unified
= cg_all_unified();
2183 if (all_unified
< 0)
2184 return log_error_errno(all_unified
, "Couldn't determine whether we are in all unified mode: %m");
2185 if (all_unified
> 0)
2186 log_debug("Unified cgroup hierarchy is located at %s.", path
);
2188 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2190 return log_error_errno(r
, "Failed to determine whether systemd's own controller is in unified mode: %m");
2192 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path
);
2194 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY
". File system hierarchy is at %s.", path
);
2197 /* 3. Allocate cgroup empty defer event source */
2198 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2199 r
= sd_event_add_defer(m
->event
, &m
->cgroup_empty_event_source
, on_cgroup_empty_event
, m
);
2201 return log_error_errno(r
, "Failed to create cgroup empty event source: %m");
2203 r
= sd_event_source_set_priority(m
->cgroup_empty_event_source
, SD_EVENT_PRIORITY_NORMAL
-5);
2205 return log_error_errno(r
, "Failed to set priority of cgroup empty event source: %m");
2207 r
= sd_event_source_set_enabled(m
->cgroup_empty_event_source
, SD_EVENT_OFF
);
2209 return log_error_errno(r
, "Failed to disable cgroup empty event source: %m");
2211 (void) sd_event_source_set_description(m
->cgroup_empty_event_source
, "cgroup-empty");
2213 /* 4. Install notifier inotify object, or agent */
2214 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0) {
2216 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2218 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2219 safe_close(m
->cgroup_inotify_fd
);
2221 m
->cgroup_inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
2222 if (m
->cgroup_inotify_fd
< 0)
2223 return log_error_errno(errno
, "Failed to create control group inotify object: %m");
2225 r
= sd_event_add_io(m
->event
, &m
->cgroup_inotify_event_source
, m
->cgroup_inotify_fd
, EPOLLIN
, on_cgroup_inotify_event
, m
);
2227 return log_error_errno(r
, "Failed to watch control group inotify object: %m");
2229 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
2230 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2231 r
= sd_event_source_set_priority(m
->cgroup_inotify_event_source
, SD_EVENT_PRIORITY_NORMAL
-4);
2233 return log_error_errno(r
, "Failed to set priority of inotify event source: %m");
2235 (void) sd_event_source_set_description(m
->cgroup_inotify_event_source
, "cgroup-inotify");
2237 } else if (MANAGER_IS_SYSTEM(m
) && m
->test_run_flags
== 0) {
2239 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2240 * since it does not generate events when control groups with children run empty. */
2242 r
= cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER
, SYSTEMD_CGROUP_AGENT_PATH
);
2244 log_warning_errno(r
, "Failed to install release agent, ignoring: %m");
2246 log_debug("Installed release agent.");
2248 log_debug("Release agent already installed.");
2251 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2252 scope_path
= strjoina(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2253 r
= cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2255 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2256 r
= cg_migrate(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2258 log_warning_errno(r
, "Couldn't move remaining userspace processes, ignoring: %m");
2260 /* 6. And pin it, so that it cannot be unmounted */
2261 safe_close(m
->pin_cgroupfs_fd
);
2262 m
->pin_cgroupfs_fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
2263 if (m
->pin_cgroupfs_fd
< 0)
2264 return log_error_errno(errno
, "Failed to open pin file: %m");
2266 } else if (r
< 0 && !m
->test_run_flags
)
2267 return log_error_errno(r
, "Failed to create %s control group: %m", scope_path
);
2269 /* 7. Always enable hierarchical support if it exists... */
2270 if (!all_unified
&& m
->test_run_flags
== 0)
2271 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
2273 /* 8. Figure out which controllers are supported, and log about it */
2274 r
= cg_mask_supported(&m
->cgroup_supported
);
2276 return log_error_errno(r
, "Failed to determine supported controllers: %m");
2277 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++)
2278 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c
), yes_no(m
->cgroup_supported
& CGROUP_CONTROLLER_TO_MASK(c
)));
2283 void manager_shutdown_cgroup(Manager
*m
, bool delete) {
2286 /* We can't really delete the group, since we are in it. But
2288 if (delete && m
->cgroup_root
&& m
->test_run_flags
!= MANAGER_TEST_RUN_MINIMAL
)
2289 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, false);
2291 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2293 m
->cgroup_inotify_wd_unit
= hashmap_free(m
->cgroup_inotify_wd_unit
);
2295 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2296 m
->cgroup_inotify_fd
= safe_close(m
->cgroup_inotify_fd
);
2298 m
->pin_cgroupfs_fd
= safe_close(m
->pin_cgroupfs_fd
);
2300 m
->cgroup_root
= mfree(m
->cgroup_root
);
2303 Unit
* manager_get_unit_by_cgroup(Manager
*m
, const char *cgroup
) {
2310 u
= hashmap_get(m
->cgroup_unit
, cgroup
);
2314 p
= strdupa(cgroup
);
2318 e
= strrchr(p
, '/');
2320 return hashmap_get(m
->cgroup_unit
, SPECIAL_ROOT_SLICE
);
2324 u
= hashmap_get(m
->cgroup_unit
, p
);
2330 Unit
*manager_get_unit_by_pid_cgroup(Manager
*m
, pid_t pid
) {
2331 _cleanup_free_
char *cgroup
= NULL
;
2335 if (!pid_is_valid(pid
))
2338 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &cgroup
) < 0)
2341 return manager_get_unit_by_cgroup(m
, cgroup
);
2344 Unit
*manager_get_unit_by_pid(Manager
*m
, pid_t pid
) {
2349 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
2350 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
2351 * relevant one as children of the process will be assigned to that one, too, before all else. */
2353 if (!pid_is_valid(pid
))
2356 if (pid
== getpid_cached())
2357 return hashmap_get(m
->units
, SPECIAL_INIT_SCOPE
);
2359 u
= manager_get_unit_by_pid_cgroup(m
, pid
);
2363 u
= hashmap_get(m
->watch_pids
, PID_TO_PTR(pid
));
2367 array
= hashmap_get(m
->watch_pids
, PID_TO_PTR(-pid
));
2374 int manager_notify_cgroup_empty(Manager
*m
, const char *cgroup
) {
2380 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
2381 * or from the --system instance */
2383 log_debug("Got cgroup empty notification for: %s", cgroup
);
2385 u
= manager_get_unit_by_cgroup(m
, cgroup
);
2389 unit_add_to_cgroup_empty_queue(u
);
2393 int unit_get_memory_current(Unit
*u
, uint64_t *ret
) {
2394 _cleanup_free_
char *v
= NULL
;
2400 if (!UNIT_CGROUP_BOOL(u
, memory_accounting
))
2403 if (!u
->cgroup_path
)
2406 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2407 if (unit_has_root_cgroup(u
))
2408 return procfs_memory_get_current(ret
);
2410 if ((u
->cgroup_realized_mask
& CGROUP_MASK_MEMORY
) == 0)
2413 r
= cg_all_unified();
2417 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.current", &v
);
2419 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.usage_in_bytes", &v
);
2425 return safe_atou64(v
, ret
);
2428 int unit_get_tasks_current(Unit
*u
, uint64_t *ret
) {
2429 _cleanup_free_
char *v
= NULL
;
2435 if (!UNIT_CGROUP_BOOL(u
, tasks_accounting
))
2438 if (!u
->cgroup_path
)
2441 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2442 if (unit_has_root_cgroup(u
))
2443 return procfs_tasks_get_current(ret
);
2445 if ((u
->cgroup_realized_mask
& CGROUP_MASK_PIDS
) == 0)
2448 r
= cg_get_attribute("pids", u
->cgroup_path
, "pids.current", &v
);
2454 return safe_atou64(v
, ret
);
2457 static int unit_get_cpu_usage_raw(Unit
*u
, nsec_t
*ret
) {
2458 _cleanup_free_
char *v
= NULL
;
2465 if (!u
->cgroup_path
)
2468 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2469 if (unit_has_root_cgroup(u
))
2470 return procfs_cpu_get_usage(ret
);
2472 r
= cg_all_unified();
2476 _cleanup_free_
char *val
= NULL
;
2479 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPU
) == 0)
2482 r
= cg_get_keyed_attribute("cpu", u
->cgroup_path
, "cpu.stat", STRV_MAKE("usage_usec"), &val
);
2485 if (IN_SET(r
, -ENOENT
, -ENXIO
))
2488 r
= safe_atou64(val
, &us
);
2492 ns
= us
* NSEC_PER_USEC
;
2494 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPUACCT
) == 0)
2497 r
= cg_get_attribute("cpuacct", u
->cgroup_path
, "cpuacct.usage", &v
);
2503 r
= safe_atou64(v
, &ns
);
2512 int unit_get_cpu_usage(Unit
*u
, nsec_t
*ret
) {
2518 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2519 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2520 * call this function with a NULL return value. */
2522 if (!UNIT_CGROUP_BOOL(u
, cpu_accounting
))
2525 r
= unit_get_cpu_usage_raw(u
, &ns
);
2526 if (r
== -ENODATA
&& u
->cpu_usage_last
!= NSEC_INFINITY
) {
2527 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2531 *ret
= u
->cpu_usage_last
;
2537 if (ns
> u
->cpu_usage_base
)
2538 ns
-= u
->cpu_usage_base
;
2542 u
->cpu_usage_last
= ns
;
2549 int unit_get_ip_accounting(
2551 CGroupIPAccountingMetric metric
,
2558 assert(metric
>= 0);
2559 assert(metric
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
);
2562 if (!UNIT_CGROUP_BOOL(u
, ip_accounting
))
2565 fd
= IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_INGRESS_PACKETS
) ?
2566 u
->ip_accounting_ingress_map_fd
:
2567 u
->ip_accounting_egress_map_fd
;
2571 if (IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_EGRESS_BYTES
))
2572 r
= bpf_firewall_read_accounting(fd
, &value
, NULL
);
2574 r
= bpf_firewall_read_accounting(fd
, NULL
, &value
);
2578 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
2579 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
2580 * ip_accounting_extra[] field, and add them in here transparently. */
2582 *ret
= value
+ u
->ip_accounting_extra
[metric
];
2587 int unit_reset_cpu_accounting(Unit
*u
) {
2593 u
->cpu_usage_last
= NSEC_INFINITY
;
2595 r
= unit_get_cpu_usage_raw(u
, &ns
);
2597 u
->cpu_usage_base
= 0;
2601 u
->cpu_usage_base
= ns
;
2605 int unit_reset_ip_accounting(Unit
*u
) {
2610 if (u
->ip_accounting_ingress_map_fd
>= 0)
2611 r
= bpf_firewall_reset_accounting(u
->ip_accounting_ingress_map_fd
);
2613 if (u
->ip_accounting_egress_map_fd
>= 0)
2614 q
= bpf_firewall_reset_accounting(u
->ip_accounting_egress_map_fd
);
2616 zero(u
->ip_accounting_extra
);
2618 return r
< 0 ? r
: q
;
2621 void unit_invalidate_cgroup(Unit
*u
, CGroupMask m
) {
2624 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2630 /* always invalidate compat pairs together */
2631 if (m
& (CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
))
2632 m
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
2634 if (m
& (CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
))
2635 m
|= CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
;
2637 if ((u
->cgroup_realized_mask
& m
) == 0) /* NOP? */
2640 u
->cgroup_realized_mask
&= ~m
;
2641 unit_add_to_cgroup_realize_queue(u
);
2644 void unit_invalidate_cgroup_bpf(Unit
*u
) {
2647 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2650 if (u
->cgroup_bpf_state
== UNIT_CGROUP_BPF_INVALIDATED
) /* NOP? */
2653 u
->cgroup_bpf_state
= UNIT_CGROUP_BPF_INVALIDATED
;
2654 unit_add_to_cgroup_realize_queue(u
);
2656 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
2657 * list of our children includes our own. */
2658 if (u
->type
== UNIT_SLICE
) {
2663 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
2667 if (UNIT_DEREF(member
->slice
) != u
)
2670 unit_invalidate_cgroup_bpf(member
);
2675 bool unit_cgroup_delegate(Unit
*u
) {
2680 if (!UNIT_VTABLE(u
)->can_delegate
)
2683 c
= unit_get_cgroup_context(u
);
2690 void manager_invalidate_startup_units(Manager
*m
) {
2696 SET_FOREACH(u
, m
->startup_units
, i
)
2697 unit_invalidate_cgroup(u
, CGROUP_MASK_CPU
|CGROUP_MASK_IO
|CGROUP_MASK_BLKIO
);
2700 static const char* const cgroup_device_policy_table
[_CGROUP_DEVICE_POLICY_MAX
] = {
2701 [CGROUP_AUTO
] = "auto",
2702 [CGROUP_CLOSED
] = "closed",
2703 [CGROUP_STRICT
] = "strict",
2706 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy
, CGroupDevicePolicy
);