1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
11 #include "alloc-util.h"
12 #include "blockdev-util.h"
13 #include "bpf-firewall.h"
14 #include "bus-error.h"
15 #include "cgroup-util.h"
20 #include "parse-util.h"
21 #include "path-util.h"
22 #include "process-util.h"
23 #include "procfs-util.h"
25 #include "stdio-util.h"
26 #include "string-table.h"
27 #include "string-util.h"
30 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
32 bool manager_owns_root_cgroup(Manager
*m
) {
35 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
36 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
37 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
38 * we run in any kind of container virtualization. */
40 if (detect_container() > 0)
43 return isempty(m
->cgroup_root
) || path_equal(m
->cgroup_root
, "/");
46 bool unit_has_root_cgroup(Unit
*u
) {
49 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
50 * the manager manages the root cgroup. */
52 if (!manager_owns_root_cgroup(u
->manager
))
55 return unit_has_name(u
, SPECIAL_ROOT_SLICE
);
58 static void cgroup_compat_warn(void) {
59 static bool cgroup_compat_warned
= false;
61 if (cgroup_compat_warned
)
64 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
65 "See cgroup-compat debug messages for details.");
67 cgroup_compat_warned
= true;
70 #define log_cgroup_compat(unit, fmt, ...) do { \
71 cgroup_compat_warn(); \
72 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
75 void cgroup_context_init(CGroupContext
*c
) {
78 /* Initialize everything to the kernel defaults, assuming the
79 * structure is preinitialized to 0 */
81 c
->cpu_weight
= CGROUP_WEIGHT_INVALID
;
82 c
->startup_cpu_weight
= CGROUP_WEIGHT_INVALID
;
83 c
->cpu_quota_per_sec_usec
= USEC_INFINITY
;
85 c
->cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
86 c
->startup_cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
88 c
->memory_high
= CGROUP_LIMIT_MAX
;
89 c
->memory_max
= CGROUP_LIMIT_MAX
;
90 c
->memory_swap_max
= CGROUP_LIMIT_MAX
;
92 c
->memory_limit
= CGROUP_LIMIT_MAX
;
94 c
->io_weight
= CGROUP_WEIGHT_INVALID
;
95 c
->startup_io_weight
= CGROUP_WEIGHT_INVALID
;
97 c
->blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
98 c
->startup_blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
100 c
->tasks_max
= (uint64_t) -1;
103 void cgroup_context_free_device_allow(CGroupContext
*c
, CGroupDeviceAllow
*a
) {
107 LIST_REMOVE(device_allow
, c
->device_allow
, a
);
112 void cgroup_context_free_io_device_weight(CGroupContext
*c
, CGroupIODeviceWeight
*w
) {
116 LIST_REMOVE(device_weights
, c
->io_device_weights
, w
);
121 void cgroup_context_free_io_device_limit(CGroupContext
*c
, CGroupIODeviceLimit
*l
) {
125 LIST_REMOVE(device_limits
, c
->io_device_limits
, l
);
130 void cgroup_context_free_blockio_device_weight(CGroupContext
*c
, CGroupBlockIODeviceWeight
*w
) {
134 LIST_REMOVE(device_weights
, c
->blockio_device_weights
, w
);
139 void cgroup_context_free_blockio_device_bandwidth(CGroupContext
*c
, CGroupBlockIODeviceBandwidth
*b
) {
143 LIST_REMOVE(device_bandwidths
, c
->blockio_device_bandwidths
, b
);
148 void cgroup_context_done(CGroupContext
*c
) {
151 while (c
->io_device_weights
)
152 cgroup_context_free_io_device_weight(c
, c
->io_device_weights
);
154 while (c
->io_device_limits
)
155 cgroup_context_free_io_device_limit(c
, c
->io_device_limits
);
157 while (c
->blockio_device_weights
)
158 cgroup_context_free_blockio_device_weight(c
, c
->blockio_device_weights
);
160 while (c
->blockio_device_bandwidths
)
161 cgroup_context_free_blockio_device_bandwidth(c
, c
->blockio_device_bandwidths
);
163 while (c
->device_allow
)
164 cgroup_context_free_device_allow(c
, c
->device_allow
);
166 c
->ip_address_allow
= ip_address_access_free_all(c
->ip_address_allow
);
167 c
->ip_address_deny
= ip_address_access_free_all(c
->ip_address_deny
);
170 void cgroup_context_dump(CGroupContext
*c
, FILE* f
, const char *prefix
) {
171 CGroupIODeviceLimit
*il
;
172 CGroupIODeviceWeight
*iw
;
173 CGroupBlockIODeviceBandwidth
*b
;
174 CGroupBlockIODeviceWeight
*w
;
175 CGroupDeviceAllow
*a
;
176 IPAddressAccessItem
*iaai
;
177 char u
[FORMAT_TIMESPAN_MAX
];
182 prefix
= strempty(prefix
);
185 "%sCPUAccounting=%s\n"
186 "%sIOAccounting=%s\n"
187 "%sBlockIOAccounting=%s\n"
188 "%sMemoryAccounting=%s\n"
189 "%sTasksAccounting=%s\n"
190 "%sIPAccounting=%s\n"
191 "%sCPUWeight=%" PRIu64
"\n"
192 "%sStartupCPUWeight=%" PRIu64
"\n"
193 "%sCPUShares=%" PRIu64
"\n"
194 "%sStartupCPUShares=%" PRIu64
"\n"
195 "%sCPUQuotaPerSecSec=%s\n"
196 "%sIOWeight=%" PRIu64
"\n"
197 "%sStartupIOWeight=%" PRIu64
"\n"
198 "%sBlockIOWeight=%" PRIu64
"\n"
199 "%sStartupBlockIOWeight=%" PRIu64
"\n"
200 "%sMemoryLow=%" PRIu64
"\n"
201 "%sMemoryHigh=%" PRIu64
"\n"
202 "%sMemoryMax=%" PRIu64
"\n"
203 "%sMemorySwapMax=%" PRIu64
"\n"
204 "%sMemoryLimit=%" PRIu64
"\n"
205 "%sTasksMax=%" PRIu64
"\n"
206 "%sDevicePolicy=%s\n"
208 prefix
, yes_no(c
->cpu_accounting
),
209 prefix
, yes_no(c
->io_accounting
),
210 prefix
, yes_no(c
->blockio_accounting
),
211 prefix
, yes_no(c
->memory_accounting
),
212 prefix
, yes_no(c
->tasks_accounting
),
213 prefix
, yes_no(c
->ip_accounting
),
214 prefix
, c
->cpu_weight
,
215 prefix
, c
->startup_cpu_weight
,
216 prefix
, c
->cpu_shares
,
217 prefix
, c
->startup_cpu_shares
,
218 prefix
, format_timespan(u
, sizeof(u
), c
->cpu_quota_per_sec_usec
, 1),
219 prefix
, c
->io_weight
,
220 prefix
, c
->startup_io_weight
,
221 prefix
, c
->blockio_weight
,
222 prefix
, c
->startup_blockio_weight
,
223 prefix
, c
->memory_low
,
224 prefix
, c
->memory_high
,
225 prefix
, c
->memory_max
,
226 prefix
, c
->memory_swap_max
,
227 prefix
, c
->memory_limit
,
228 prefix
, c
->tasks_max
,
229 prefix
, cgroup_device_policy_to_string(c
->device_policy
),
230 prefix
, yes_no(c
->delegate
));
233 _cleanup_free_
char *t
= NULL
;
235 (void) cg_mask_to_string(c
->delegate_controllers
, &t
);
237 fprintf(f
, "%sDelegateControllers=%s\n",
242 LIST_FOREACH(device_allow
, a
, c
->device_allow
)
244 "%sDeviceAllow=%s %s%s%s\n",
247 a
->r
? "r" : "", a
->w
? "w" : "", a
->m
? "m" : "");
249 LIST_FOREACH(device_weights
, iw
, c
->io_device_weights
)
251 "%sIODeviceWeight=%s %" PRIu64
,
256 LIST_FOREACH(device_limits
, il
, c
->io_device_limits
) {
257 char buf
[FORMAT_BYTES_MAX
];
258 CGroupIOLimitType type
;
260 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
261 if (il
->limits
[type
] != cgroup_io_limit_defaults
[type
])
265 cgroup_io_limit_type_to_string(type
),
267 format_bytes(buf
, sizeof(buf
), il
->limits
[type
]));
270 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
272 "%sBlockIODeviceWeight=%s %" PRIu64
,
277 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
278 char buf
[FORMAT_BYTES_MAX
];
280 if (b
->rbps
!= CGROUP_LIMIT_MAX
)
282 "%sBlockIOReadBandwidth=%s %s\n",
285 format_bytes(buf
, sizeof(buf
), b
->rbps
));
286 if (b
->wbps
!= CGROUP_LIMIT_MAX
)
288 "%sBlockIOWriteBandwidth=%s %s\n",
291 format_bytes(buf
, sizeof(buf
), b
->wbps
));
294 LIST_FOREACH(items
, iaai
, c
->ip_address_allow
) {
295 _cleanup_free_
char *k
= NULL
;
297 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
298 fprintf(f
, "%sIPAddressAllow=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
301 LIST_FOREACH(items
, iaai
, c
->ip_address_deny
) {
302 _cleanup_free_
char *k
= NULL
;
304 (void) in_addr_to_string(iaai
->family
, &iaai
->address
, &k
);
305 fprintf(f
, "%sIPAddressDeny=%s/%u\n", prefix
, strnull(k
), iaai
->prefixlen
);
309 static int lookup_block_device(const char *p
, dev_t
*dev
) {
318 return log_warning_errno(errno
, "Couldn't stat device %s: %m", p
);
320 if (S_ISBLK(st
.st_mode
))
322 else if (major(st
.st_dev
) != 0) {
323 /* If this is not a device node then find the block
324 * device this file is stored on */
327 /* If this is a partition, try to get the originating
329 (void) block_get_whole_disk(*dev
, dev
);
331 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p
);
338 static int whitelist_device(const char *path
, const char *node
, const char *acc
) {
339 char buf
[2+DECIMAL_STR_MAX(dev_t
)*2+2+4];
341 bool ignore_notfound
;
347 if (node
[0] == '-') {
348 /* Non-existent paths starting with "-" must be silently ignored */
350 ignore_notfound
= true;
352 ignore_notfound
= false;
354 if (stat(node
, &st
) < 0) {
355 if (errno
== ENOENT
&& ignore_notfound
)
358 return log_warning_errno(errno
, "Couldn't stat device %s: %m", node
);
361 if (!S_ISCHR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
362 log_warning("%s is not a device.", node
);
368 S_ISCHR(st
.st_mode
) ? 'c' : 'b',
369 major(st
.st_rdev
), minor(st
.st_rdev
),
372 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
374 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
375 "Failed to set devices.allow on %s: %m", path
);
380 static int whitelist_major(const char *path
, const char *name
, char type
, const char *acc
) {
381 _cleanup_fclose_
FILE *f
= NULL
;
388 assert(IN_SET(type
, 'b', 'c'));
390 f
= fopen("/proc/devices", "re");
392 return log_warning_errno(errno
, "Cannot open /proc/devices to resolve %s (%c): %m", name
, type
);
394 FOREACH_LINE(line
, f
, goto fail
) {
395 char buf
[2+DECIMAL_STR_MAX(unsigned)+3+4], *p
, *w
;
400 if (type
== 'c' && streq(line
, "Character devices:")) {
405 if (type
== 'b' && streq(line
, "Block devices:")) {
420 w
= strpbrk(p
, WHITESPACE
);
425 r
= safe_atou(p
, &maj
);
432 w
+= strspn(w
, WHITESPACE
);
434 if (fnmatch(name
, w
, 0) != 0)
443 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
445 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
446 "Failed to set devices.allow on %s: %m", path
);
452 return log_warning_errno(errno
, "Failed to read /proc/devices: %m");
455 static bool cgroup_context_has_cpu_weight(CGroupContext
*c
) {
456 return c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
||
457 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
;
460 static bool cgroup_context_has_cpu_shares(CGroupContext
*c
) {
461 return c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
462 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
;
465 static uint64_t cgroup_context_cpu_weight(CGroupContext
*c
, ManagerState state
) {
466 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
467 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
)
468 return c
->startup_cpu_weight
;
469 else if (c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
)
470 return c
->cpu_weight
;
472 return CGROUP_WEIGHT_DEFAULT
;
475 static uint64_t cgroup_context_cpu_shares(CGroupContext
*c
, ManagerState state
) {
476 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
477 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
478 return c
->startup_cpu_shares
;
479 else if (c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
480 return c
->cpu_shares
;
482 return CGROUP_CPU_SHARES_DEFAULT
;
485 static void cgroup_apply_unified_cpu_config(Unit
*u
, uint64_t weight
, uint64_t quota
) {
486 char buf
[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t
) + 1) * 2)];
489 xsprintf(buf
, "%" PRIu64
"\n", weight
);
490 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.weight", buf
);
492 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
493 "Failed to set cpu.weight: %m");
495 if (quota
!= USEC_INFINITY
)
496 xsprintf(buf
, USEC_FMT
" " USEC_FMT
"\n",
497 quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
, CGROUP_CPU_QUOTA_PERIOD_USEC
);
499 xsprintf(buf
, "max " USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
501 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.max", buf
);
504 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
505 "Failed to set cpu.max: %m");
508 static void cgroup_apply_legacy_cpu_config(Unit
*u
, uint64_t shares
, uint64_t quota
) {
509 char buf
[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t
)) + 1];
512 xsprintf(buf
, "%" PRIu64
"\n", shares
);
513 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.shares", buf
);
515 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
516 "Failed to set cpu.shares: %m");
518 xsprintf(buf
, USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
519 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_period_us", buf
);
521 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
522 "Failed to set cpu.cfs_period_us: %m");
524 if (quota
!= USEC_INFINITY
) {
525 xsprintf(buf
, USEC_FMT
"\n", quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
);
526 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", buf
);
528 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", "-1");
530 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
531 "Failed to set cpu.cfs_quota_us: %m");
534 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares
) {
535 return CLAMP(shares
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_CPU_SHARES_DEFAULT
,
536 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
539 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight
) {
540 return CLAMP(weight
* CGROUP_CPU_SHARES_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
541 CGROUP_CPU_SHARES_MIN
, CGROUP_CPU_SHARES_MAX
);
544 static bool cgroup_context_has_io_config(CGroupContext
*c
) {
545 return c
->io_accounting
||
546 c
->io_weight
!= CGROUP_WEIGHT_INVALID
||
547 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
548 c
->io_device_weights
||
552 static bool cgroup_context_has_blockio_config(CGroupContext
*c
) {
553 return c
->blockio_accounting
||
554 c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
555 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
556 c
->blockio_device_weights
||
557 c
->blockio_device_bandwidths
;
560 static uint64_t cgroup_context_io_weight(CGroupContext
*c
, ManagerState state
) {
561 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
562 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
)
563 return c
->startup_io_weight
;
564 else if (c
->io_weight
!= CGROUP_WEIGHT_INVALID
)
567 return CGROUP_WEIGHT_DEFAULT
;
570 static uint64_t cgroup_context_blkio_weight(CGroupContext
*c
, ManagerState state
) {
571 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
572 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
573 return c
->startup_blockio_weight
;
574 else if (c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
575 return c
->blockio_weight
;
577 return CGROUP_BLKIO_WEIGHT_DEFAULT
;
580 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight
) {
581 return CLAMP(blkio_weight
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_BLKIO_WEIGHT_DEFAULT
,
582 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
585 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight
) {
586 return CLAMP(io_weight
* CGROUP_BLKIO_WEIGHT_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
587 CGROUP_BLKIO_WEIGHT_MIN
, CGROUP_BLKIO_WEIGHT_MAX
);
590 static void cgroup_apply_io_device_weight(Unit
*u
, const char *dev_path
, uint64_t io_weight
) {
591 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
595 r
= lookup_block_device(dev_path
, &dev
);
599 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), io_weight
);
600 r
= cg_set_attribute("io", u
->cgroup_path
, "io.weight", buf
);
602 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
603 "Failed to set io.weight: %m");
606 static void cgroup_apply_blkio_device_weight(Unit
*u
, const char *dev_path
, uint64_t blkio_weight
) {
607 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
611 r
= lookup_block_device(dev_path
, &dev
);
615 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), blkio_weight
);
616 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.weight_device", buf
);
618 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
619 "Failed to set blkio.weight_device: %m");
622 static unsigned cgroup_apply_io_device_limit(Unit
*u
, const char *dev_path
, uint64_t *limits
) {
623 char limit_bufs
[_CGROUP_IO_LIMIT_TYPE_MAX
][DECIMAL_STR_MAX(uint64_t)];
624 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
625 CGroupIOLimitType type
;
630 r
= lookup_block_device(dev_path
, &dev
);
634 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++) {
635 if (limits
[type
] != cgroup_io_limit_defaults
[type
]) {
636 xsprintf(limit_bufs
[type
], "%" PRIu64
, limits
[type
]);
639 xsprintf(limit_bufs
[type
], "%s", limits
[type
] == CGROUP_LIMIT_MAX
? "max" : "0");
643 xsprintf(buf
, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev
), minor(dev
),
644 limit_bufs
[CGROUP_IO_RBPS_MAX
], limit_bufs
[CGROUP_IO_WBPS_MAX
],
645 limit_bufs
[CGROUP_IO_RIOPS_MAX
], limit_bufs
[CGROUP_IO_WIOPS_MAX
]);
646 r
= cg_set_attribute("io", u
->cgroup_path
, "io.max", buf
);
648 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
649 "Failed to set io.max: %m");
653 static unsigned cgroup_apply_blkio_device_limit(Unit
*u
, const char *dev_path
, uint64_t rbps
, uint64_t wbps
) {
654 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
659 r
= lookup_block_device(dev_path
, &dev
);
663 if (rbps
!= CGROUP_LIMIT_MAX
)
665 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), rbps
);
666 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.read_bps_device", buf
);
668 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
669 "Failed to set blkio.throttle.read_bps_device: %m");
671 if (wbps
!= CGROUP_LIMIT_MAX
)
673 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), wbps
);
674 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.write_bps_device", buf
);
676 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
677 "Failed to set blkio.throttle.write_bps_device: %m");
682 static bool cgroup_context_has_unified_memory_config(CGroupContext
*c
) {
683 return c
->memory_low
> 0 || c
->memory_high
!= CGROUP_LIMIT_MAX
|| c
->memory_max
!= CGROUP_LIMIT_MAX
|| c
->memory_swap_max
!= CGROUP_LIMIT_MAX
;
686 static void cgroup_apply_unified_memory_limit(Unit
*u
, const char *file
, uint64_t v
) {
687 char buf
[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
690 if (v
!= CGROUP_LIMIT_MAX
)
691 xsprintf(buf
, "%" PRIu64
"\n", v
);
693 r
= cg_set_attribute("memory", u
->cgroup_path
, file
, buf
);
695 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
696 "Failed to set %s: %m", file
);
699 static void cgroup_apply_firewall(Unit
*u
) {
702 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
704 if (bpf_firewall_compile(u
) < 0)
707 (void) bpf_firewall_install(u
);
710 static void cgroup_context_apply(
712 CGroupMask apply_mask
,
714 ManagerState state
) {
723 /* Nothing to do? Exit early! */
724 if (apply_mask
== 0 && !apply_bpf
)
727 /* Some cgroup attributes are not supported on the root cgroup, hence silently ignore */
728 is_root
= unit_has_root_cgroup(u
);
730 assert_se(c
= unit_get_cgroup_context(u
));
731 assert_se(path
= u
->cgroup_path
);
733 if (is_root
) /* Make sure we don't try to display messages with an empty path. */
736 /* We generally ignore errors caused by read-only mounted
737 * cgroup trees (assuming we are running in a container then),
738 * and missing cgroups, i.e. EROFS and ENOENT. */
740 if ((apply_mask
& CGROUP_MASK_CPU
) && !is_root
) {
741 bool has_weight
, has_shares
;
743 has_weight
= cgroup_context_has_cpu_weight(c
);
744 has_shares
= cgroup_context_has_cpu_shares(c
);
746 if (cg_all_unified() > 0) {
750 weight
= cgroup_context_cpu_weight(c
, state
);
751 else if (has_shares
) {
752 uint64_t shares
= cgroup_context_cpu_shares(c
, state
);
754 weight
= cgroup_cpu_shares_to_weight(shares
);
756 log_cgroup_compat(u
, "Applying [Startup]CpuShares %" PRIu64
" as [Startup]CpuWeight %" PRIu64
" on %s",
757 shares
, weight
, path
);
759 weight
= CGROUP_WEIGHT_DEFAULT
;
761 cgroup_apply_unified_cpu_config(u
, weight
, c
->cpu_quota_per_sec_usec
);
766 uint64_t weight
= cgroup_context_cpu_weight(c
, state
);
768 shares
= cgroup_cpu_weight_to_shares(weight
);
770 log_cgroup_compat(u
, "Applying [Startup]CpuWeight %" PRIu64
" as [Startup]CpuShares %" PRIu64
" on %s",
771 weight
, shares
, path
);
772 } else if (has_shares
)
773 shares
= cgroup_context_cpu_shares(c
, state
);
775 shares
= CGROUP_CPU_SHARES_DEFAULT
;
777 cgroup_apply_legacy_cpu_config(u
, shares
, c
->cpu_quota_per_sec_usec
);
781 if (apply_mask
& CGROUP_MASK_IO
) {
782 bool has_io
= cgroup_context_has_io_config(c
);
783 bool has_blockio
= cgroup_context_has_blockio_config(c
);
786 char buf
[8+DECIMAL_STR_MAX(uint64_t)+1];
790 weight
= cgroup_context_io_weight(c
, state
);
791 else if (has_blockio
) {
792 uint64_t blkio_weight
= cgroup_context_blkio_weight(c
, state
);
794 weight
= cgroup_weight_blkio_to_io(blkio_weight
);
796 log_cgroup_compat(u
, "Applying [Startup]BlockIOWeight %" PRIu64
" as [Startup]IOWeight %" PRIu64
,
797 blkio_weight
, weight
);
799 weight
= CGROUP_WEIGHT_DEFAULT
;
801 xsprintf(buf
, "default %" PRIu64
"\n", weight
);
802 r
= cg_set_attribute("io", path
, "io.weight", buf
);
804 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
805 "Failed to set io.weight: %m");
808 CGroupIODeviceWeight
*w
;
810 /* FIXME: no way to reset this list */
811 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
)
812 cgroup_apply_io_device_weight(u
, w
->path
, w
->weight
);
813 } else if (has_blockio
) {
814 CGroupBlockIODeviceWeight
*w
;
816 /* FIXME: no way to reset this list */
817 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
) {
818 weight
= cgroup_weight_blkio_to_io(w
->weight
);
820 log_cgroup_compat(u
, "Applying BlockIODeviceWeight %" PRIu64
" as IODeviceWeight %" PRIu64
" for %s",
821 w
->weight
, weight
, w
->path
);
823 cgroup_apply_io_device_weight(u
, w
->path
, weight
);
828 /* Apply limits and free ones without config. */
830 CGroupIODeviceLimit
*l
, *next
;
832 LIST_FOREACH_SAFE(device_limits
, l
, next
, c
->io_device_limits
) {
833 if (!cgroup_apply_io_device_limit(u
, l
->path
, l
->limits
))
834 cgroup_context_free_io_device_limit(c
, l
);
836 } else if (has_blockio
) {
837 CGroupBlockIODeviceBandwidth
*b
, *next
;
839 LIST_FOREACH_SAFE(device_bandwidths
, b
, next
, c
->blockio_device_bandwidths
) {
840 uint64_t limits
[_CGROUP_IO_LIMIT_TYPE_MAX
];
841 CGroupIOLimitType type
;
843 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
844 limits
[type
] = cgroup_io_limit_defaults
[type
];
846 limits
[CGROUP_IO_RBPS_MAX
] = b
->rbps
;
847 limits
[CGROUP_IO_WBPS_MAX
] = b
->wbps
;
849 log_cgroup_compat(u
, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as IO{Read|Write}BandwidthMax for %s",
850 b
->rbps
, b
->wbps
, b
->path
);
852 if (!cgroup_apply_io_device_limit(u
, b
->path
, limits
))
853 cgroup_context_free_blockio_device_bandwidth(c
, b
);
858 if (apply_mask
& CGROUP_MASK_BLKIO
) {
859 bool has_io
= cgroup_context_has_io_config(c
);
860 bool has_blockio
= cgroup_context_has_blockio_config(c
);
863 char buf
[DECIMAL_STR_MAX(uint64_t)+1];
867 uint64_t io_weight
= cgroup_context_io_weight(c
, state
);
869 weight
= cgroup_weight_io_to_blkio(cgroup_context_io_weight(c
, state
));
871 log_cgroup_compat(u
, "Applying [Startup]IOWeight %" PRIu64
" as [Startup]BlockIOWeight %" PRIu64
,
873 } else if (has_blockio
)
874 weight
= cgroup_context_blkio_weight(c
, state
);
876 weight
= CGROUP_BLKIO_WEIGHT_DEFAULT
;
878 xsprintf(buf
, "%" PRIu64
"\n", weight
);
879 r
= cg_set_attribute("blkio", path
, "blkio.weight", buf
);
881 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
882 "Failed to set blkio.weight: %m");
885 CGroupIODeviceWeight
*w
;
887 /* FIXME: no way to reset this list */
888 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
) {
889 weight
= cgroup_weight_io_to_blkio(w
->weight
);
891 log_cgroup_compat(u
, "Applying IODeviceWeight %" PRIu64
" as BlockIODeviceWeight %" PRIu64
" for %s",
892 w
->weight
, weight
, w
->path
);
894 cgroup_apply_blkio_device_weight(u
, w
->path
, weight
);
896 } else if (has_blockio
) {
897 CGroupBlockIODeviceWeight
*w
;
899 /* FIXME: no way to reset this list */
900 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
901 cgroup_apply_blkio_device_weight(u
, w
->path
, w
->weight
);
905 /* Apply limits and free ones without config. */
907 CGroupIODeviceLimit
*l
, *next
;
909 LIST_FOREACH_SAFE(device_limits
, l
, next
, c
->io_device_limits
) {
910 log_cgroup_compat(u
, "Applying IO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as BlockIO{Read|Write}BandwidthMax for %s",
911 l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
], l
->path
);
913 if (!cgroup_apply_blkio_device_limit(u
, l
->path
, l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
]))
914 cgroup_context_free_io_device_limit(c
, l
);
916 } else if (has_blockio
) {
917 CGroupBlockIODeviceBandwidth
*b
, *next
;
919 LIST_FOREACH_SAFE(device_bandwidths
, b
, next
, c
->blockio_device_bandwidths
)
920 if (!cgroup_apply_blkio_device_limit(u
, b
->path
, b
->rbps
, b
->wbps
))
921 cgroup_context_free_blockio_device_bandwidth(c
, b
);
925 if ((apply_mask
& CGROUP_MASK_MEMORY
) && !is_root
) {
926 if (cg_all_unified() > 0) {
927 uint64_t max
, swap_max
= CGROUP_LIMIT_MAX
;
929 if (cgroup_context_has_unified_memory_config(c
)) {
931 swap_max
= c
->memory_swap_max
;
933 max
= c
->memory_limit
;
935 if (max
!= CGROUP_LIMIT_MAX
)
936 log_cgroup_compat(u
, "Applying MemoryLimit %" PRIu64
" as MemoryMax", max
);
939 cgroup_apply_unified_memory_limit(u
, "memory.low", c
->memory_low
);
940 cgroup_apply_unified_memory_limit(u
, "memory.high", c
->memory_high
);
941 cgroup_apply_unified_memory_limit(u
, "memory.max", max
);
942 cgroup_apply_unified_memory_limit(u
, "memory.swap.max", swap_max
);
944 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
947 if (cgroup_context_has_unified_memory_config(c
)) {
949 log_cgroup_compat(u
, "Applying MemoryMax %" PRIi64
" as MemoryLimit", val
);
951 val
= c
->memory_limit
;
953 if (val
== CGROUP_LIMIT_MAX
)
954 strncpy(buf
, "-1\n", sizeof(buf
));
956 xsprintf(buf
, "%" PRIu64
"\n", val
);
958 r
= cg_set_attribute("memory", path
, "memory.limit_in_bytes", buf
);
960 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
961 "Failed to set memory.limit_in_bytes: %m");
965 if ((apply_mask
& CGROUP_MASK_DEVICES
) && !is_root
) {
966 CGroupDeviceAllow
*a
;
968 /* Changing the devices list of a populated cgroup
969 * might result in EINVAL, hence ignore EINVAL
972 if (c
->device_allow
|| c
->device_policy
!= CGROUP_AUTO
)
973 r
= cg_set_attribute("devices", path
, "devices.deny", "a");
975 r
= cg_set_attribute("devices", path
, "devices.allow", "a");
977 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
978 "Failed to reset devices.list: %m");
980 if (c
->device_policy
== CGROUP_CLOSED
||
981 (c
->device_policy
== CGROUP_AUTO
&& c
->device_allow
)) {
982 static const char auto_devices
[] =
983 "/dev/null\0" "rwm\0"
984 "/dev/zero\0" "rwm\0"
985 "/dev/full\0" "rwm\0"
986 "/dev/random\0" "rwm\0"
987 "/dev/urandom\0" "rwm\0"
989 "/dev/ptmx\0" "rwm\0"
990 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
991 "-/run/systemd/inaccessible/chr\0" "rwm\0"
992 "-/run/systemd/inaccessible/blk\0" "rwm\0";
996 NULSTR_FOREACH_PAIR(x
, y
, auto_devices
)
997 whitelist_device(path
, x
, y
);
999 /* PTS (/dev/pts) devices may not be duplicated, but accessed */
1000 whitelist_major(path
, "pts", 'c', "rw");
1003 LIST_FOREACH(device_allow
, a
, c
->device_allow
) {
1019 if (path_startswith(a
->path
, "/dev/"))
1020 whitelist_device(path
, a
->path
, acc
);
1021 else if ((val
= startswith(a
->path
, "block-")))
1022 whitelist_major(path
, val
, 'b', acc
);
1023 else if ((val
= startswith(a
->path
, "char-")))
1024 whitelist_major(path
, val
, 'c', acc
);
1026 log_unit_debug(u
, "Ignoring device %s while writing cgroup attribute.", a
->path
);
1030 if (apply_mask
& CGROUP_MASK_PIDS
) {
1033 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1034 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1035 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1036 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1037 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1038 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1039 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1040 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1041 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1042 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1043 * which is desirable so that there's an offical way to release control of the sysctl from
1044 * systemd: set the limit to unbounded and reload. */
1046 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1047 u
->manager
->sysctl_pid_max_changed
= true;
1048 r
= procfs_tasks_set_limit(c
->tasks_max
);
1049 } else if (u
->manager
->sysctl_pid_max_changed
)
1050 r
= procfs_tasks_set_limit(TASKS_MAX
);
1055 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1056 "Failed to write to tasks limit sysctls: %m");
1059 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
1060 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
1062 sprintf(buf
, "%" PRIu64
"\n", c
->tasks_max
);
1063 r
= cg_set_attribute("pids", path
, "pids.max", buf
);
1065 r
= cg_set_attribute("pids", path
, "pids.max", "max");
1067 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1068 "Failed to set pids.max: %m");
1073 cgroup_apply_firewall(u
);
1076 CGroupMask
cgroup_context_get_mask(CGroupContext
*c
) {
1077 CGroupMask mask
= 0;
1079 /* Figure out which controllers we need */
1081 if (c
->cpu_accounting
||
1082 cgroup_context_has_cpu_weight(c
) ||
1083 cgroup_context_has_cpu_shares(c
) ||
1084 c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
)
1085 mask
|= CGROUP_MASK_CPUACCT
| CGROUP_MASK_CPU
;
1087 if (cgroup_context_has_io_config(c
) || cgroup_context_has_blockio_config(c
))
1088 mask
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
1090 if (c
->memory_accounting
||
1091 c
->memory_limit
!= CGROUP_LIMIT_MAX
||
1092 cgroup_context_has_unified_memory_config(c
))
1093 mask
|= CGROUP_MASK_MEMORY
;
1095 if (c
->device_allow
||
1096 c
->device_policy
!= CGROUP_AUTO
)
1097 mask
|= CGROUP_MASK_DEVICES
;
1099 if (c
->tasks_accounting
||
1100 c
->tasks_max
!= CGROUP_LIMIT_MAX
)
1101 mask
|= CGROUP_MASK_PIDS
;
1106 CGroupMask
unit_get_own_mask(Unit
*u
) {
1109 /* Returns the mask of controllers the unit needs for itself */
1111 c
= unit_get_cgroup_context(u
);
1115 return cgroup_context_get_mask(c
) | unit_get_delegate_mask(u
);
1118 CGroupMask
unit_get_delegate_mask(Unit
*u
) {
1121 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1122 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
1124 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1126 if (!unit_cgroup_delegate(u
))
1129 if (cg_all_unified() <= 0) {
1132 e
= unit_get_exec_context(u
);
1133 if (e
&& !exec_context_maintains_privileges(e
))
1137 assert_se(c
= unit_get_cgroup_context(u
));
1138 return c
->delegate_controllers
;
1141 CGroupMask
unit_get_members_mask(Unit
*u
) {
1144 /* Returns the mask of controllers all of the unit's children require, merged */
1146 if (u
->cgroup_members_mask_valid
)
1147 return u
->cgroup_members_mask
;
1149 u
->cgroup_members_mask
= 0;
1151 if (u
->type
== UNIT_SLICE
) {
1156 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
1161 if (UNIT_DEREF(member
->slice
) != u
)
1164 u
->cgroup_members_mask
|= unit_get_subtree_mask(member
); /* note that this calls ourselves again, for the children */
1168 u
->cgroup_members_mask_valid
= true;
1169 return u
->cgroup_members_mask
;
1172 CGroupMask
unit_get_siblings_mask(Unit
*u
) {
1175 /* Returns the mask of controllers all of the unit's siblings
1176 * require, i.e. the members mask of the unit's parent slice
1177 * if there is one. */
1179 if (UNIT_ISSET(u
->slice
))
1180 return unit_get_members_mask(UNIT_DEREF(u
->slice
));
1182 return unit_get_subtree_mask(u
); /* we are the top-level slice */
1185 CGroupMask
unit_get_subtree_mask(Unit
*u
) {
1187 /* Returns the mask of this subtree, meaning of the group
1188 * itself and its children. */
1190 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
1193 CGroupMask
unit_get_target_mask(Unit
*u
) {
1196 /* This returns the cgroup mask of all controllers to enable
1197 * for a specific cgroup, i.e. everything it needs itself,
1198 * plus all that its children need, plus all that its siblings
1199 * need. This is primarily useful on the legacy cgroup
1200 * hierarchy, where we need to duplicate each cgroup in each
1201 * hierarchy that shall be enabled for it. */
1203 mask
= unit_get_own_mask(u
) | unit_get_members_mask(u
) | unit_get_siblings_mask(u
);
1204 mask
&= u
->manager
->cgroup_supported
;
1209 CGroupMask
unit_get_enable_mask(Unit
*u
) {
1212 /* This returns the cgroup mask of all controllers to enable
1213 * for the children of a specific cgroup. This is primarily
1214 * useful for the unified cgroup hierarchy, where each cgroup
1215 * controls which controllers are enabled for its children. */
1217 mask
= unit_get_members_mask(u
);
1218 mask
&= u
->manager
->cgroup_supported
;
1223 bool unit_get_needs_bpf(Unit
*u
) {
1228 c
= unit_get_cgroup_context(u
);
1232 if (c
->ip_accounting
||
1233 c
->ip_address_allow
||
1237 /* If any parent slice has an IP access list defined, it applies too */
1238 for (p
= UNIT_DEREF(u
->slice
); p
; p
= UNIT_DEREF(p
->slice
)) {
1239 c
= unit_get_cgroup_context(p
);
1243 if (c
->ip_address_allow
||
1251 /* Recurse from a unit up through its containing slices, propagating
1252 * mask bits upward. A unit is also member of itself. */
1253 void unit_update_cgroup_members_masks(Unit
*u
) {
1259 /* Calculate subtree mask */
1260 m
= unit_get_subtree_mask(u
);
1262 /* See if anything changed from the previous invocation. If
1263 * not, we're done. */
1264 if (u
->cgroup_subtree_mask_valid
&& m
== u
->cgroup_subtree_mask
)
1268 u
->cgroup_subtree_mask_valid
&&
1269 ((m
& ~u
->cgroup_subtree_mask
) != 0) &&
1270 ((~m
& u
->cgroup_subtree_mask
) == 0);
1272 u
->cgroup_subtree_mask
= m
;
1273 u
->cgroup_subtree_mask_valid
= true;
1275 if (UNIT_ISSET(u
->slice
)) {
1276 Unit
*s
= UNIT_DEREF(u
->slice
);
1279 /* There's more set now than before. We
1280 * propagate the new mask to the parent's mask
1281 * (not caring if it actually was valid or
1284 s
->cgroup_members_mask
|= m
;
1287 /* There's less set now than before (or we
1288 * don't know), we need to recalculate
1289 * everything, so let's invalidate the
1290 * parent's members mask */
1292 s
->cgroup_members_mask_valid
= false;
1294 /* And now make sure that this change also hits our
1296 unit_update_cgroup_members_masks(s
);
1300 const char *unit_get_realized_cgroup_path(Unit
*u
, CGroupMask mask
) {
1302 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
1306 if (u
->cgroup_path
&&
1307 u
->cgroup_realized
&&
1308 (u
->cgroup_realized_mask
& mask
) == mask
)
1309 return u
->cgroup_path
;
1311 u
= UNIT_DEREF(u
->slice
);
1317 static const char *migrate_callback(CGroupMask mask
, void *userdata
) {
1318 return unit_get_realized_cgroup_path(userdata
, mask
);
1321 char *unit_default_cgroup_path(Unit
*u
) {
1322 _cleanup_free_
char *escaped
= NULL
, *slice
= NULL
;
1327 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1328 return strdup(u
->manager
->cgroup_root
);
1330 if (UNIT_ISSET(u
->slice
) && !unit_has_name(UNIT_DEREF(u
->slice
), SPECIAL_ROOT_SLICE
)) {
1331 r
= cg_slice_to_path(UNIT_DEREF(u
->slice
)->id
, &slice
);
1336 escaped
= cg_escape(u
->id
);
1341 return strjoin(u
->manager
->cgroup_root
, "/", slice
, "/",
1344 return strjoin(u
->manager
->cgroup_root
, "/", escaped
);
1347 int unit_set_cgroup_path(Unit
*u
, const char *path
) {
1348 _cleanup_free_
char *p
= NULL
;
1360 if (streq_ptr(u
->cgroup_path
, p
))
1364 r
= hashmap_put(u
->manager
->cgroup_unit
, p
, u
);
1369 unit_release_cgroup(u
);
1371 u
->cgroup_path
= TAKE_PTR(p
);
1376 int unit_watch_cgroup(Unit
*u
) {
1377 _cleanup_free_
char *events
= NULL
;
1382 if (!u
->cgroup_path
)
1385 if (u
->cgroup_inotify_wd
>= 0)
1388 /* Only applies to the unified hierarchy */
1389 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
1391 return log_error_errno(r
, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1395 /* Don't watch the root slice, it's pointless. */
1396 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1399 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_inotify_wd_unit
, &trivial_hash_ops
);
1403 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events", &events
);
1407 u
->cgroup_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
1408 if (u
->cgroup_inotify_wd
< 0) {
1410 if (errno
== ENOENT
) /* If the directory is already
1411 * gone we don't need to track
1412 * it, so this is not an error */
1415 return log_unit_error_errno(u
, errno
, "Failed to add inotify watch descriptor for control group %s: %m", u
->cgroup_path
);
1418 r
= hashmap_put(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
), u
);
1420 return log_unit_error_errno(u
, r
, "Failed to add inotify watch descriptor to hash map: %m");
1425 int unit_pick_cgroup_path(Unit
*u
) {
1426 _cleanup_free_
char *path
= NULL
;
1434 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1437 path
= unit_default_cgroup_path(u
);
1441 r
= unit_set_cgroup_path(u
, path
);
1443 return log_unit_error_errno(u
, r
, "Control group %s exists already.", path
);
1445 return log_unit_error_errno(u
, r
, "Failed to set unit's control group path to %s: %m", path
);
1450 static int unit_create_cgroup(
1452 CGroupMask target_mask
,
1453 CGroupMask enable_mask
,
1461 c
= unit_get_cgroup_context(u
);
1465 /* Figure out our cgroup path */
1466 r
= unit_pick_cgroup_path(u
);
1470 /* First, create our own group */
1471 r
= cg_create_everywhere(u
->manager
->cgroup_supported
, target_mask
, u
->cgroup_path
);
1473 return log_unit_error_errno(u
, r
, "Failed to create cgroup %s: %m", u
->cgroup_path
);
1475 /* Start watching it */
1476 (void) unit_watch_cgroup(u
);
1478 /* Enable all controllers we need */
1479 r
= cg_enable_everywhere(u
->manager
->cgroup_supported
, enable_mask
, u
->cgroup_path
);
1481 log_unit_warning_errno(u
, r
, "Failed to enable controllers on cgroup %s, ignoring: %m", u
->cgroup_path
);
1483 /* Keep track that this is now realized */
1484 u
->cgroup_realized
= true;
1485 u
->cgroup_realized_mask
= target_mask
;
1486 u
->cgroup_enabled_mask
= enable_mask
;
1487 u
->cgroup_bpf_state
= needs_bpf
? UNIT_CGROUP_BPF_ON
: UNIT_CGROUP_BPF_OFF
;
1489 if (u
->type
!= UNIT_SLICE
&& !unit_cgroup_delegate(u
)) {
1491 /* Then, possibly move things over, but not if
1492 * subgroups may contain processes, which is the case
1493 * for slice and delegation units. */
1494 r
= cg_migrate_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->cgroup_path
, migrate_callback
, u
);
1496 log_unit_warning_errno(u
, r
, "Failed to migrate cgroup from to %s, ignoring: %m", u
->cgroup_path
);
1502 static int unit_attach_pid_to_cgroup_via_bus(Unit
*u
, pid_t pid
, const char *suffix_path
) {
1503 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1509 if (MANAGER_IS_SYSTEM(u
->manager
))
1512 if (!u
->manager
->system_bus
)
1515 if (!u
->cgroup_path
)
1518 /* Determine this unit's cgroup path relative to our cgroup root */
1519 pp
= path_startswith(u
->cgroup_path
, u
->manager
->cgroup_root
);
1523 pp
= strjoina("/", pp
, suffix_path
);
1524 path_kill_slashes(pp
);
1526 r
= sd_bus_call_method(u
->manager
->system_bus
,
1527 "org.freedesktop.systemd1",
1528 "/org/freedesktop/systemd1",
1529 "org.freedesktop.systemd1.Manager",
1530 "AttachProcessesToUnit",
1533 NULL
/* empty unit name means client's unit, i.e. us */, pp
, 1, (uint32_t) pid
);
1535 return log_unit_debug_errno(u
, r
, "Failed to attach unit process " PID_FMT
" via the bus: %s", pid
, bus_error_message(&error
, r
));
1540 int unit_attach_pids_to_cgroup(Unit
*u
, Set
*pids
, const char *suffix_path
) {
1541 CGroupMask delegated_mask
;
1549 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1552 if (set_isempty(pids
))
1555 r
= unit_realize_cgroup(u
);
1559 if (isempty(suffix_path
))
1562 p
= strjoina(u
->cgroup_path
, "/", suffix_path
);
1564 delegated_mask
= unit_get_delegate_mask(u
);
1567 SET_FOREACH(pidp
, pids
, i
) {
1568 pid_t pid
= PTR_TO_PID(pidp
);
1571 /* First, attach the PID to the main cgroup hierarchy */
1572 q
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, p
, pid
);
1574 log_unit_debug_errno(u
, q
, "Couldn't move process " PID_FMT
" to requested cgroup '%s': %m", pid
, p
);
1576 if (MANAGER_IS_USER(u
->manager
) && IN_SET(q
, -EPERM
, -EACCES
)) {
1579 /* If we are in a user instance, and we can't move the process ourselves due to
1580 * permission problems, let's ask the system instance about it instead. Since it's more
1581 * privileged it might be able to move the process across the leaves of a subtree who's
1582 * top node is not owned by us. */
1584 z
= unit_attach_pid_to_cgroup_via_bus(u
, pid
, suffix_path
);
1586 log_unit_debug_errno(u
, z
, "Couldn't move process " PID_FMT
" to requested cgroup '%s' via the system bus either: %m", pid
, p
);
1588 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1592 r
= q
; /* Remember first error */
1597 q
= cg_all_unified();
1603 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
1604 * innermost realized one */
1606 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1607 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1608 const char *realized
;
1610 if (!(u
->manager
->cgroup_supported
& bit
))
1613 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
1614 if (delegated_mask
& u
->cgroup_realized_mask
& bit
) {
1615 q
= cg_attach(cgroup_controller_to_string(c
), p
, pid
);
1617 continue; /* Success! */
1619 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",
1620 pid
, p
, cgroup_controller_to_string(c
));
1623 /* So this controller is either not delegate or realized, or something else weird happened. In
1624 * that case let's attach the PID at least to the closest cgroup up the tree that is
1626 realized
= unit_get_realized_cgroup_path(u
, bit
);
1628 continue; /* Not even realized in the root slice? Then let's not bother */
1630 q
= cg_attach(cgroup_controller_to_string(c
), realized
, pid
);
1632 log_unit_debug_errno(u
, q
, "Failed to attach PID " PID_FMT
" to realized cgroup %s in controller %s, ignoring: %m",
1633 pid
, realized
, cgroup_controller_to_string(c
));
1640 static void cgroup_xattr_apply(Unit
*u
) {
1641 char ids
[SD_ID128_STRING_MAX
];
1646 if (!MANAGER_IS_SYSTEM(u
->manager
))
1649 if (sd_id128_is_null(u
->invocation_id
))
1652 r
= cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
1653 "trusted.invocation_id",
1654 sd_id128_to_string(u
->invocation_id
, ids
), 32,
1657 log_unit_debug_errno(u
, r
, "Failed to set invocation ID on control group %s, ignoring: %m", u
->cgroup_path
);
1660 static bool unit_has_mask_realized(
1662 CGroupMask target_mask
,
1663 CGroupMask enable_mask
,
1668 return u
->cgroup_realized
&&
1669 u
->cgroup_realized_mask
== target_mask
&&
1670 u
->cgroup_enabled_mask
== enable_mask
&&
1671 ((needs_bpf
&& u
->cgroup_bpf_state
== UNIT_CGROUP_BPF_ON
) ||
1672 (!needs_bpf
&& u
->cgroup_bpf_state
== UNIT_CGROUP_BPF_OFF
));
1675 static void unit_add_to_cgroup_realize_queue(Unit
*u
) {
1678 if (u
->in_cgroup_realize_queue
)
1681 LIST_PREPEND(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1682 u
->in_cgroup_realize_queue
= true;
1685 static void unit_remove_from_cgroup_realize_queue(Unit
*u
) {
1688 if (!u
->in_cgroup_realize_queue
)
1691 LIST_REMOVE(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
1692 u
->in_cgroup_realize_queue
= false;
1696 /* Check if necessary controllers and attributes for a unit are in place.
1698 * If so, do nothing.
1699 * If not, create paths, move processes over, and set attributes.
1701 * Returns 0 on success and < 0 on failure. */
1702 static int unit_realize_cgroup_now(Unit
*u
, ManagerState state
) {
1703 CGroupMask target_mask
, enable_mask
;
1704 bool needs_bpf
, apply_bpf
;
1709 unit_remove_from_cgroup_realize_queue(u
);
1711 target_mask
= unit_get_target_mask(u
);
1712 enable_mask
= unit_get_enable_mask(u
);
1713 needs_bpf
= unit_get_needs_bpf(u
);
1715 if (unit_has_mask_realized(u
, target_mask
, enable_mask
, needs_bpf
))
1718 /* Make sure we apply the BPF filters either when one is configured, or if none is configured but previously
1719 * the state was anything but off. This way, if a unit with a BPF filter applied is reconfigured to lose it
1720 * this will trickle down properly to cgroupfs. */
1721 apply_bpf
= needs_bpf
|| u
->cgroup_bpf_state
!= UNIT_CGROUP_BPF_OFF
;
1723 /* First, realize parents */
1724 if (UNIT_ISSET(u
->slice
)) {
1725 r
= unit_realize_cgroup_now(UNIT_DEREF(u
->slice
), state
);
1730 /* And then do the real work */
1731 r
= unit_create_cgroup(u
, target_mask
, enable_mask
, needs_bpf
);
1735 /* Finally, apply the necessary attributes. */
1736 cgroup_context_apply(u
, target_mask
, apply_bpf
, state
);
1737 cgroup_xattr_apply(u
);
1742 unsigned manager_dispatch_cgroup_realize_queue(Manager
*m
) {
1750 state
= manager_state(m
);
1752 while ((i
= m
->cgroup_realize_queue
)) {
1753 assert(i
->in_cgroup_realize_queue
);
1755 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i
))) {
1756 /* Maybe things changed, and the unit is not actually active anymore? */
1757 unit_remove_from_cgroup_realize_queue(i
);
1761 r
= unit_realize_cgroup_now(i
, state
);
1763 log_warning_errno(r
, "Failed to realize cgroups for queued unit %s, ignoring: %m", i
->id
);
1771 static void unit_add_siblings_to_cgroup_realize_queue(Unit
*u
) {
1774 /* This adds the siblings of the specified unit and the
1775 * siblings of all parent units to the cgroup queue. (But
1776 * neither the specified unit itself nor the parents.) */
1778 while ((slice
= UNIT_DEREF(u
->slice
))) {
1783 HASHMAP_FOREACH_KEY(v
, m
, u
->dependencies
[UNIT_BEFORE
], i
) {
1787 /* Skip units that have a dependency on the slice
1788 * but aren't actually in it. */
1789 if (UNIT_DEREF(m
->slice
) != slice
)
1792 /* No point in doing cgroup application for units
1793 * without active processes. */
1794 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m
)))
1797 /* If the unit doesn't need any new controllers
1798 * and has current ones realized, it doesn't need
1800 if (unit_has_mask_realized(m
,
1801 unit_get_target_mask(m
),
1802 unit_get_enable_mask(m
),
1803 unit_get_needs_bpf(m
)))
1806 unit_add_to_cgroup_realize_queue(m
);
1813 int unit_realize_cgroup(Unit
*u
) {
1816 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1819 /* So, here's the deal: when realizing the cgroups for this
1820 * unit, we need to first create all parents, but there's more
1821 * actually: for the weight-based controllers we also need to
1822 * make sure that all our siblings (i.e. units that are in the
1823 * same slice as we are) have cgroups, too. Otherwise, things
1824 * would become very uneven as each of their processes would
1825 * get as much resources as all our group together. This call
1826 * will synchronously create the parent cgroups, but will
1827 * defer work on the siblings to the next event loop
1830 /* Add all sibling slices to the cgroup queue. */
1831 unit_add_siblings_to_cgroup_realize_queue(u
);
1833 /* And realize this one now (and apply the values) */
1834 return unit_realize_cgroup_now(u
, manager_state(u
->manager
));
1837 void unit_release_cgroup(Unit
*u
) {
1840 /* Forgets all cgroup details for this cgroup */
1842 if (u
->cgroup_path
) {
1843 (void) hashmap_remove(u
->manager
->cgroup_unit
, u
->cgroup_path
);
1844 u
->cgroup_path
= mfree(u
->cgroup_path
);
1847 if (u
->cgroup_inotify_wd
>= 0) {
1848 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_inotify_wd
) < 0)
1849 log_unit_debug_errno(u
, errno
, "Failed to remove cgroup inotify watch %i for %s, ignoring", u
->cgroup_inotify_wd
, u
->id
);
1851 (void) hashmap_remove(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
));
1852 u
->cgroup_inotify_wd
= -1;
1856 void unit_prune_cgroup(Unit
*u
) {
1862 /* Removes the cgroup, if empty and possible, and stops watching it. */
1864 if (!u
->cgroup_path
)
1867 (void) unit_get_cpu_usage(u
, NULL
); /* Cache the last CPU usage value before we destroy the cgroup */
1869 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
1871 r
= cg_trim_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, !is_root_slice
);
1873 log_unit_debug_errno(u
, r
, "Failed to destroy cgroup %s, ignoring: %m", u
->cgroup_path
);
1880 unit_release_cgroup(u
);
1882 u
->cgroup_realized
= false;
1883 u
->cgroup_realized_mask
= 0;
1884 u
->cgroup_enabled_mask
= 0;
1887 int unit_search_main_pid(Unit
*u
, pid_t
*ret
) {
1888 _cleanup_fclose_
FILE *f
= NULL
;
1889 pid_t pid
= 0, npid
, mypid
;
1895 if (!u
->cgroup_path
)
1898 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, &f
);
1902 mypid
= getpid_cached();
1903 while (cg_read_pid(f
, &npid
) > 0) {
1909 /* Ignore processes that aren't our kids */
1910 if (get_process_ppid(npid
, &ppid
) >= 0 && ppid
!= mypid
)
1914 /* Dang, there's more than one daemonized PID
1915 in this group, so we don't know what process
1916 is the main process. */
1927 static int unit_watch_pids_in_path(Unit
*u
, const char *path
) {
1928 _cleanup_closedir_
DIR *d
= NULL
;
1929 _cleanup_fclose_
FILE *f
= NULL
;
1935 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
);
1941 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
1942 r
= unit_watch_pid(u
, pid
);
1943 if (r
< 0 && ret
>= 0)
1947 if (r
< 0 && ret
>= 0)
1951 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
1958 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1959 _cleanup_free_
char *p
= NULL
;
1961 p
= strjoin(path
, "/", fn
);
1967 r
= unit_watch_pids_in_path(u
, p
);
1968 if (r
< 0 && ret
>= 0)
1972 if (r
< 0 && ret
>= 0)
1979 int unit_synthesize_cgroup_empty_event(Unit
*u
) {
1984 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
1985 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
1986 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
1988 if (!u
->cgroup_path
)
1991 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
1994 if (r
> 0) /* On unified we have reliable notifications, and don't need this */
1997 if (!set_isempty(u
->pids
))
2000 unit_add_to_cgroup_empty_queue(u
);
2004 int unit_watch_all_pids(Unit
*u
) {
2009 /* Adds all PIDs from our cgroup to the set of PIDs we
2010 * watch. This is a fallback logic for cases where we do not
2011 * get reliable cgroup empty notifications: we try to use
2012 * SIGCHLD as replacement. */
2014 if (!u
->cgroup_path
)
2017 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2020 if (r
> 0) /* On unified we can use proper notifications */
2023 return unit_watch_pids_in_path(u
, u
->cgroup_path
);
2026 static int on_cgroup_empty_event(sd_event_source
*s
, void *userdata
) {
2027 Manager
*m
= userdata
;
2034 u
= m
->cgroup_empty_queue
;
2038 assert(u
->in_cgroup_empty_queue
);
2039 u
->in_cgroup_empty_queue
= false;
2040 LIST_REMOVE(cgroup_empty_queue
, m
->cgroup_empty_queue
, u
);
2042 if (m
->cgroup_empty_queue
) {
2043 /* More stuff queued, let's make sure we remain enabled */
2044 r
= sd_event_source_set_enabled(s
, SD_EVENT_ONESHOT
);
2046 log_debug_errno(r
, "Failed to reenable cgroup empty event source: %m");
2049 unit_add_to_gc_queue(u
);
2051 if (UNIT_VTABLE(u
)->notify_cgroup_empty
)
2052 UNIT_VTABLE(u
)->notify_cgroup_empty(u
);
2057 void unit_add_to_cgroup_empty_queue(Unit
*u
) {
2062 /* Note that there are four different ways how cgroup empty events reach us:
2064 * 1. On the unified hierarchy we get an inotify event on the cgroup
2066 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2068 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2070 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2071 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2073 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2074 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2075 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2076 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2077 * case for scope units). */
2079 if (u
->in_cgroup_empty_queue
)
2082 /* Let's verify that the cgroup is really empty */
2083 if (!u
->cgroup_path
)
2085 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
2087 log_unit_debug_errno(u
, r
, "Failed to determine whether cgroup %s is empty: %m", u
->cgroup_path
);
2093 LIST_PREPEND(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
2094 u
->in_cgroup_empty_queue
= true;
2096 /* Trigger the defer event */
2097 r
= sd_event_source_set_enabled(u
->manager
->cgroup_empty_event_source
, SD_EVENT_ONESHOT
);
2099 log_debug_errno(r
, "Failed to enable cgroup empty event source: %m");
2102 static int on_cgroup_inotify_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
2103 Manager
*m
= userdata
;
2110 union inotify_event_buffer buffer
;
2111 struct inotify_event
*e
;
2114 l
= read(fd
, &buffer
, sizeof(buffer
));
2116 if (IN_SET(errno
, EINTR
, EAGAIN
))
2119 return log_error_errno(errno
, "Failed to read control group inotify events: %m");
2122 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
2126 /* Queue overflow has no watch descriptor */
2129 if (e
->mask
& IN_IGNORED
)
2130 /* The watch was just removed */
2133 u
= hashmap_get(m
->cgroup_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
2134 if (!u
) /* Not that inotify might deliver
2135 * events for a watch even after it
2136 * was removed, because it was queued
2137 * before the removal. Let's ignore
2138 * this here safely. */
2141 unit_add_to_cgroup_empty_queue(u
);
2146 int manager_setup_cgroup(Manager
*m
) {
2147 _cleanup_free_
char *path
= NULL
;
2148 const char *scope_path
;
2155 /* 1. Determine hierarchy */
2156 m
->cgroup_root
= mfree(m
->cgroup_root
);
2157 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &m
->cgroup_root
);
2159 return log_error_errno(r
, "Cannot determine cgroup we are running in: %m");
2161 /* Chop off the init scope, if we are already located in it */
2162 e
= endswith(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2164 /* LEGACY: Also chop off the system slice if we are in
2165 * it. This is to support live upgrades from older systemd
2166 * versions where PID 1 was moved there. Also see
2167 * cg_get_root_path(). */
2168 if (!e
&& MANAGER_IS_SYSTEM(m
)) {
2169 e
= endswith(m
->cgroup_root
, "/" SPECIAL_SYSTEM_SLICE
);
2171 e
= endswith(m
->cgroup_root
, "/system"); /* even more legacy */
2176 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2177 * easily prepend it everywhere. */
2178 delete_trailing_chars(m
->cgroup_root
, "/");
2181 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, NULL
, &path
);
2183 return log_error_errno(r
, "Cannot find cgroup mount point: %m");
2185 r
= cg_unified_flush();
2187 return log_error_errno(r
, "Couldn't determine if we are running in the unified hierarchy: %m");
2189 all_unified
= cg_all_unified();
2190 if (all_unified
< 0)
2191 return log_error_errno(all_unified
, "Couldn't determine whether we are in all unified mode: %m");
2192 if (all_unified
> 0)
2193 log_debug("Unified cgroup hierarchy is located at %s.", path
);
2195 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2197 return log_error_errno(r
, "Failed to determine whether systemd's own controller is in unified mode: %m");
2199 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path
);
2201 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY
". File system hierarchy is at %s.", path
);
2204 /* 3. Allocate cgroup empty defer event source */
2205 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2206 r
= sd_event_add_defer(m
->event
, &m
->cgroup_empty_event_source
, on_cgroup_empty_event
, m
);
2208 return log_error_errno(r
, "Failed to create cgroup empty event source: %m");
2210 r
= sd_event_source_set_priority(m
->cgroup_empty_event_source
, SD_EVENT_PRIORITY_NORMAL
-5);
2212 return log_error_errno(r
, "Failed to set priority of cgroup empty event source: %m");
2214 r
= sd_event_source_set_enabled(m
->cgroup_empty_event_source
, SD_EVENT_OFF
);
2216 return log_error_errno(r
, "Failed to disable cgroup empty event source: %m");
2218 (void) sd_event_source_set_description(m
->cgroup_empty_event_source
, "cgroup-empty");
2220 /* 4. Install notifier inotify object, or agent */
2221 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0) {
2223 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2225 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2226 safe_close(m
->cgroup_inotify_fd
);
2228 m
->cgroup_inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
2229 if (m
->cgroup_inotify_fd
< 0)
2230 return log_error_errno(errno
, "Failed to create control group inotify object: %m");
2232 r
= sd_event_add_io(m
->event
, &m
->cgroup_inotify_event_source
, m
->cgroup_inotify_fd
, EPOLLIN
, on_cgroup_inotify_event
, m
);
2234 return log_error_errno(r
, "Failed to watch control group inotify object: %m");
2236 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
2237 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2238 r
= sd_event_source_set_priority(m
->cgroup_inotify_event_source
, SD_EVENT_PRIORITY_NORMAL
-4);
2240 return log_error_errno(r
, "Failed to set priority of inotify event source: %m");
2242 (void) sd_event_source_set_description(m
->cgroup_inotify_event_source
, "cgroup-inotify");
2244 } else if (MANAGER_IS_SYSTEM(m
) && m
->test_run_flags
== 0) {
2246 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2247 * since it does not generate events when control groups with children run empty. */
2249 r
= cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER
, SYSTEMD_CGROUP_AGENT_PATH
);
2251 log_warning_errno(r
, "Failed to install release agent, ignoring: %m");
2253 log_debug("Installed release agent.");
2255 log_debug("Release agent already installed.");
2258 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2259 scope_path
= strjoina(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
2260 r
= cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2262 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2263 r
= cg_migrate(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
2265 log_warning_errno(r
, "Couldn't move remaining userspace processes, ignoring: %m");
2267 /* 6. And pin it, so that it cannot be unmounted */
2268 safe_close(m
->pin_cgroupfs_fd
);
2269 m
->pin_cgroupfs_fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
2270 if (m
->pin_cgroupfs_fd
< 0)
2271 return log_error_errno(errno
, "Failed to open pin file: %m");
2273 } else if (r
< 0 && !m
->test_run_flags
)
2274 return log_error_errno(r
, "Failed to create %s control group: %m", scope_path
);
2276 /* 7. Always enable hierarchical support if it exists... */
2277 if (!all_unified
&& m
->test_run_flags
== 0)
2278 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
2280 /* 8. Figure out which controllers are supported, and log about it */
2281 r
= cg_mask_supported(&m
->cgroup_supported
);
2283 return log_error_errno(r
, "Failed to determine supported controllers: %m");
2284 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++)
2285 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c
), yes_no(m
->cgroup_supported
& CGROUP_CONTROLLER_TO_MASK(c
)));
2290 void manager_shutdown_cgroup(Manager
*m
, bool delete) {
2293 /* We can't really delete the group, since we are in it. But
2295 if (delete && m
->cgroup_root
&& m
->test_run_flags
!= MANAGER_TEST_RUN_MINIMAL
)
2296 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, false);
2298 m
->cgroup_empty_event_source
= sd_event_source_unref(m
->cgroup_empty_event_source
);
2300 m
->cgroup_inotify_wd_unit
= hashmap_free(m
->cgroup_inotify_wd_unit
);
2302 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
2303 m
->cgroup_inotify_fd
= safe_close(m
->cgroup_inotify_fd
);
2305 m
->pin_cgroupfs_fd
= safe_close(m
->pin_cgroupfs_fd
);
2307 m
->cgroup_root
= mfree(m
->cgroup_root
);
2310 Unit
* manager_get_unit_by_cgroup(Manager
*m
, const char *cgroup
) {
2317 u
= hashmap_get(m
->cgroup_unit
, cgroup
);
2321 p
= strdupa(cgroup
);
2325 e
= strrchr(p
, '/');
2327 return hashmap_get(m
->cgroup_unit
, SPECIAL_ROOT_SLICE
);
2331 u
= hashmap_get(m
->cgroup_unit
, p
);
2337 Unit
*manager_get_unit_by_pid_cgroup(Manager
*m
, pid_t pid
) {
2338 _cleanup_free_
char *cgroup
= NULL
;
2342 if (!pid_is_valid(pid
))
2345 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &cgroup
) < 0)
2348 return manager_get_unit_by_cgroup(m
, cgroup
);
2351 Unit
*manager_get_unit_by_pid(Manager
*m
, pid_t pid
) {
2356 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
2357 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
2358 * relevant one as children of the process will be assigned to that one, too, before all else. */
2360 if (!pid_is_valid(pid
))
2363 if (pid
== getpid_cached())
2364 return hashmap_get(m
->units
, SPECIAL_INIT_SCOPE
);
2366 u
= manager_get_unit_by_pid_cgroup(m
, pid
);
2370 u
= hashmap_get(m
->watch_pids
, PID_TO_PTR(pid
));
2374 array
= hashmap_get(m
->watch_pids
, PID_TO_PTR(-pid
));
2381 int manager_notify_cgroup_empty(Manager
*m
, const char *cgroup
) {
2387 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
2388 * or from the --system instance */
2390 log_debug("Got cgroup empty notification for: %s", cgroup
);
2392 u
= manager_get_unit_by_cgroup(m
, cgroup
);
2396 unit_add_to_cgroup_empty_queue(u
);
2400 int unit_get_memory_current(Unit
*u
, uint64_t *ret
) {
2401 _cleanup_free_
char *v
= NULL
;
2407 if (!UNIT_CGROUP_BOOL(u
, memory_accounting
))
2410 if (!u
->cgroup_path
)
2413 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2414 if (unit_has_root_cgroup(u
))
2415 return procfs_memory_get_current(ret
);
2417 if ((u
->cgroup_realized_mask
& CGROUP_MASK_MEMORY
) == 0)
2420 r
= cg_all_unified();
2424 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.current", &v
);
2426 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.usage_in_bytes", &v
);
2432 return safe_atou64(v
, ret
);
2435 int unit_get_tasks_current(Unit
*u
, uint64_t *ret
) {
2436 _cleanup_free_
char *v
= NULL
;
2442 if (!UNIT_CGROUP_BOOL(u
, tasks_accounting
))
2445 if (!u
->cgroup_path
)
2448 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2449 if (unit_has_root_cgroup(u
))
2450 return procfs_tasks_get_current(ret
);
2452 if ((u
->cgroup_realized_mask
& CGROUP_MASK_PIDS
) == 0)
2455 r
= cg_get_attribute("pids", u
->cgroup_path
, "pids.current", &v
);
2461 return safe_atou64(v
, ret
);
2464 static int unit_get_cpu_usage_raw(Unit
*u
, nsec_t
*ret
) {
2465 _cleanup_free_
char *v
= NULL
;
2472 if (!u
->cgroup_path
)
2475 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2476 if (unit_has_root_cgroup(u
))
2477 return procfs_cpu_get_usage(ret
);
2479 r
= cg_all_unified();
2483 _cleanup_free_
char *val
= NULL
;
2486 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPU
) == 0)
2489 r
= cg_get_keyed_attribute("cpu", u
->cgroup_path
, "cpu.stat", STRV_MAKE("usage_usec"), &val
);
2492 if (IN_SET(r
, -ENOENT
, -ENXIO
))
2495 r
= safe_atou64(val
, &us
);
2499 ns
= us
* NSEC_PER_USEC
;
2501 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPUACCT
) == 0)
2504 r
= cg_get_attribute("cpuacct", u
->cgroup_path
, "cpuacct.usage", &v
);
2510 r
= safe_atou64(v
, &ns
);
2519 int unit_get_cpu_usage(Unit
*u
, nsec_t
*ret
) {
2525 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2526 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2527 * call this function with a NULL return value. */
2529 if (!UNIT_CGROUP_BOOL(u
, cpu_accounting
))
2532 r
= unit_get_cpu_usage_raw(u
, &ns
);
2533 if (r
== -ENODATA
&& u
->cpu_usage_last
!= NSEC_INFINITY
) {
2534 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2538 *ret
= u
->cpu_usage_last
;
2544 if (ns
> u
->cpu_usage_base
)
2545 ns
-= u
->cpu_usage_base
;
2549 u
->cpu_usage_last
= ns
;
2556 int unit_get_ip_accounting(
2558 CGroupIPAccountingMetric metric
,
2565 assert(metric
>= 0);
2566 assert(metric
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
);
2569 if (!UNIT_CGROUP_BOOL(u
, ip_accounting
))
2572 fd
= IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_INGRESS_PACKETS
) ?
2573 u
->ip_accounting_ingress_map_fd
:
2574 u
->ip_accounting_egress_map_fd
;
2578 if (IN_SET(metric
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_EGRESS_BYTES
))
2579 r
= bpf_firewall_read_accounting(fd
, &value
, NULL
);
2581 r
= bpf_firewall_read_accounting(fd
, NULL
, &value
);
2585 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
2586 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
2587 * ip_accounting_extra[] field, and add them in here transparently. */
2589 *ret
= value
+ u
->ip_accounting_extra
[metric
];
2594 int unit_reset_cpu_accounting(Unit
*u
) {
2600 u
->cpu_usage_last
= NSEC_INFINITY
;
2602 r
= unit_get_cpu_usage_raw(u
, &ns
);
2604 u
->cpu_usage_base
= 0;
2608 u
->cpu_usage_base
= ns
;
2612 int unit_reset_ip_accounting(Unit
*u
) {
2617 if (u
->ip_accounting_ingress_map_fd
>= 0)
2618 r
= bpf_firewall_reset_accounting(u
->ip_accounting_ingress_map_fd
);
2620 if (u
->ip_accounting_egress_map_fd
>= 0)
2621 q
= bpf_firewall_reset_accounting(u
->ip_accounting_egress_map_fd
);
2623 zero(u
->ip_accounting_extra
);
2625 return r
< 0 ? r
: q
;
2628 void unit_invalidate_cgroup(Unit
*u
, CGroupMask m
) {
2631 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2637 /* always invalidate compat pairs together */
2638 if (m
& (CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
))
2639 m
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
2641 if (m
& (CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
))
2642 m
|= CGROUP_MASK_CPU
| CGROUP_MASK_CPUACCT
;
2644 if ((u
->cgroup_realized_mask
& m
) == 0) /* NOP? */
2647 u
->cgroup_realized_mask
&= ~m
;
2648 unit_add_to_cgroup_realize_queue(u
);
2651 void unit_invalidate_cgroup_bpf(Unit
*u
) {
2654 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2657 if (u
->cgroup_bpf_state
== UNIT_CGROUP_BPF_INVALIDATED
) /* NOP? */
2660 u
->cgroup_bpf_state
= UNIT_CGROUP_BPF_INVALIDATED
;
2661 unit_add_to_cgroup_realize_queue(u
);
2663 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
2664 * list of our children includes our own. */
2665 if (u
->type
== UNIT_SLICE
) {
2670 HASHMAP_FOREACH_KEY(v
, member
, u
->dependencies
[UNIT_BEFORE
], i
) {
2674 if (UNIT_DEREF(member
->slice
) != u
)
2677 unit_invalidate_cgroup_bpf(member
);
2682 bool unit_cgroup_delegate(Unit
*u
) {
2687 if (!UNIT_VTABLE(u
)->can_delegate
)
2690 c
= unit_get_cgroup_context(u
);
2697 void manager_invalidate_startup_units(Manager
*m
) {
2703 SET_FOREACH(u
, m
->startup_units
, i
)
2704 unit_invalidate_cgroup(u
, CGROUP_MASK_CPU
|CGROUP_MASK_IO
|CGROUP_MASK_BLKIO
);
2707 static const char* const cgroup_device_policy_table
[_CGROUP_DEVICE_POLICY_MAX
] = {
2708 [CGROUP_AUTO
] = "auto",
2709 [CGROUP_CLOSED
] = "closed",
2710 [CGROUP_STRICT
] = "strict",
2713 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy
, CGroupDevicePolicy
);