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"
23 //#include "special.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 #if 0 /// UNNEEDED by elogind
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 *ret) {
316 if (stat(p, &st) < 0)
317 return log_warning_errno(errno, "Couldn't stat device '%s': %m", p);
319 if (S_ISBLK(st.st_mode))
321 else if (major(st.st_dev) != 0)
322 *ret = st.st_dev; /* If this is not a device node then use the block device this file is stored on */
324 /* If this is btrfs, getting the backing block device is a bit harder */
325 r = btrfs_get_block_device(p, ret);
326 if (r < 0 && r != -ENOTTY)
327 return log_warning_errno(r, "Failed to determine block device backing btrfs file system '%s': %m", p);
329 log_warning("'%s' is not a block device node, and file system block device cannot be determined or is not local.", p);
334 /* If this is a LUKS device, try to get the originating block device */
335 (void) block_get_originating(*ret, ret);
337 /* If this is a partition, try to get the originating block device */
338 (void) block_get_whole_disk(*ret, ret);
342 static int whitelist_device(const char *path, const char *node, const char *acc) {
343 char buf[2+DECIMAL_STR_MAX(dev_t)*2+2+4];
345 bool ignore_notfound;
351 if (node[0] == '-') {
352 /* Non-existent paths starting with "-" must be silently ignored */
354 ignore_notfound = true;
356 ignore_notfound = false;
358 if (stat(node, &st) < 0) {
359 if (errno == ENOENT && ignore_notfound)
362 return log_warning_errno(errno, "Couldn't stat device %s: %m", node);
365 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
366 log_warning("%s is not a device.", node);
372 S_ISCHR(st.st_mode) ? 'c' : 'b',
373 major(st.st_rdev), minor(st.st_rdev),
376 r = cg_set_attribute("devices", path, "devices.allow", buf);
378 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
379 "Failed to set devices.allow on %s: %m", path);
384 static int whitelist_major(const char *path, const char *name, char type, const char *acc) {
385 _cleanup_fclose_ FILE *f = NULL;
392 assert(IN_SET(type, 'b', 'c'));
394 f = fopen("/proc/devices", "re");
396 return log_warning_errno(errno, "Cannot open /proc/devices to resolve %s (%c): %m", name, type);
398 FOREACH_LINE(line, f, goto fail) {
399 char buf[2+DECIMAL_STR_MAX(unsigned)+3+4], *p, *w;
404 if (type == 'c' && streq(line, "Character devices:")) {
409 if (type == 'b' && streq(line, "Block devices:")) {
424 w = strpbrk(p, WHITESPACE);
429 r = safe_atou(p, &maj);
436 w += strspn(w, WHITESPACE);
438 if (fnmatch(name, w, 0) != 0)
447 r = cg_set_attribute("devices", path, "devices.allow", buf);
449 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
450 "Failed to set devices.allow on %s: %m", path);
456 return log_warning_errno(errno, "Failed to read /proc/devices: %m");
459 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
460 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
461 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
464 static bool cgroup_context_has_cpu_shares(CGroupContext *c) {
465 return c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
466 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID;
469 static uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
470 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
471 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
472 return c->startup_cpu_weight;
473 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
474 return c->cpu_weight;
476 return CGROUP_WEIGHT_DEFAULT;
479 static uint64_t cgroup_context_cpu_shares(CGroupContext *c, ManagerState state) {
480 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
481 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID)
482 return c->startup_cpu_shares;
483 else if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID)
484 return c->cpu_shares;
486 return CGROUP_CPU_SHARES_DEFAULT;
489 static void cgroup_apply_unified_cpu_config(Unit *u, uint64_t weight, uint64_t quota) {
490 char buf[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t) + 1) * 2)];
493 xsprintf(buf, "%" PRIu64 "\n", weight);
494 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.weight", buf);
496 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
497 "Failed to set cpu.weight: %m");
499 if (quota != USEC_INFINITY)
500 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
501 quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC, CGROUP_CPU_QUOTA_PERIOD_USEC);
503 xsprintf(buf, "max " USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
505 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.max", buf);
508 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
509 "Failed to set cpu.max: %m");
512 static void cgroup_apply_legacy_cpu_config(Unit *u, uint64_t shares, uint64_t quota) {
513 char buf[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t)) + 1];
516 xsprintf(buf, "%" PRIu64 "\n", shares);
517 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.shares", buf);
519 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
520 "Failed to set cpu.shares: %m");
522 xsprintf(buf, USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
523 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_period_us", buf);
525 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
526 "Failed to set cpu.cfs_period_us: %m");
528 if (quota != USEC_INFINITY) {
529 xsprintf(buf, USEC_FMT "\n", quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC);
530 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", buf);
532 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", "-1");
534 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
535 "Failed to set cpu.cfs_quota_us: %m");
538 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares) {
539 return CLAMP(shares * CGROUP_WEIGHT_DEFAULT / CGROUP_CPU_SHARES_DEFAULT,
540 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
543 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight) {
544 return CLAMP(weight * CGROUP_CPU_SHARES_DEFAULT / CGROUP_WEIGHT_DEFAULT,
545 CGROUP_CPU_SHARES_MIN, CGROUP_CPU_SHARES_MAX);
548 static bool cgroup_context_has_io_config(CGroupContext *c) {
549 return c->io_accounting ||
550 c->io_weight != CGROUP_WEIGHT_INVALID ||
551 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
552 c->io_device_weights ||
556 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
557 return c->blockio_accounting ||
558 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
559 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
560 c->blockio_device_weights ||
561 c->blockio_device_bandwidths;
564 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
565 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
566 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
567 return c->startup_io_weight;
568 else if (c->io_weight != CGROUP_WEIGHT_INVALID)
571 return CGROUP_WEIGHT_DEFAULT;
574 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
575 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
576 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
577 return c->startup_blockio_weight;
578 else if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
579 return c->blockio_weight;
581 return CGROUP_BLKIO_WEIGHT_DEFAULT;
584 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
585 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
586 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
589 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
590 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
591 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
594 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
595 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
599 r = lookup_block_device(dev_path, &dev);
603 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), io_weight);
604 r = cg_set_attribute("io", u->cgroup_path, "io.weight", buf);
606 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
607 "Failed to set io.weight: %m");
610 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
611 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
615 r = lookup_block_device(dev_path, &dev);
619 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), blkio_weight);
620 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.weight_device", buf);
622 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
623 "Failed to set blkio.weight_device: %m");
626 static void cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
627 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)];
628 char buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
629 CGroupIOLimitType type;
633 r = lookup_block_device(dev_path, &dev);
637 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
638 if (limits[type] != cgroup_io_limit_defaults[type])
639 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
641 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");
652 static void cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
653 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
657 r = lookup_block_device(dev_path, &dev);
661 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), rbps);
662 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.read_bps_device", buf);
664 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
665 "Failed to set blkio.throttle.read_bps_device: %m");
667 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), wbps);
668 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.write_bps_device", buf);
670 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
671 "Failed to set blkio.throttle.write_bps_device: %m");
674 static bool cgroup_context_has_unified_memory_config(CGroupContext *c) {
675 return c->memory_low > 0 || c->memory_high != CGROUP_LIMIT_MAX || c->memory_max != CGROUP_LIMIT_MAX || c->memory_swap_max != CGROUP_LIMIT_MAX;
678 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
679 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
682 if (v != CGROUP_LIMIT_MAX)
683 xsprintf(buf, "%" PRIu64 "\n", v);
685 r = cg_set_attribute("memory", u->cgroup_path, file, buf);
687 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
688 "Failed to set %s: %m", file);
691 static void cgroup_apply_firewall(Unit *u) {
694 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
696 if (bpf_firewall_compile(u) < 0)
699 (void) bpf_firewall_install(u);
702 static void cgroup_context_apply(
704 CGroupMask apply_mask,
706 ManagerState state) {
715 /* Nothing to do? Exit early! */
716 if (apply_mask == 0 && !apply_bpf)
719 /* Some cgroup attributes are not supported on the root cgroup, hence silently ignore */
720 is_root = unit_has_root_cgroup(u);
722 assert_se(c = unit_get_cgroup_context(u));
723 assert_se(path = u->cgroup_path);
725 if (is_root) /* Make sure we don't try to display messages with an empty path. */
728 /* We generally ignore errors caused by read-only mounted
729 * cgroup trees (assuming we are running in a container then),
730 * and missing cgroups, i.e. EROFS and ENOENT. */
732 if ((apply_mask & CGROUP_MASK_CPU) && !is_root) {
733 bool has_weight, has_shares;
735 has_weight = cgroup_context_has_cpu_weight(c);
736 has_shares = cgroup_context_has_cpu_shares(c);
738 if (cg_all_unified() > 0) {
742 weight = cgroup_context_cpu_weight(c, state);
743 else if (has_shares) {
744 uint64_t shares = cgroup_context_cpu_shares(c, state);
746 weight = cgroup_cpu_shares_to_weight(shares);
748 log_cgroup_compat(u, "Applying [Startup]CpuShares %" PRIu64 " as [Startup]CpuWeight %" PRIu64 " on %s",
749 shares, weight, path);
751 weight = CGROUP_WEIGHT_DEFAULT;
753 cgroup_apply_unified_cpu_config(u, weight, c->cpu_quota_per_sec_usec);
758 uint64_t weight = cgroup_context_cpu_weight(c, state);
760 shares = cgroup_cpu_weight_to_shares(weight);
762 log_cgroup_compat(u, "Applying [Startup]CpuWeight %" PRIu64 " as [Startup]CpuShares %" PRIu64 " on %s",
763 weight, shares, path);
764 } else if (has_shares)
765 shares = cgroup_context_cpu_shares(c, state);
767 shares = CGROUP_CPU_SHARES_DEFAULT;
769 cgroup_apply_legacy_cpu_config(u, shares, c->cpu_quota_per_sec_usec);
773 if (apply_mask & CGROUP_MASK_IO) {
774 bool has_io = cgroup_context_has_io_config(c);
775 bool has_blockio = cgroup_context_has_blockio_config(c);
778 char buf[8+DECIMAL_STR_MAX(uint64_t)+1];
782 weight = cgroup_context_io_weight(c, state);
783 else if (has_blockio) {
784 uint64_t blkio_weight = cgroup_context_blkio_weight(c, state);
786 weight = cgroup_weight_blkio_to_io(blkio_weight);
788 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight %" PRIu64 " as [Startup]IOWeight %" PRIu64,
789 blkio_weight, weight);
791 weight = CGROUP_WEIGHT_DEFAULT;
793 xsprintf(buf, "default %" PRIu64 "\n", weight);
794 r = cg_set_attribute("io", path, "io.weight", buf);
796 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
797 "Failed to set io.weight: %m");
800 CGroupIODeviceWeight *w;
802 /* FIXME: no way to reset this list */
803 LIST_FOREACH(device_weights, w, c->io_device_weights)
804 cgroup_apply_io_device_weight(u, w->path, w->weight);
805 } else if (has_blockio) {
806 CGroupBlockIODeviceWeight *w;
808 /* FIXME: no way to reset this list */
809 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
810 weight = cgroup_weight_blkio_to_io(w->weight);
812 log_cgroup_compat(u, "Applying BlockIODeviceWeight %" PRIu64 " as IODeviceWeight %" PRIu64 " for %s",
813 w->weight, weight, w->path);
815 cgroup_apply_io_device_weight(u, w->path, weight);
820 /* Apply limits and free ones without config. */
822 CGroupIODeviceLimit *l;
824 LIST_FOREACH(device_limits, l, c->io_device_limits)
825 cgroup_apply_io_device_limit(u, l->path, l->limits);
827 } else if (has_blockio) {
828 CGroupBlockIODeviceBandwidth *b;
830 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
831 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
832 CGroupIOLimitType type;
834 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
835 limits[type] = cgroup_io_limit_defaults[type];
837 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
838 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
840 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax for %s",
841 b->rbps, b->wbps, b->path);
843 cgroup_apply_io_device_limit(u, b->path, limits);
848 if (apply_mask & CGROUP_MASK_BLKIO) {
849 bool has_io = cgroup_context_has_io_config(c);
850 bool has_blockio = cgroup_context_has_blockio_config(c);
853 char buf[DECIMAL_STR_MAX(uint64_t)+1];
857 uint64_t io_weight = cgroup_context_io_weight(c, state);
859 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
861 log_cgroup_compat(u, "Applying [Startup]IOWeight %" PRIu64 " as [Startup]BlockIOWeight %" PRIu64,
863 } else if (has_blockio)
864 weight = cgroup_context_blkio_weight(c, state);
866 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
868 xsprintf(buf, "%" PRIu64 "\n", weight);
869 r = cg_set_attribute("blkio", path, "blkio.weight", buf);
871 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
872 "Failed to set blkio.weight: %m");
875 CGroupIODeviceWeight *w;
877 /* FIXME: no way to reset this list */
878 LIST_FOREACH(device_weights, w, c->io_device_weights) {
879 weight = cgroup_weight_io_to_blkio(w->weight);
881 log_cgroup_compat(u, "Applying IODeviceWeight %" PRIu64 " as BlockIODeviceWeight %" PRIu64 " for %s",
882 w->weight, weight, w->path);
884 cgroup_apply_blkio_device_weight(u, w->path, weight);
886 } else if (has_blockio) {
887 CGroupBlockIODeviceWeight *w;
889 /* FIXME: no way to reset this list */
890 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
891 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
895 /* Apply limits and free ones without config. */
897 CGroupIODeviceLimit *l;
899 LIST_FOREACH(device_limits, l, c->io_device_limits) {
900 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax for %s",
901 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
903 cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]);
905 } else if (has_blockio) {
906 CGroupBlockIODeviceBandwidth *b;
908 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
909 cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps);
913 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_root) {
914 if (cg_all_unified() > 0) {
915 uint64_t max, swap_max = CGROUP_LIMIT_MAX;
917 if (cgroup_context_has_unified_memory_config(c)) {
919 swap_max = c->memory_swap_max;
921 max = c->memory_limit;
923 if (max != CGROUP_LIMIT_MAX)
924 log_cgroup_compat(u, "Applying MemoryLimit %" PRIu64 " as MemoryMax", max);
927 cgroup_apply_unified_memory_limit(u, "memory.low", c->memory_low);
928 cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
929 cgroup_apply_unified_memory_limit(u, "memory.max", max);
930 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
932 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
935 if (cgroup_context_has_unified_memory_config(c)) {
937 log_cgroup_compat(u, "Applying MemoryMax %" PRIi64 " as MemoryLimit", val);
939 val = c->memory_limit;
941 if (val == CGROUP_LIMIT_MAX)
942 strncpy(buf, "-1\n", sizeof(buf));
944 xsprintf(buf, "%" PRIu64 "\n", val);
946 r = cg_set_attribute("memory", path, "memory.limit_in_bytes", buf);
948 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
949 "Failed to set memory.limit_in_bytes: %m");
953 if ((apply_mask & CGROUP_MASK_DEVICES) && !is_root) {
954 CGroupDeviceAllow *a;
956 /* Changing the devices list of a populated cgroup
957 * might result in EINVAL, hence ignore EINVAL
960 if (c->device_allow || c->device_policy != CGROUP_AUTO)
961 r = cg_set_attribute("devices", path, "devices.deny", "a");
963 r = cg_set_attribute("devices", path, "devices.allow", "a");
965 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
966 "Failed to reset devices.list: %m");
968 if (c->device_policy == CGROUP_CLOSED ||
969 (c->device_policy == CGROUP_AUTO && c->device_allow)) {
970 static const char auto_devices[] =
971 "/dev/null\0" "rwm\0"
972 "/dev/zero\0" "rwm\0"
973 "/dev/full\0" "rwm\0"
974 "/dev/random\0" "rwm\0"
975 "/dev/urandom\0" "rwm\0"
977 "/dev/ptmx\0" "rwm\0"
978 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
979 "-/run/systemd/inaccessible/chr\0" "rwm\0"
980 "-/run/systemd/inaccessible/blk\0" "rwm\0";
984 NULSTR_FOREACH_PAIR(x, y, auto_devices)
985 whitelist_device(path, x, y);
987 /* PTS (/dev/pts) devices may not be duplicated, but accessed */
988 whitelist_major(path, "pts", 'c', "rw");
991 LIST_FOREACH(device_allow, a, c->device_allow) {
1007 if (path_startswith(a->path, "/dev/"))
1008 whitelist_device(path, a->path, acc);
1009 else if ((val = startswith(a->path, "block-")))
1010 whitelist_major(path, val, 'b', acc);
1011 else if ((val = startswith(a->path, "char-")))
1012 whitelist_major(path, val, 'c', acc);
1014 log_unit_debug(u, "Ignoring device %s while writing cgroup attribute.", a->path);
1018 if (apply_mask & CGROUP_MASK_PIDS) {
1021 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1022 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1023 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1024 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1025 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1026 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1027 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1028 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1029 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1030 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1031 * which is desirable so that there's an offical way to release control of the sysctl from
1032 * systemd: set the limit to unbounded and reload. */
1034 if (c->tasks_max != CGROUP_LIMIT_MAX) {
1035 u->manager->sysctl_pid_max_changed = true;
1036 r = procfs_tasks_set_limit(c->tasks_max);
1037 } else if (u->manager->sysctl_pid_max_changed)
1038 r = procfs_tasks_set_limit(TASKS_MAX);
1043 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1044 "Failed to write to tasks limit sysctls: %m");
1047 if (c->tasks_max != CGROUP_LIMIT_MAX) {
1048 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1050 sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
1051 r = cg_set_attribute("pids", path, "pids.max", buf);
1053 r = cg_set_attribute("pids", path, "pids.max", "max");
1055 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1056 "Failed to set pids.max: %m");
1061 cgroup_apply_firewall(u);
1064 CGroupMask cgroup_context_get_mask(CGroupContext *c) {
1065 CGroupMask mask = 0;
1067 /* Figure out which controllers we need */
1069 if (c->cpu_accounting ||
1070 cgroup_context_has_cpu_weight(c) ||
1071 cgroup_context_has_cpu_shares(c) ||
1072 c->cpu_quota_per_sec_usec != USEC_INFINITY)
1073 mask |= CGROUP_MASK_CPUACCT | CGROUP_MASK_CPU;
1075 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
1076 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
1078 if (c->memory_accounting ||
1079 c->memory_limit != CGROUP_LIMIT_MAX ||
1080 cgroup_context_has_unified_memory_config(c))
1081 mask |= CGROUP_MASK_MEMORY;
1083 if (c->device_allow ||
1084 c->device_policy != CGROUP_AUTO)
1085 mask |= CGROUP_MASK_DEVICES;
1087 if (c->tasks_accounting ||
1088 c->tasks_max != CGROUP_LIMIT_MAX)
1089 mask |= CGROUP_MASK_PIDS;
1094 CGroupMask unit_get_own_mask(Unit *u) {
1097 /* Returns the mask of controllers the unit needs for itself */
1099 c = unit_get_cgroup_context(u);
1103 return cgroup_context_get_mask(c) | unit_get_delegate_mask(u);
1106 CGroupMask unit_get_delegate_mask(Unit *u) {
1109 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1110 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
1112 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1114 if (!unit_cgroup_delegate(u))
1117 if (cg_all_unified() <= 0) {
1120 e = unit_get_exec_context(u);
1121 if (e && !exec_context_maintains_privileges(e))
1125 assert_se(c = unit_get_cgroup_context(u));
1126 return c->delegate_controllers;
1129 CGroupMask unit_get_members_mask(Unit *u) {
1132 /* Returns the mask of controllers all of the unit's children require, merged */
1134 if (u->cgroup_members_mask_valid)
1135 return u->cgroup_members_mask;
1137 u->cgroup_members_mask = 0;
1139 if (u->type == UNIT_SLICE) {
1144 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE], i) {
1149 if (UNIT_DEREF(member->slice) != u)
1152 u->cgroup_members_mask |= unit_get_subtree_mask(member); /* note that this calls ourselves again, for the children */
1156 u->cgroup_members_mask_valid = true;
1157 return u->cgroup_members_mask;
1160 CGroupMask unit_get_siblings_mask(Unit *u) {
1163 /* Returns the mask of controllers all of the unit's siblings
1164 * require, i.e. the members mask of the unit's parent slice
1165 * if there is one. */
1167 if (UNIT_ISSET(u->slice))
1168 return unit_get_members_mask(UNIT_DEREF(u->slice));
1170 return unit_get_subtree_mask(u); /* we are the top-level slice */
1173 CGroupMask unit_get_subtree_mask(Unit *u) {
1175 /* Returns the mask of this subtree, meaning of the group
1176 * itself and its children. */
1178 return unit_get_own_mask(u) | unit_get_members_mask(u);
1181 CGroupMask unit_get_target_mask(Unit *u) {
1184 /* This returns the cgroup mask of all controllers to enable
1185 * for a specific cgroup, i.e. everything it needs itself,
1186 * plus all that its children need, plus all that its siblings
1187 * need. This is primarily useful on the legacy cgroup
1188 * hierarchy, where we need to duplicate each cgroup in each
1189 * hierarchy that shall be enabled for it. */
1191 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
1192 mask &= u->manager->cgroup_supported;
1197 CGroupMask unit_get_enable_mask(Unit *u) {
1200 /* This returns the cgroup mask of all controllers to enable
1201 * for the children of a specific cgroup. This is primarily
1202 * useful for the unified cgroup hierarchy, where each cgroup
1203 * controls which controllers are enabled for its children. */
1205 mask = unit_get_members_mask(u);
1206 mask &= u->manager->cgroup_supported;
1211 bool unit_get_needs_bpf(Unit *u) {
1216 c = unit_get_cgroup_context(u);
1220 if (c->ip_accounting ||
1221 c->ip_address_allow ||
1225 /* If any parent slice has an IP access list defined, it applies too */
1226 for (p = UNIT_DEREF(u->slice); p; p = UNIT_DEREF(p->slice)) {
1227 c = unit_get_cgroup_context(p);
1231 if (c->ip_address_allow ||
1239 /* Recurse from a unit up through its containing slices, propagating
1240 * mask bits upward. A unit is also member of itself. */
1241 void unit_update_cgroup_members_masks(Unit *u) {
1247 /* Calculate subtree mask */
1248 m = unit_get_subtree_mask(u);
1250 /* See if anything changed from the previous invocation. If
1251 * not, we're done. */
1252 if (u->cgroup_subtree_mask_valid && m == u->cgroup_subtree_mask)
1256 u->cgroup_subtree_mask_valid &&
1257 ((m & ~u->cgroup_subtree_mask) != 0) &&
1258 ((~m & u->cgroup_subtree_mask) == 0);
1260 u->cgroup_subtree_mask = m;
1261 u->cgroup_subtree_mask_valid = true;
1263 if (UNIT_ISSET(u->slice)) {
1264 Unit *s = UNIT_DEREF(u->slice);
1267 /* There's more set now than before. We
1268 * propagate the new mask to the parent's mask
1269 * (not caring if it actually was valid or
1272 s->cgroup_members_mask |= m;
1275 /* There's less set now than before (or we
1276 * don't know), we need to recalculate
1277 * everything, so let's invalidate the
1278 * parent's members mask */
1280 s->cgroup_members_mask_valid = false;
1282 /* And now make sure that this change also hits our
1284 unit_update_cgroup_members_masks(s);
1288 const char *unit_get_realized_cgroup_path(Unit *u, CGroupMask mask) {
1290 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
1294 if (u->cgroup_path &&
1295 u->cgroup_realized &&
1296 FLAGS_SET(u->cgroup_realized_mask, mask))
1297 return u->cgroup_path;
1299 u = UNIT_DEREF(u->slice);
1305 static const char *migrate_callback(CGroupMask mask, void *userdata) {
1306 return unit_get_realized_cgroup_path(userdata, mask);
1309 char *unit_default_cgroup_path(Unit *u) {
1310 _cleanup_free_ char *escaped = NULL, *slice = NULL;
1315 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1316 return strdup(u->manager->cgroup_root);
1318 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1319 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1324 escaped = cg_escape(u->id);
1329 return strjoin(u->manager->cgroup_root, "/", slice, "/",
1332 return strjoin(u->manager->cgroup_root, "/", escaped);
1335 int unit_set_cgroup_path(Unit *u, const char *path) {
1336 _cleanup_free_ char *p = NULL;
1348 if (streq_ptr(u->cgroup_path, p))
1352 r = hashmap_put(u->manager->cgroup_unit, p, u);
1357 unit_release_cgroup(u);
1359 u->cgroup_path = TAKE_PTR(p);
1364 int unit_watch_cgroup(Unit *u) {
1365 _cleanup_free_ char *events = NULL;
1370 if (!u->cgroup_path)
1373 if (u->cgroup_inotify_wd >= 0)
1376 /* Only applies to the unified hierarchy */
1377 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1379 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1383 /* Don't watch the root slice, it's pointless. */
1384 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1387 r = hashmap_ensure_allocated(&u->manager->cgroup_inotify_wd_unit, &trivial_hash_ops);
1391 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1395 u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1396 if (u->cgroup_inotify_wd < 0) {
1398 if (errno == ENOENT) /* If the directory is already
1399 * gone we don't need to track
1400 * it, so this is not an error */
1403 return log_unit_error_errno(u, errno, "Failed to add inotify watch descriptor for control group %s: %m", u->cgroup_path);
1406 r = hashmap_put(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd), u);
1408 return log_unit_error_errno(u, r, "Failed to add inotify watch descriptor to hash map: %m");
1413 int unit_pick_cgroup_path(Unit *u) {
1414 _cleanup_free_ char *path = NULL;
1422 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1425 path = unit_default_cgroup_path(u);
1429 r = unit_set_cgroup_path(u, path);
1431 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1433 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1438 static int unit_create_cgroup(
1440 CGroupMask target_mask,
1441 CGroupMask enable_mask,
1450 c = unit_get_cgroup_context(u);
1454 /* Figure out our cgroup path */
1455 r = unit_pick_cgroup_path(u);
1459 /* First, create our own group */
1460 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1462 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1465 /* Start watching it */
1466 (void) unit_watch_cgroup(u);
1468 /* Preserve enabled controllers in delegated units, adjust others. */
1469 if (created || !unit_cgroup_delegate(u)) {
1471 /* Enable all controllers we need */
1472 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path);
1474 log_unit_warning_errno(u, r, "Failed to enable controllers on cgroup %s, ignoring: %m",
1478 /* Keep track that this is now realized */
1479 u->cgroup_realized = true;
1480 u->cgroup_realized_mask = target_mask;
1481 u->cgroup_enabled_mask = enable_mask;
1482 u->cgroup_bpf_state = needs_bpf ? UNIT_CGROUP_BPF_ON : UNIT_CGROUP_BPF_OFF;
1484 if (u->type != UNIT_SLICE && !unit_cgroup_delegate(u)) {
1486 /* Then, possibly move things over, but not if
1487 * subgroups may contain processes, which is the case
1488 * for slice and delegation units. */
1489 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1491 log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
1497 static int unit_attach_pid_to_cgroup_via_bus(Unit *u, pid_t pid, const char *suffix_path) {
1498 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1504 if (MANAGER_IS_SYSTEM(u->manager))
1507 if (!u->manager->system_bus)
1510 if (!u->cgroup_path)
1513 /* Determine this unit's cgroup path relative to our cgroup root */
1514 pp = path_startswith(u->cgroup_path, u->manager->cgroup_root);
1518 pp = strjoina("/", pp, suffix_path);
1519 path_simplify(pp, false);
1521 r = sd_bus_call_method(u->manager->system_bus,
1522 "org.freedesktop.systemd1",
1523 "/org/freedesktop/systemd1",
1524 "org.freedesktop.systemd1.Manager",
1525 "AttachProcessesToUnit",
1528 NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
1530 return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
1535 int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
1536 CGroupMask delegated_mask;
1544 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1547 if (set_isempty(pids))
1550 r = unit_realize_cgroup(u);
1554 if (isempty(suffix_path))
1557 p = strjoina(u->cgroup_path, "/", suffix_path);
1559 delegated_mask = unit_get_delegate_mask(u);
1562 SET_FOREACH(pidp, pids, i) {
1563 pid_t pid = PTR_TO_PID(pidp);
1566 /* First, attach the PID to the main cgroup hierarchy */
1567 q = cg_attach(SYSTEMD_CGROUP_CONTROLLER, p, pid);
1569 log_unit_debug_errno(u, q, "Couldn't move process " PID_FMT " to requested cgroup '%s': %m", pid, p);
1571 if (MANAGER_IS_USER(u->manager) && IN_SET(q, -EPERM, -EACCES)) {
1574 /* If we are in a user instance, and we can't move the process ourselves due to
1575 * permission problems, let's ask the system instance about it instead. Since it's more
1576 * privileged it might be able to move the process across the leaves of a subtree who's
1577 * top node is not owned by us. */
1579 z = unit_attach_pid_to_cgroup_via_bus(u, pid, suffix_path);
1581 log_unit_debug_errno(u, z, "Couldn't move process " PID_FMT " to requested cgroup '%s' via the system bus either: %m", pid, p);
1583 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1587 r = q; /* Remember first error */
1592 q = cg_all_unified();
1598 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
1599 * innermost realized one */
1601 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1602 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1603 const char *realized;
1605 if (!(u->manager->cgroup_supported & bit))
1608 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
1609 if (delegated_mask & u->cgroup_realized_mask & bit) {
1610 q = cg_attach(cgroup_controller_to_string(c), p, pid);
1612 continue; /* Success! */
1614 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",
1615 pid, p, cgroup_controller_to_string(c));
1618 /* So this controller is either not delegate or realized, or something else weird happened. In
1619 * that case let's attach the PID at least to the closest cgroup up the tree that is
1621 realized = unit_get_realized_cgroup_path(u, bit);
1623 continue; /* Not even realized in the root slice? Then let's not bother */
1625 q = cg_attach(cgroup_controller_to_string(c), realized, pid);
1627 log_unit_debug_errno(u, q, "Failed to attach PID " PID_FMT " to realized cgroup %s in controller %s, ignoring: %m",
1628 pid, realized, cgroup_controller_to_string(c));
1635 static void cgroup_xattr_apply(Unit *u) {
1636 char ids[SD_ID128_STRING_MAX];
1641 if (!MANAGER_IS_SYSTEM(u->manager))
1644 if (sd_id128_is_null(u->invocation_id))
1647 r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
1648 "trusted.invocation_id",
1649 sd_id128_to_string(u->invocation_id, ids), 32,
1652 log_unit_debug_errno(u, r, "Failed to set invocation ID on control group %s, ignoring: %m", u->cgroup_path);
1655 static bool unit_has_mask_realized(
1657 CGroupMask target_mask,
1658 CGroupMask enable_mask,
1663 return u->cgroup_realized &&
1664 u->cgroup_realized_mask == target_mask &&
1665 u->cgroup_enabled_mask == enable_mask &&
1666 ((needs_bpf && u->cgroup_bpf_state == UNIT_CGROUP_BPF_ON) ||
1667 (!needs_bpf && u->cgroup_bpf_state == UNIT_CGROUP_BPF_OFF));
1670 static void unit_add_to_cgroup_realize_queue(Unit *u) {
1673 if (u->in_cgroup_realize_queue)
1676 LIST_PREPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
1677 u->in_cgroup_realize_queue = true;
1680 static void unit_remove_from_cgroup_realize_queue(Unit *u) {
1683 if (!u->in_cgroup_realize_queue)
1686 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
1687 u->in_cgroup_realize_queue = false;
1690 /* Check if necessary controllers and attributes for a unit are in place.
1692 * If so, do nothing.
1693 * If not, create paths, move processes over, and set attributes.
1695 * Returns 0 on success and < 0 on failure. */
1696 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
1697 CGroupMask target_mask, enable_mask;
1698 bool needs_bpf, apply_bpf;
1703 unit_remove_from_cgroup_realize_queue(u);
1705 target_mask = unit_get_target_mask(u);
1706 enable_mask = unit_get_enable_mask(u);
1707 needs_bpf = unit_get_needs_bpf(u);
1709 if (unit_has_mask_realized(u, target_mask, enable_mask, needs_bpf))
1712 /* Make sure we apply the BPF filters either when one is configured, or if none is configured but previously
1713 * the state was anything but off. This way, if a unit with a BPF filter applied is reconfigured to lose it
1714 * this will trickle down properly to cgroupfs. */
1715 apply_bpf = needs_bpf || u->cgroup_bpf_state != UNIT_CGROUP_BPF_OFF;
1717 /* First, realize parents */
1718 if (UNIT_ISSET(u->slice)) {
1719 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
1724 /* And then do the real work */
1725 r = unit_create_cgroup(u, target_mask, enable_mask, needs_bpf);
1729 /* Finally, apply the necessary attributes. */
1730 cgroup_context_apply(u, target_mask, apply_bpf, state);
1731 cgroup_xattr_apply(u);
1736 unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
1744 state = manager_state(m);
1746 while ((i = m->cgroup_realize_queue)) {
1747 assert(i->in_cgroup_realize_queue);
1749 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
1750 /* Maybe things changed, and the unit is not actually active anymore? */
1751 unit_remove_from_cgroup_realize_queue(i);
1755 r = unit_realize_cgroup_now(i, state);
1757 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
1765 static void unit_add_siblings_to_cgroup_realize_queue(Unit *u) {
1768 /* This adds the siblings of the specified unit and the
1769 * siblings of all parent units to the cgroup queue. (But
1770 * neither the specified unit itself nor the parents.) */
1772 while ((slice = UNIT_DEREF(u->slice))) {
1777 HASHMAP_FOREACH_KEY(v, m, u->dependencies[UNIT_BEFORE], i) {
1781 /* Skip units that have a dependency on the slice
1782 * but aren't actually in it. */
1783 if (UNIT_DEREF(m->slice) != slice)
1786 /* No point in doing cgroup application for units
1787 * without active processes. */
1788 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
1791 /* If the unit doesn't need any new controllers
1792 * and has current ones realized, it doesn't need
1794 if (unit_has_mask_realized(m,
1795 unit_get_target_mask(m),
1796 unit_get_enable_mask(m),
1797 unit_get_needs_bpf(m)))
1800 unit_add_to_cgroup_realize_queue(m);
1807 int unit_realize_cgroup(Unit *u) {
1810 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1813 /* So, here's the deal: when realizing the cgroups for this
1814 * unit, we need to first create all parents, but there's more
1815 * actually: for the weight-based controllers we also need to
1816 * make sure that all our siblings (i.e. units that are in the
1817 * same slice as we are) have cgroups, too. Otherwise, things
1818 * would become very uneven as each of their processes would
1819 * get as much resources as all our group together. This call
1820 * will synchronously create the parent cgroups, but will
1821 * defer work on the siblings to the next event loop
1824 /* Add all sibling slices to the cgroup queue. */
1825 unit_add_siblings_to_cgroup_realize_queue(u);
1827 /* And realize this one now (and apply the values) */
1828 return unit_realize_cgroup_now(u, manager_state(u->manager));
1831 void unit_release_cgroup(Unit *u) {
1834 /* Forgets all cgroup details for this cgroup */
1836 if (u->cgroup_path) {
1837 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1838 u->cgroup_path = mfree(u->cgroup_path);
1841 if (u->cgroup_inotify_wd >= 0) {
1842 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1843 log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1845 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1846 u->cgroup_inotify_wd = -1;
1850 void unit_prune_cgroup(Unit *u) {
1856 /* Removes the cgroup, if empty and possible, and stops watching it. */
1858 if (!u->cgroup_path)
1861 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
1863 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1865 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
1867 log_unit_debug_errno(u, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
1874 unit_release_cgroup(u);
1876 u->cgroup_realized = false;
1877 u->cgroup_realized_mask = 0;
1878 u->cgroup_enabled_mask = 0;
1881 int unit_search_main_pid(Unit *u, pid_t *ret) {
1882 _cleanup_fclose_ FILE *f = NULL;
1883 pid_t pid = 0, npid, mypid;
1889 if (!u->cgroup_path)
1892 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1896 mypid = getpid_cached();
1897 while (cg_read_pid(f, &npid) > 0) {
1903 /* Ignore processes that aren't our kids */
1904 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
1908 /* Dang, there's more than one daemonized PID
1909 in this group, so we don't know what process
1910 is the main process. */
1921 static int unit_watch_pids_in_path(Unit *u, const char *path) {
1922 _cleanup_closedir_ DIR *d = NULL;
1923 _cleanup_fclose_ FILE *f = NULL;
1929 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1935 while ((r = cg_read_pid(f, &pid)) > 0) {
1936 r = unit_watch_pid(u, pid);
1937 if (r < 0 && ret >= 0)
1941 if (r < 0 && ret >= 0)
1945 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1952 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1953 _cleanup_free_ char *p = NULL;
1955 p = strjoin(path, "/", fn);
1961 r = unit_watch_pids_in_path(u, p);
1962 if (r < 0 && ret >= 0)
1966 if (r < 0 && ret >= 0)
1973 int unit_synthesize_cgroup_empty_event(Unit *u) {
1978 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
1979 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
1980 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
1982 if (!u->cgroup_path)
1985 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1988 if (r > 0) /* On unified we have reliable notifications, and don't need this */
1991 if (!set_isempty(u->pids))
1994 unit_add_to_cgroup_empty_queue(u);
1998 int unit_watch_all_pids(Unit *u) {
2003 /* Adds all PIDs from our cgroup to the set of PIDs we
2004 * watch. This is a fallback logic for cases where we do not
2005 * get reliable cgroup empty notifications: we try to use
2006 * SIGCHLD as replacement. */
2008 if (!u->cgroup_path)
2011 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2014 if (r > 0) /* On unified we can use proper notifications */
2017 return unit_watch_pids_in_path(u, u->cgroup_path);
2020 static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
2021 Manager *m = userdata;
2028 u = m->cgroup_empty_queue;
2032 assert(u->in_cgroup_empty_queue);
2033 u->in_cgroup_empty_queue = false;
2034 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
2036 if (m->cgroup_empty_queue) {
2037 /* More stuff queued, let's make sure we remain enabled */
2038 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
2040 log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
2043 unit_add_to_gc_queue(u);
2045 if (UNIT_VTABLE(u)->notify_cgroup_empty)
2046 UNIT_VTABLE(u)->notify_cgroup_empty(u);
2051 void unit_add_to_cgroup_empty_queue(Unit *u) {
2056 /* Note that there are four different ways how cgroup empty events reach us:
2058 * 1. On the unified hierarchy we get an inotify event on the cgroup
2060 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2062 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2064 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2065 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2067 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2068 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2069 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2070 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2071 * case for scope units). */
2073 if (u->in_cgroup_empty_queue)
2076 /* Let's verify that the cgroup is really empty */
2077 if (!u->cgroup_path)
2079 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
2081 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", u->cgroup_path);
2087 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
2088 u->in_cgroup_empty_queue = true;
2090 /* Trigger the defer event */
2091 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
2093 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
2096 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2097 Manager *m = userdata;
2104 union inotify_event_buffer buffer;
2105 struct inotify_event *e;
2108 l = read(fd, &buffer, sizeof(buffer));
2110 if (IN_SET(errno, EINTR, EAGAIN))
2113 return log_error_errno(errno, "Failed to read control group inotify events: %m");
2116 FOREACH_INOTIFY_EVENT(e, buffer, l) {
2120 /* Queue overflow has no watch descriptor */
2123 if (e->mask & IN_IGNORED)
2124 /* The watch was just removed */
2127 u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
2128 if (!u) /* Not that inotify might deliver
2129 * events for a watch even after it
2130 * was removed, because it was queued
2131 * before the removal. Let's ignore
2132 * this here safely. */
2135 unit_add_to_cgroup_empty_queue(u);
2141 int manager_setup_cgroup(Manager *m) {
2142 _cleanup_free_ char *path = NULL;
2143 const char *scope_path;
2146 #if 0 /// UNNEEDED by elogind
2152 /* 1. Determine hierarchy */
2153 m->cgroup_root = mfree(m->cgroup_root);
2154 #if 0 /// elogind is not init and must therefore search for PID 1 instead of self.
2155 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
2157 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &m->cgroup_root);
2160 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
2162 #if 0 /// elogind does not support systemd scopes and slices
2163 /* Chop off the init scope, if we are already located in it */
2164 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2166 /* LEGACY: Also chop off the system slice if we are in
2167 * it. This is to support live upgrades from older systemd
2168 * versions where PID 1 was moved there. Also see
2169 * cg_get_root_path(). */
2170 if (!e && MANAGER_IS_SYSTEM(m)) {
2171 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
2173 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
2179 log_debug_elogind("Cgroup Controller \"%s\" -> root \"%s\"",
2180 SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root);
2181 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2182 * easily prepend it everywhere. */
2183 delete_trailing_chars(m->cgroup_root, "/");
2186 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
2188 return log_error_errno(r, "Cannot find cgroup mount point: %m");
2190 r = cg_unified_flush();
2192 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
2194 all_unified = cg_all_unified();
2195 if (all_unified < 0)
2196 return log_error_errno(all_unified, "Couldn't determine whether we are in all unified mode: %m");
2197 if (all_unified > 0)
2198 log_debug("Unified cgroup hierarchy is located at %s.", path);
2200 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2202 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
2204 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
2206 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
2209 #if 0 /// elogind is not init, and does not install the agent here.
2210 /* 3. Allocate cgroup empty defer event source */
2211 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2212 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
2214 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
2216 r = sd_event_source_set_priority(m->cgroup_empty_event_source, SD_EVENT_PRIORITY_NORMAL-5);
2218 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
2220 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
2222 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
2224 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
2226 /* 4. Install notifier inotify object, or agent */
2227 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
2229 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2231 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2232 safe_close(m->cgroup_inotify_fd);
2234 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
2235 if (m->cgroup_inotify_fd < 0)
2236 return log_error_errno(errno, "Failed to create control group inotify object: %m");
2238 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
2240 return log_error_errno(r, "Failed to watch control group inotify object: %m");
2242 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
2243 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2244 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-4);
2246 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
2248 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
2250 } else if (MANAGER_IS_SYSTEM(m) && m->test_run_flags == 0) {
2252 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2253 * since it does not generate events when control groups with children run empty. */
2255 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
2257 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
2259 log_debug("Installed release agent.");
2261 log_debug("Release agent already installed.");
2264 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2265 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2266 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2268 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2269 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2271 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
2274 * This method is in core, and normally called by systemd
2275 * being init. As elogind is never init, we can not install
2276 * our agent here. We do so when mounting our cgroup file
2277 * system, so only if elogind is its own tiny controller.
2278 * Further, elogind is not meant to run in systemd init scope. */
2279 if (MANAGER_IS_SYSTEM(m))
2280 // we are our own cgroup controller
2281 scope_path = strjoina("");
2282 else if (streq(m->cgroup_root, "/elogind"))
2283 // root already is our cgroup
2284 scope_path = strjoina(m->cgroup_root);
2286 // we have to create our own group
2287 scope_path = strjoina(m->cgroup_root, "/elogind");
2288 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2290 log_debug_elogind("Created control group \"%s\"", scope_path);
2292 /* 6. And pin it, so that it cannot be unmounted */
2293 safe_close(m->pin_cgroupfs_fd);
2294 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
2295 if (m->pin_cgroupfs_fd < 0)
2296 return log_error_errno(errno, "Failed to open pin file: %m");
2298 #if 0 /// this is from the cgroup migration above that elogind does not need.
2299 } else if (r < 0 && !m->test_run_flags)
2300 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
2303 /* 7. Always enable hierarchical support if it exists... */
2304 if (!all_unified && m->test_run_flags == 0)
2305 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
2307 /* 8. Figure out which controllers are supported, and log about it */
2308 r = cg_mask_supported(&m->cgroup_supported);
2310 return log_error_errno(r, "Failed to determine supported controllers: %m");
2311 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
2312 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
2317 void manager_shutdown_cgroup(Manager *m, bool delete) {
2320 #if 0 /// elogind is not init
2321 /* We can't really delete the group, since we are in it. But
2323 if (delete && m->cgroup_root && m->test_run_flags != MANAGER_TEST_RUN_MINIMAL)
2324 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
2326 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2328 m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
2330 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2331 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
2334 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
2336 m->cgroup_root = mfree(m->cgroup_root);
2339 #if 0 /// UNNEEDED by elogind
2340 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
2347 u = hashmap_get(m->cgroup_unit, cgroup);
2351 p = strdupa(cgroup);
2355 e = strrchr(p, '/');
2357 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
2361 u = hashmap_get(m->cgroup_unit, p);
2367 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
2368 _cleanup_free_ char *cgroup = NULL;
2372 if (!pid_is_valid(pid))
2375 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup) < 0)
2378 return manager_get_unit_by_cgroup(m, cgroup);
2381 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
2386 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
2387 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
2388 * relevant one as children of the process will be assigned to that one, too, before all else. */
2390 if (!pid_is_valid(pid))
2393 if (pid == getpid_cached())
2394 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
2396 u = manager_get_unit_by_pid_cgroup(m, pid);
2400 u = hashmap_get(m->watch_pids, PID_TO_PTR(pid));
2404 array = hashmap_get(m->watch_pids, PID_TO_PTR(-pid));
2412 #if 0 /// elogind must substitute this with its own variant
2413 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
2419 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
2420 * or from the --system instance */
2422 log_debug("Got cgroup empty notification for: %s", cgroup);
2424 u = manager_get_unit_by_cgroup(m, cgroup);
2428 unit_add_to_cgroup_empty_queue(u);
2432 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
2438 log_debug("Got cgroup empty notification for: %s", cgroup);
2440 s = hashmap_get(m->sessions, cgroup);
2443 session_finalize(s);
2446 log_warning("Session not found: %s", cgroup);
2451 #if 0 /// UNNEEDED by elogind
2452 int unit_get_memory_current(Unit *u, uint64_t *ret) {
2453 _cleanup_free_ char *v = NULL;
2459 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
2462 if (!u->cgroup_path)
2465 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2466 if (unit_has_root_cgroup(u))
2467 return procfs_memory_get_current(ret);
2469 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
2472 r = cg_all_unified();
2476 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
2478 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
2484 return safe_atou64(v, ret);
2487 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
2488 _cleanup_free_ char *v = NULL;
2494 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
2497 if (!u->cgroup_path)
2500 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2501 if (unit_has_root_cgroup(u))
2502 return procfs_tasks_get_current(ret);
2504 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
2507 r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
2513 return safe_atou64(v, ret);
2516 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
2517 _cleanup_free_ char *v = NULL;
2524 if (!u->cgroup_path)
2527 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2528 if (unit_has_root_cgroup(u))
2529 return procfs_cpu_get_usage(ret);
2531 r = cg_all_unified();
2535 _cleanup_free_ char *val = NULL;
2538 if ((u->cgroup_realized_mask & CGROUP_MASK_CPU) == 0)
2541 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
2544 if (IN_SET(r, -ENOENT, -ENXIO))
2547 r = safe_atou64(val, &us);
2551 ns = us * NSEC_PER_USEC;
2553 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
2556 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
2562 r = safe_atou64(v, &ns);
2571 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
2577 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2578 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2579 * call this function with a NULL return value. */
2581 if (!UNIT_CGROUP_BOOL(u, cpu_accounting))
2584 r = unit_get_cpu_usage_raw(u, &ns);
2585 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
2586 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2590 *ret = u->cpu_usage_last;
2596 if (ns > u->cpu_usage_base)
2597 ns -= u->cpu_usage_base;
2601 u->cpu_usage_last = ns;
2608 int unit_get_ip_accounting(
2610 CGroupIPAccountingMetric metric,
2617 assert(metric >= 0);
2618 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
2621 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
2624 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
2625 u->ip_accounting_ingress_map_fd :
2626 u->ip_accounting_egress_map_fd;
2630 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
2631 r = bpf_firewall_read_accounting(fd, &value, NULL);
2633 r = bpf_firewall_read_accounting(fd, NULL, &value);
2637 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
2638 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
2639 * ip_accounting_extra[] field, and add them in here transparently. */
2641 *ret = value + u->ip_accounting_extra[metric];
2646 int unit_reset_cpu_accounting(Unit *u) {
2652 u->cpu_usage_last = NSEC_INFINITY;
2654 r = unit_get_cpu_usage_raw(u, &ns);
2656 u->cpu_usage_base = 0;
2660 u->cpu_usage_base = ns;
2664 int unit_reset_ip_accounting(Unit *u) {
2669 if (u->ip_accounting_ingress_map_fd >= 0)
2670 r = bpf_firewall_reset_accounting(u->ip_accounting_ingress_map_fd);
2672 if (u->ip_accounting_egress_map_fd >= 0)
2673 q = bpf_firewall_reset_accounting(u->ip_accounting_egress_map_fd);
2675 zero(u->ip_accounting_extra);
2677 return r < 0 ? r : q;
2680 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
2683 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2689 /* always invalidate compat pairs together */
2690 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
2691 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
2693 if (m & (CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT))
2694 m |= CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT;
2696 if ((u->cgroup_realized_mask & m) == 0) /* NOP? */
2699 u->cgroup_realized_mask &= ~m;
2700 unit_add_to_cgroup_realize_queue(u);
2703 void unit_invalidate_cgroup_bpf(Unit *u) {
2706 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2709 if (u->cgroup_bpf_state == UNIT_CGROUP_BPF_INVALIDATED) /* NOP? */
2712 u->cgroup_bpf_state = UNIT_CGROUP_BPF_INVALIDATED;
2713 unit_add_to_cgroup_realize_queue(u);
2715 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
2716 * list of our children includes our own. */
2717 if (u->type == UNIT_SLICE) {
2722 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE], i) {
2726 if (UNIT_DEREF(member->slice) != u)
2729 unit_invalidate_cgroup_bpf(member);
2734 bool unit_cgroup_delegate(Unit *u) {
2739 if (!UNIT_VTABLE(u)->can_delegate)
2742 c = unit_get_cgroup_context(u);
2749 void manager_invalidate_startup_units(Manager *m) {
2755 SET_FOREACH(u, m->startup_units, i)
2756 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
2759 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
2760 [CGROUP_AUTO] = "auto",
2761 [CGROUP_CLOSED] = "closed",
2762 [CGROUP_STRICT] = "strict",
2765 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);