2 This file is part of systemd.
4 Copyright 2013 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
23 #include "alloc-util.h"
24 //#include "bpf-firewall.h"
25 #include "cgroup-util.h"
30 #include "parse-util.h"
31 #include "path-util.h"
32 #include "process-util.h"
33 //#include "special.h"
34 #include "stdio-util.h"
35 #include "string-table.h"
36 #include "string-util.h"
38 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
40 #if 0 /// UNNEEDED by elogind
41 static void cgroup_compat_warn(void) {
42 static bool cgroup_compat_warned = false;
44 if (cgroup_compat_warned)
47 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. See cgroup-compat debug messages for details.");
48 cgroup_compat_warned = true;
51 #define log_cgroup_compat(unit, fmt, ...) do { \
52 cgroup_compat_warn(); \
53 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
56 void cgroup_context_init(CGroupContext *c) {
59 /* Initialize everything to the kernel defaults, assuming the
60 * structure is preinitialized to 0 */
62 c->cpu_weight = CGROUP_WEIGHT_INVALID;
63 c->startup_cpu_weight = CGROUP_WEIGHT_INVALID;
64 c->cpu_quota_per_sec_usec = USEC_INFINITY;
66 c->cpu_shares = CGROUP_CPU_SHARES_INVALID;
67 c->startup_cpu_shares = CGROUP_CPU_SHARES_INVALID;
69 c->memory_high = CGROUP_LIMIT_MAX;
70 c->memory_max = CGROUP_LIMIT_MAX;
71 c->memory_swap_max = CGROUP_LIMIT_MAX;
73 c->memory_limit = CGROUP_LIMIT_MAX;
75 c->io_weight = CGROUP_WEIGHT_INVALID;
76 c->startup_io_weight = CGROUP_WEIGHT_INVALID;
78 c->blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
79 c->startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
81 c->tasks_max = (uint64_t) -1;
84 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
88 LIST_REMOVE(device_allow, c->device_allow, a);
93 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
97 LIST_REMOVE(device_weights, c->io_device_weights, w);
102 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
106 LIST_REMOVE(device_limits, c->io_device_limits, l);
111 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
115 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
120 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
124 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
129 void cgroup_context_done(CGroupContext *c) {
132 while (c->io_device_weights)
133 cgroup_context_free_io_device_weight(c, c->io_device_weights);
135 while (c->io_device_limits)
136 cgroup_context_free_io_device_limit(c, c->io_device_limits);
138 while (c->blockio_device_weights)
139 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
141 while (c->blockio_device_bandwidths)
142 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
144 while (c->device_allow)
145 cgroup_context_free_device_allow(c, c->device_allow);
147 c->ip_address_allow = ip_address_access_free_all(c->ip_address_allow);
148 c->ip_address_deny = ip_address_access_free_all(c->ip_address_deny);
151 void cgroup_context_dump(CGroupContext *c, FILE* f, const char *prefix) {
152 CGroupIODeviceLimit *il;
153 CGroupIODeviceWeight *iw;
154 CGroupBlockIODeviceBandwidth *b;
155 CGroupBlockIODeviceWeight *w;
156 CGroupDeviceAllow *a;
157 IPAddressAccessItem *iaai;
158 char u[FORMAT_TIMESPAN_MAX];
163 prefix = strempty(prefix);
166 "%sCPUAccounting=%s\n"
167 "%sIOAccounting=%s\n"
168 "%sBlockIOAccounting=%s\n"
169 "%sMemoryAccounting=%s\n"
170 "%sTasksAccounting=%s\n"
171 "%sIPAccounting=%s\n"
172 "%sCPUWeight=%" PRIu64 "\n"
173 "%sStartupCPUWeight=%" PRIu64 "\n"
174 "%sCPUShares=%" PRIu64 "\n"
175 "%sStartupCPUShares=%" PRIu64 "\n"
176 "%sCPUQuotaPerSecSec=%s\n"
177 "%sIOWeight=%" PRIu64 "\n"
178 "%sStartupIOWeight=%" PRIu64 "\n"
179 "%sBlockIOWeight=%" PRIu64 "\n"
180 "%sStartupBlockIOWeight=%" PRIu64 "\n"
181 "%sMemoryLow=%" PRIu64 "\n"
182 "%sMemoryHigh=%" PRIu64 "\n"
183 "%sMemoryMax=%" PRIu64 "\n"
184 "%sMemorySwapMax=%" PRIu64 "\n"
185 "%sMemoryLimit=%" PRIu64 "\n"
186 "%sTasksMax=%" PRIu64 "\n"
187 "%sDevicePolicy=%s\n"
189 prefix, yes_no(c->cpu_accounting),
190 prefix, yes_no(c->io_accounting),
191 prefix, yes_no(c->blockio_accounting),
192 prefix, yes_no(c->memory_accounting),
193 prefix, yes_no(c->tasks_accounting),
194 prefix, yes_no(c->ip_accounting),
195 prefix, c->cpu_weight,
196 prefix, c->startup_cpu_weight,
197 prefix, c->cpu_shares,
198 prefix, c->startup_cpu_shares,
199 prefix, format_timespan(u, sizeof(u), c->cpu_quota_per_sec_usec, 1),
200 prefix, c->io_weight,
201 prefix, c->startup_io_weight,
202 prefix, c->blockio_weight,
203 prefix, c->startup_blockio_weight,
204 prefix, c->memory_low,
205 prefix, c->memory_high,
206 prefix, c->memory_max,
207 prefix, c->memory_swap_max,
208 prefix, c->memory_limit,
209 prefix, c->tasks_max,
210 prefix, cgroup_device_policy_to_string(c->device_policy),
211 prefix, yes_no(c->delegate));
213 LIST_FOREACH(device_allow, a, c->device_allow)
215 "%sDeviceAllow=%s %s%s%s\n",
218 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
220 LIST_FOREACH(device_weights, iw, c->io_device_weights)
222 "%sIODeviceWeight=%s %" PRIu64,
227 LIST_FOREACH(device_limits, il, c->io_device_limits) {
228 char buf[FORMAT_BYTES_MAX];
229 CGroupIOLimitType type;
231 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
232 if (il->limits[type] != cgroup_io_limit_defaults[type])
236 cgroup_io_limit_type_to_string(type),
238 format_bytes(buf, sizeof(buf), il->limits[type]));
241 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
243 "%sBlockIODeviceWeight=%s %" PRIu64,
248 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
249 char buf[FORMAT_BYTES_MAX];
251 if (b->rbps != CGROUP_LIMIT_MAX)
253 "%sBlockIOReadBandwidth=%s %s\n",
256 format_bytes(buf, sizeof(buf), b->rbps));
257 if (b->wbps != CGROUP_LIMIT_MAX)
259 "%sBlockIOWriteBandwidth=%s %s\n",
262 format_bytes(buf, sizeof(buf), b->wbps));
265 LIST_FOREACH(items, iaai, c->ip_address_allow) {
266 _cleanup_free_ char *k = NULL;
268 (void) in_addr_to_string(iaai->family, &iaai->address, &k);
269 fprintf(f, "%sIPAddressAllow=%s/%u\n", prefix, strnull(k), iaai->prefixlen);
272 LIST_FOREACH(items, iaai, c->ip_address_deny) {
273 _cleanup_free_ char *k = NULL;
275 (void) in_addr_to_string(iaai->family, &iaai->address, &k);
276 fprintf(f, "%sIPAddressDeny=%s/%u\n", prefix, strnull(k), iaai->prefixlen);
280 static int lookup_block_device(const char *p, dev_t *dev) {
289 return log_warning_errno(errno, "Couldn't stat device %s: %m", p);
291 if (S_ISBLK(st.st_mode))
293 else if (major(st.st_dev) != 0) {
294 /* If this is not a device node then find the block
295 * device this file is stored on */
298 /* If this is a partition, try to get the originating
300 block_get_whole_disk(*dev, dev);
302 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p);
309 static int whitelist_device(const char *path, const char *node, const char *acc) {
310 char buf[2+DECIMAL_STR_MAX(dev_t)*2+2+4];
312 bool ignore_notfound;
318 if (node[0] == '-') {
319 /* Non-existent paths starting with "-" must be silently ignored */
321 ignore_notfound = true;
323 ignore_notfound = false;
325 if (stat(node, &st) < 0) {
326 if (errno == ENOENT && ignore_notfound)
329 return log_warning_errno(errno, "Couldn't stat device %s: %m", node);
332 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
333 log_warning("%s is not a device.", node);
339 S_ISCHR(st.st_mode) ? 'c' : 'b',
340 major(st.st_rdev), minor(st.st_rdev),
343 r = cg_set_attribute("devices", path, "devices.allow", buf);
345 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
346 "Failed to set devices.allow on %s: %m", path);
351 static int whitelist_major(const char *path, const char *name, char type, const char *acc) {
352 _cleanup_fclose_ FILE *f = NULL;
359 assert(IN_SET(type, 'b', 'c'));
361 f = fopen("/proc/devices", "re");
363 return log_warning_errno(errno, "Cannot open /proc/devices to resolve %s (%c): %m", name, type);
365 FOREACH_LINE(line, f, goto fail) {
366 char buf[2+DECIMAL_STR_MAX(unsigned)+3+4], *p, *w;
371 if (type == 'c' && streq(line, "Character devices:")) {
376 if (type == 'b' && streq(line, "Block devices:")) {
391 w = strpbrk(p, WHITESPACE);
396 r = safe_atou(p, &maj);
403 w += strspn(w, WHITESPACE);
405 if (fnmatch(name, w, 0) != 0)
414 r = cg_set_attribute("devices", path, "devices.allow", buf);
416 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
417 "Failed to set devices.allow on %s: %m", path);
423 return log_warning_errno(errno, "Failed to read /proc/devices: %m");
426 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
427 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
428 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
431 static bool cgroup_context_has_cpu_shares(CGroupContext *c) {
432 return c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
433 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID;
436 static uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
437 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
438 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
439 return c->startup_cpu_weight;
440 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
441 return c->cpu_weight;
443 return CGROUP_WEIGHT_DEFAULT;
446 static uint64_t cgroup_context_cpu_shares(CGroupContext *c, ManagerState state) {
447 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
448 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID)
449 return c->startup_cpu_shares;
450 else if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID)
451 return c->cpu_shares;
453 return CGROUP_CPU_SHARES_DEFAULT;
456 static void cgroup_apply_unified_cpu_config(Unit *u, uint64_t weight, uint64_t quota) {
457 char buf[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t) + 1) * 2)];
460 xsprintf(buf, "%" PRIu64 "\n", weight);
461 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.weight", buf);
463 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
464 "Failed to set cpu.weight: %m");
466 if (quota != USEC_INFINITY)
467 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
468 quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC, CGROUP_CPU_QUOTA_PERIOD_USEC);
470 xsprintf(buf, "max " USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
472 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.max", buf);
475 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
476 "Failed to set cpu.max: %m");
479 static void cgroup_apply_legacy_cpu_config(Unit *u, uint64_t shares, uint64_t quota) {
480 char buf[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t)) + 1];
483 xsprintf(buf, "%" PRIu64 "\n", shares);
484 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.shares", buf);
486 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
487 "Failed to set cpu.shares: %m");
489 xsprintf(buf, USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
490 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_period_us", buf);
492 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
493 "Failed to set cpu.cfs_period_us: %m");
495 if (quota != USEC_INFINITY) {
496 xsprintf(buf, USEC_FMT "\n", quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC);
497 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", buf);
499 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", "-1");
501 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
502 "Failed to set cpu.cfs_quota_us: %m");
505 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares) {
506 return CLAMP(shares * CGROUP_WEIGHT_DEFAULT / CGROUP_CPU_SHARES_DEFAULT,
507 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
510 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight) {
511 return CLAMP(weight * CGROUP_CPU_SHARES_DEFAULT / CGROUP_WEIGHT_DEFAULT,
512 CGROUP_CPU_SHARES_MIN, CGROUP_CPU_SHARES_MAX);
515 static bool cgroup_context_has_io_config(CGroupContext *c) {
516 return c->io_accounting ||
517 c->io_weight != CGROUP_WEIGHT_INVALID ||
518 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
519 c->io_device_weights ||
523 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
524 return c->blockio_accounting ||
525 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
526 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
527 c->blockio_device_weights ||
528 c->blockio_device_bandwidths;
531 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
532 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
533 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
534 return c->startup_io_weight;
535 else if (c->io_weight != CGROUP_WEIGHT_INVALID)
538 return CGROUP_WEIGHT_DEFAULT;
541 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
542 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
543 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
544 return c->startup_blockio_weight;
545 else if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
546 return c->blockio_weight;
548 return CGROUP_BLKIO_WEIGHT_DEFAULT;
551 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
552 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
553 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
556 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
557 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
558 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
561 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
562 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
566 r = lookup_block_device(dev_path, &dev);
570 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), io_weight);
571 r = cg_set_attribute("io", u->cgroup_path, "io.weight", buf);
573 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
574 "Failed to set io.weight: %m");
577 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
578 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
582 r = lookup_block_device(dev_path, &dev);
586 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), blkio_weight);
587 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.weight_device", buf);
589 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
590 "Failed to set blkio.weight_device: %m");
593 static unsigned cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
594 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)];
595 char buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
596 CGroupIOLimitType type;
601 r = lookup_block_device(dev_path, &dev);
605 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++) {
606 if (limits[type] != cgroup_io_limit_defaults[type]) {
607 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
610 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
614 xsprintf(buf, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev), minor(dev),
615 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
616 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
617 r = cg_set_attribute("io", u->cgroup_path, "io.max", buf);
619 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
620 "Failed to set io.max: %m");
624 static unsigned cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
625 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
630 r = lookup_block_device(dev_path, &dev);
634 if (rbps != CGROUP_LIMIT_MAX)
636 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), rbps);
637 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.read_bps_device", buf);
639 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
640 "Failed to set blkio.throttle.read_bps_device: %m");
642 if (wbps != CGROUP_LIMIT_MAX)
644 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), wbps);
645 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.write_bps_device", buf);
647 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
648 "Failed to set blkio.throttle.write_bps_device: %m");
653 static bool cgroup_context_has_unified_memory_config(CGroupContext *c) {
654 return c->memory_low > 0 || c->memory_high != CGROUP_LIMIT_MAX || c->memory_max != CGROUP_LIMIT_MAX || c->memory_swap_max != CGROUP_LIMIT_MAX;
657 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
658 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
661 if (v != CGROUP_LIMIT_MAX)
662 xsprintf(buf, "%" PRIu64 "\n", v);
664 r = cg_set_attribute("memory", u->cgroup_path, file, buf);
666 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
667 "Failed to set %s: %m", file);
670 static void cgroup_apply_firewall(Unit *u, CGroupContext *c) {
673 if (u->type == UNIT_SLICE) /* Skip this for slice units, they are inner cgroup nodes, and since bpf/cgroup is
674 * not recursive we don't ever touch the bpf on them */
677 r = bpf_firewall_compile(u);
681 (void) bpf_firewall_install(u);
685 static void cgroup_context_apply(
687 CGroupMask apply_mask,
689 ManagerState state) {
698 c = unit_get_cgroup_context(u);
699 path = u->cgroup_path;
704 /* Nothing to do? Exit early! */
705 if (apply_mask == 0 && !apply_bpf)
708 /* Some cgroup attributes are not supported on the root cgroup,
709 * hence silently ignore */
710 is_root = isempty(path) || path_equal(path, "/");
712 /* Make sure we don't try to display messages with an empty path. */
715 /* We generally ignore errors caused by read-only mounted
716 * cgroup trees (assuming we are running in a container then),
717 * and missing cgroups, i.e. EROFS and ENOENT. */
719 if ((apply_mask & CGROUP_MASK_CPU) && !is_root) {
720 bool has_weight, has_shares;
722 has_weight = cgroup_context_has_cpu_weight(c);
723 has_shares = cgroup_context_has_cpu_shares(c);
725 if (cg_all_unified() > 0) {
729 weight = cgroup_context_cpu_weight(c, state);
730 else if (has_shares) {
731 uint64_t shares = cgroup_context_cpu_shares(c, state);
733 weight = cgroup_cpu_shares_to_weight(shares);
735 log_cgroup_compat(u, "Applying [Startup]CpuShares %" PRIu64 " as [Startup]CpuWeight %" PRIu64 " on %s",
736 shares, weight, path);
738 weight = CGROUP_WEIGHT_DEFAULT;
740 cgroup_apply_unified_cpu_config(u, weight, c->cpu_quota_per_sec_usec);
745 uint64_t weight = cgroup_context_cpu_weight(c, state);
747 shares = cgroup_cpu_weight_to_shares(weight);
749 log_cgroup_compat(u, "Applying [Startup]CpuWeight %" PRIu64 " as [Startup]CpuShares %" PRIu64 " on %s",
750 weight, shares, path);
751 } else if (has_shares)
752 shares = cgroup_context_cpu_shares(c, state);
754 shares = CGROUP_CPU_SHARES_DEFAULT;
756 cgroup_apply_legacy_cpu_config(u, shares, c->cpu_quota_per_sec_usec);
760 if (apply_mask & CGROUP_MASK_IO) {
761 bool has_io = cgroup_context_has_io_config(c);
762 bool has_blockio = cgroup_context_has_blockio_config(c);
765 char buf[8+DECIMAL_STR_MAX(uint64_t)+1];
769 weight = cgroup_context_io_weight(c, state);
770 else if (has_blockio) {
771 uint64_t blkio_weight = cgroup_context_blkio_weight(c, state);
773 weight = cgroup_weight_blkio_to_io(blkio_weight);
775 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight %" PRIu64 " as [Startup]IOWeight %" PRIu64,
776 blkio_weight, weight);
778 weight = CGROUP_WEIGHT_DEFAULT;
780 xsprintf(buf, "default %" PRIu64 "\n", weight);
781 r = cg_set_attribute("io", path, "io.weight", buf);
783 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
784 "Failed to set io.weight: %m");
787 CGroupIODeviceWeight *w;
789 /* FIXME: no way to reset this list */
790 LIST_FOREACH(device_weights, w, c->io_device_weights)
791 cgroup_apply_io_device_weight(u, w->path, w->weight);
792 } else if (has_blockio) {
793 CGroupBlockIODeviceWeight *w;
795 /* FIXME: no way to reset this list */
796 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
797 weight = cgroup_weight_blkio_to_io(w->weight);
799 log_cgroup_compat(u, "Applying BlockIODeviceWeight %" PRIu64 " as IODeviceWeight %" PRIu64 " for %s",
800 w->weight, weight, w->path);
802 cgroup_apply_io_device_weight(u, w->path, weight);
807 /* Apply limits and free ones without config. */
809 CGroupIODeviceLimit *l, *next;
811 LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
812 if (!cgroup_apply_io_device_limit(u, l->path, l->limits))
813 cgroup_context_free_io_device_limit(c, l);
815 } else if (has_blockio) {
816 CGroupBlockIODeviceBandwidth *b, *next;
818 LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths) {
819 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
820 CGroupIOLimitType type;
822 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
823 limits[type] = cgroup_io_limit_defaults[type];
825 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
826 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
828 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax for %s",
829 b->rbps, b->wbps, b->path);
831 if (!cgroup_apply_io_device_limit(u, b->path, limits))
832 cgroup_context_free_blockio_device_bandwidth(c, b);
837 if (apply_mask & CGROUP_MASK_BLKIO) {
838 bool has_io = cgroup_context_has_io_config(c);
839 bool has_blockio = cgroup_context_has_blockio_config(c);
842 char buf[DECIMAL_STR_MAX(uint64_t)+1];
846 uint64_t io_weight = cgroup_context_io_weight(c, state);
848 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
850 log_cgroup_compat(u, "Applying [Startup]IOWeight %" PRIu64 " as [Startup]BlockIOWeight %" PRIu64,
852 } else if (has_blockio)
853 weight = cgroup_context_blkio_weight(c, state);
855 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
857 xsprintf(buf, "%" PRIu64 "\n", weight);
858 r = cg_set_attribute("blkio", path, "blkio.weight", buf);
860 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
861 "Failed to set blkio.weight: %m");
864 CGroupIODeviceWeight *w;
866 /* FIXME: no way to reset this list */
867 LIST_FOREACH(device_weights, w, c->io_device_weights) {
868 weight = cgroup_weight_io_to_blkio(w->weight);
870 log_cgroup_compat(u, "Applying IODeviceWeight %" PRIu64 " as BlockIODeviceWeight %" PRIu64 " for %s",
871 w->weight, weight, w->path);
873 cgroup_apply_blkio_device_weight(u, w->path, weight);
875 } else if (has_blockio) {
876 CGroupBlockIODeviceWeight *w;
878 /* FIXME: no way to reset this list */
879 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
880 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
884 /* Apply limits and free ones without config. */
886 CGroupIODeviceLimit *l, *next;
888 LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
889 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax for %s",
890 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
892 if (!cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]))
893 cgroup_context_free_io_device_limit(c, l);
895 } else if (has_blockio) {
896 CGroupBlockIODeviceBandwidth *b, *next;
898 LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths)
899 if (!cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps))
900 cgroup_context_free_blockio_device_bandwidth(c, b);
904 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_root) {
905 if (cg_all_unified() > 0) {
906 uint64_t max, swap_max = CGROUP_LIMIT_MAX;
908 if (cgroup_context_has_unified_memory_config(c)) {
910 swap_max = c->memory_swap_max;
912 max = c->memory_limit;
914 if (max != CGROUP_LIMIT_MAX)
915 log_cgroup_compat(u, "Applying MemoryLimit %" PRIu64 " as MemoryMax", max);
918 cgroup_apply_unified_memory_limit(u, "memory.low", c->memory_low);
919 cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
920 cgroup_apply_unified_memory_limit(u, "memory.max", max);
921 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
923 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
926 if (cgroup_context_has_unified_memory_config(c)) {
928 log_cgroup_compat(u, "Applying MemoryMax %" PRIi64 " as MemoryLimit", val);
930 val = c->memory_limit;
932 if (val == CGROUP_LIMIT_MAX)
933 strncpy(buf, "-1\n", sizeof(buf));
935 xsprintf(buf, "%" PRIu64 "\n", val);
937 r = cg_set_attribute("memory", path, "memory.limit_in_bytes", buf);
939 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
940 "Failed to set memory.limit_in_bytes: %m");
944 if ((apply_mask & CGROUP_MASK_DEVICES) && !is_root) {
945 CGroupDeviceAllow *a;
947 /* Changing the devices list of a populated cgroup
948 * might result in EINVAL, hence ignore EINVAL
951 if (c->device_allow || c->device_policy != CGROUP_AUTO)
952 r = cg_set_attribute("devices", path, "devices.deny", "a");
954 r = cg_set_attribute("devices", path, "devices.allow", "a");
956 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
957 "Failed to reset devices.list: %m");
959 if (c->device_policy == CGROUP_CLOSED ||
960 (c->device_policy == CGROUP_AUTO && c->device_allow)) {
961 static const char auto_devices[] =
962 "/dev/null\0" "rwm\0"
963 "/dev/zero\0" "rwm\0"
964 "/dev/full\0" "rwm\0"
965 "/dev/random\0" "rwm\0"
966 "/dev/urandom\0" "rwm\0"
968 "/dev/pts/ptmx\0" "rw\0" /* /dev/pts/ptmx may not be duplicated, but accessed */
969 /* Allow /run/elogind/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
970 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
971 "-/run/systemd/inaccessible/chr\0" "rwm\0"
972 "-/run/systemd/inaccessible/blk\0" "rwm\0";
976 NULSTR_FOREACH_PAIR(x, y, auto_devices)
977 whitelist_device(path, x, y);
979 whitelist_major(path, "pts", 'c', "rw");
982 LIST_FOREACH(device_allow, a, c->device_allow) {
998 if (path_startswith(a->path, "/dev/"))
999 whitelist_device(path, a->path, acc);
1000 else if ((val = startswith(a->path, "block-")))
1001 whitelist_major(path, val, 'b', acc);
1002 else if ((val = startswith(a->path, "char-")))
1003 whitelist_major(path, val, 'c', acc);
1005 log_unit_debug(u, "Ignoring device %s while writing cgroup attribute.", a->path);
1009 if ((apply_mask & CGROUP_MASK_PIDS) && !is_root) {
1011 if (c->tasks_max != CGROUP_LIMIT_MAX) {
1012 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1014 sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
1015 r = cg_set_attribute("pids", path, "pids.max", buf);
1017 r = cg_set_attribute("pids", path, "pids.max", "max");
1020 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1021 "Failed to set pids.max: %m");
1025 cgroup_apply_firewall(u, c);
1028 CGroupMask cgroup_context_get_mask(CGroupContext *c) {
1029 CGroupMask mask = 0;
1031 /* Figure out which controllers we need */
1033 if (c->cpu_accounting ||
1034 cgroup_context_has_cpu_weight(c) ||
1035 cgroup_context_has_cpu_shares(c) ||
1036 c->cpu_quota_per_sec_usec != USEC_INFINITY)
1037 mask |= CGROUP_MASK_CPUACCT | CGROUP_MASK_CPU;
1039 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
1040 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
1042 if (c->memory_accounting ||
1043 c->memory_limit != CGROUP_LIMIT_MAX ||
1044 cgroup_context_has_unified_memory_config(c))
1045 mask |= CGROUP_MASK_MEMORY;
1047 if (c->device_allow ||
1048 c->device_policy != CGROUP_AUTO)
1049 mask |= CGROUP_MASK_DEVICES;
1051 if (c->tasks_accounting ||
1052 c->tasks_max != (uint64_t) -1)
1053 mask |= CGROUP_MASK_PIDS;
1058 CGroupMask unit_get_own_mask(Unit *u) {
1061 /* Returns the mask of controllers the unit needs for itself */
1063 c = unit_get_cgroup_context(u);
1067 /* If delegation is turned on, then turn on all cgroups,
1068 * unless we are on the legacy hierarchy and the process we
1069 * fork into it is known to drop privileges, and hence
1070 * shouldn't get access to the controllers.
1072 * Note that on the unified hierarchy it is safe to delegate
1073 * controllers to unprivileged services. */
1078 e = unit_get_exec_context(u);
1080 exec_context_maintains_privileges(e) ||
1081 cg_all_unified() > 0)
1082 return _CGROUP_MASK_ALL;
1085 return cgroup_context_get_mask(c);
1088 CGroupMask unit_get_members_mask(Unit *u) {
1091 /* Returns the mask of controllers all of the unit's children
1092 * require, merged */
1094 if (u->cgroup_members_mask_valid)
1095 return u->cgroup_members_mask;
1097 u->cgroup_members_mask = 0;
1099 if (u->type == UNIT_SLICE) {
1103 SET_FOREACH(member, u->dependencies[UNIT_BEFORE], i) {
1108 if (UNIT_DEREF(member->slice) != u)
1111 u->cgroup_members_mask |=
1112 unit_get_own_mask(member) |
1113 unit_get_members_mask(member);
1117 u->cgroup_members_mask_valid = true;
1118 return u->cgroup_members_mask;
1121 CGroupMask unit_get_siblings_mask(Unit *u) {
1124 /* Returns the mask of controllers all of the unit's siblings
1125 * require, i.e. the members mask of the unit's parent slice
1126 * if there is one. */
1128 if (UNIT_ISSET(u->slice))
1129 return unit_get_members_mask(UNIT_DEREF(u->slice));
1131 return unit_get_own_mask(u) | unit_get_members_mask(u);
1134 CGroupMask unit_get_subtree_mask(Unit *u) {
1136 /* Returns the mask of this subtree, meaning of the group
1137 * itself and its children. */
1139 return unit_get_own_mask(u) | unit_get_members_mask(u);
1142 CGroupMask unit_get_target_mask(Unit *u) {
1145 /* This returns the cgroup mask of all controllers to enable
1146 * for a specific cgroup, i.e. everything it needs itself,
1147 * plus all that its children need, plus all that its siblings
1148 * need. This is primarily useful on the legacy cgroup
1149 * hierarchy, where we need to duplicate each cgroup in each
1150 * hierarchy that shall be enabled for it. */
1152 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
1153 mask &= u->manager->cgroup_supported;
1158 CGroupMask unit_get_enable_mask(Unit *u) {
1161 /* This returns the cgroup mask of all controllers to enable
1162 * for the children of a specific cgroup. This is primarily
1163 * useful for the unified cgroup hierarchy, where each cgroup
1164 * controls which controllers are enabled for its children. */
1166 mask = unit_get_members_mask(u);
1167 mask &= u->manager->cgroup_supported;
1172 bool unit_get_needs_bpf(Unit *u) {
1177 /* We never attach BPF to slice units, as they are inner cgroup nodes and cgroup/BPF is not recursive at the
1179 if (u->type == UNIT_SLICE)
1182 c = unit_get_cgroup_context(u);
1186 if (c->ip_accounting ||
1187 c->ip_address_allow ||
1191 /* If any parent slice has an IP access list defined, it applies too */
1192 for (p = UNIT_DEREF(u->slice); p; p = UNIT_DEREF(p->slice)) {
1193 c = unit_get_cgroup_context(p);
1197 if (c->ip_address_allow ||
1205 /* Recurse from a unit up through its containing slices, propagating
1206 * mask bits upward. A unit is also member of itself. */
1207 void unit_update_cgroup_members_masks(Unit *u) {
1213 /* Calculate subtree mask */
1214 m = unit_get_subtree_mask(u);
1216 /* See if anything changed from the previous invocation. If
1217 * not, we're done. */
1218 if (u->cgroup_subtree_mask_valid && m == u->cgroup_subtree_mask)
1222 u->cgroup_subtree_mask_valid &&
1223 ((m & ~u->cgroup_subtree_mask) != 0) &&
1224 ((~m & u->cgroup_subtree_mask) == 0);
1226 u->cgroup_subtree_mask = m;
1227 u->cgroup_subtree_mask_valid = true;
1229 if (UNIT_ISSET(u->slice)) {
1230 Unit *s = UNIT_DEREF(u->slice);
1233 /* There's more set now than before. We
1234 * propagate the new mask to the parent's mask
1235 * (not caring if it actually was valid or
1238 s->cgroup_members_mask |= m;
1241 /* There's less set now than before (or we
1242 * don't know), we need to recalculate
1243 * everything, so let's invalidate the
1244 * parent's members mask */
1246 s->cgroup_members_mask_valid = false;
1248 /* And now make sure that this change also hits our
1250 unit_update_cgroup_members_masks(s);
1254 static const char *migrate_callback(CGroupMask mask, void *userdata) {
1261 if (u->cgroup_path &&
1262 u->cgroup_realized &&
1263 (u->cgroup_realized_mask & mask) == mask)
1264 return u->cgroup_path;
1266 u = UNIT_DEREF(u->slice);
1272 char *unit_default_cgroup_path(Unit *u) {
1273 _cleanup_free_ char *escaped = NULL, *slice = NULL;
1278 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1279 return strdup(u->manager->cgroup_root);
1281 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1282 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1287 escaped = cg_escape(u->id);
1292 return strjoin(u->manager->cgroup_root, "/", slice, "/",
1295 return strjoin(u->manager->cgroup_root, "/", escaped);
1298 int unit_set_cgroup_path(Unit *u, const char *path) {
1299 _cleanup_free_ char *p = NULL;
1311 if (streq_ptr(u->cgroup_path, p))
1315 r = hashmap_put(u->manager->cgroup_unit, p, u);
1320 unit_release_cgroup(u);
1328 int unit_watch_cgroup(Unit *u) {
1329 _cleanup_free_ char *events = NULL;
1334 if (!u->cgroup_path)
1337 if (u->cgroup_inotify_wd >= 0)
1340 /* Only applies to the unified hierarchy */
1341 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1343 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1347 /* Don't watch the root slice, it's pointless. */
1348 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1351 r = hashmap_ensure_allocated(&u->manager->cgroup_inotify_wd_unit, &trivial_hash_ops);
1355 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1359 u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1360 if (u->cgroup_inotify_wd < 0) {
1362 if (errno == ENOENT) /* If the directory is already
1363 * gone we don't need to track
1364 * it, so this is not an error */
1367 return log_unit_error_errno(u, errno, "Failed to add inotify watch descriptor for control group %s: %m", u->cgroup_path);
1370 r = hashmap_put(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd), u);
1372 return log_unit_error_errno(u, r, "Failed to add inotify watch descriptor to hash map: %m");
1377 static int unit_create_cgroup(
1379 CGroupMask target_mask,
1380 CGroupMask enable_mask,
1388 c = unit_get_cgroup_context(u);
1392 if (!u->cgroup_path) {
1393 _cleanup_free_ char *path = NULL;
1395 path = unit_default_cgroup_path(u);
1399 r = unit_set_cgroup_path(u, path);
1401 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1403 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1406 /* First, create our own group */
1407 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1409 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1411 /* Start watching it */
1412 (void) unit_watch_cgroup(u);
1414 /* Enable all controllers we need */
1415 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path);
1417 log_unit_warning_errno(u, r, "Failed to enable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
1419 /* Keep track that this is now realized */
1420 u->cgroup_realized = true;
1421 u->cgroup_realized_mask = target_mask;
1422 u->cgroup_enabled_mask = enable_mask;
1423 u->cgroup_bpf_state = needs_bpf ? UNIT_CGROUP_BPF_ON : UNIT_CGROUP_BPF_OFF;
1425 if (u->type != UNIT_SLICE && !c->delegate) {
1427 /* Then, possibly move things over, but not if
1428 * subgroups may contain processes, which is the case
1429 * for slice and delegation units. */
1430 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1432 log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
1438 int unit_attach_pids_to_cgroup(Unit *u) {
1442 r = unit_realize_cgroup(u);
1446 r = cg_attach_many_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->pids, migrate_callback, u);
1453 static void cgroup_xattr_apply(Unit *u) {
1454 char ids[SD_ID128_STRING_MAX];
1459 if (!MANAGER_IS_SYSTEM(u->manager))
1462 if (sd_id128_is_null(u->invocation_id))
1465 r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
1466 "trusted.invocation_id",
1467 sd_id128_to_string(u->invocation_id, ids), 32,
1470 log_unit_warning_errno(u, r, "Failed to set invocation ID on control group %s, ignoring: %m", u->cgroup_path);
1473 static bool unit_has_mask_realized(
1475 CGroupMask target_mask,
1476 CGroupMask enable_mask,
1481 return u->cgroup_realized &&
1482 u->cgroup_realized_mask == target_mask &&
1483 u->cgroup_enabled_mask == enable_mask &&
1484 ((needs_bpf && u->cgroup_bpf_state == UNIT_CGROUP_BPF_ON) ||
1485 (!needs_bpf && u->cgroup_bpf_state == UNIT_CGROUP_BPF_OFF));
1488 /* Check if necessary controllers and attributes for a unit are in place.
1490 * If so, do nothing.
1491 * If not, create paths, move processes over, and set attributes.
1493 * Returns 0 on success and < 0 on failure. */
1494 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
1495 CGroupMask target_mask, enable_mask;
1496 bool needs_bpf, apply_bpf;
1501 if (u->in_cgroup_realize_queue) {
1502 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
1503 u->in_cgroup_realize_queue = false;
1506 target_mask = unit_get_target_mask(u);
1507 enable_mask = unit_get_enable_mask(u);
1508 needs_bpf = unit_get_needs_bpf(u);
1510 if (unit_has_mask_realized(u, target_mask, enable_mask, needs_bpf))
1513 /* Make sure we apply the BPF filters either when one is configured, or if none is configured but previously
1514 * the state was anything but off. This way, if a unit with a BPF filter applied is reconfigured to lose it
1515 * this will trickle down properly to cgroupfs. */
1516 apply_bpf = needs_bpf || u->cgroup_bpf_state != UNIT_CGROUP_BPF_OFF;
1518 /* First, realize parents */
1519 if (UNIT_ISSET(u->slice)) {
1520 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
1525 /* And then do the real work */
1526 r = unit_create_cgroup(u, target_mask, enable_mask, needs_bpf);
1530 /* Finally, apply the necessary attributes. */
1531 cgroup_context_apply(u, target_mask, apply_bpf, state);
1532 cgroup_xattr_apply(u);
1537 static void unit_add_to_cgroup_realize_queue(Unit *u) {
1540 if (u->in_cgroup_realize_queue)
1543 LIST_PREPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
1544 u->in_cgroup_realize_queue = true;
1547 unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
1555 state = manager_state(m);
1557 while ((i = m->cgroup_realize_queue)) {
1558 assert(i->in_cgroup_realize_queue);
1560 r = unit_realize_cgroup_now(i, state);
1562 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
1570 static void unit_add_siblings_to_cgroup_realize_queue(Unit *u) {
1573 /* This adds the siblings of the specified unit and the
1574 * siblings of all parent units to the cgroup queue. (But
1575 * neither the specified unit itself nor the parents.) */
1577 while ((slice = UNIT_DEREF(u->slice))) {
1581 SET_FOREACH(m, slice->dependencies[UNIT_BEFORE], i) {
1585 /* Skip units that have a dependency on the slice
1586 * but aren't actually in it. */
1587 if (UNIT_DEREF(m->slice) != slice)
1590 /* No point in doing cgroup application for units
1591 * without active processes. */
1592 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
1595 /* If the unit doesn't need any new controllers
1596 * and has current ones realized, it doesn't need
1598 if (unit_has_mask_realized(m,
1599 unit_get_target_mask(m),
1600 unit_get_enable_mask(m),
1601 unit_get_needs_bpf(m)))
1604 unit_add_to_cgroup_realize_queue(m);
1611 int unit_realize_cgroup(Unit *u) {
1614 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1617 /* So, here's the deal: when realizing the cgroups for this
1618 * unit, we need to first create all parents, but there's more
1619 * actually: for the weight-based controllers we also need to
1620 * make sure that all our siblings (i.e. units that are in the
1621 * same slice as we are) have cgroups, too. Otherwise, things
1622 * would become very uneven as each of their processes would
1623 * get as much resources as all our group together. This call
1624 * will synchronously create the parent cgroups, but will
1625 * defer work on the siblings to the next event loop
1628 /* Add all sibling slices to the cgroup queue. */
1629 unit_add_siblings_to_cgroup_realize_queue(u);
1631 /* And realize this one now (and apply the values) */
1632 return unit_realize_cgroup_now(u, manager_state(u->manager));
1635 void unit_release_cgroup(Unit *u) {
1638 /* Forgets all cgroup details for this cgroup */
1640 if (u->cgroup_path) {
1641 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1642 u->cgroup_path = mfree(u->cgroup_path);
1645 if (u->cgroup_inotify_wd >= 0) {
1646 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1647 log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1649 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1650 u->cgroup_inotify_wd = -1;
1654 void unit_prune_cgroup(Unit *u) {
1660 /* Removes the cgroup, if empty and possible, and stops watching it. */
1662 if (!u->cgroup_path)
1665 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
1667 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1669 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
1671 log_unit_debug_errno(u, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
1678 unit_release_cgroup(u);
1680 u->cgroup_realized = false;
1681 u->cgroup_realized_mask = 0;
1682 u->cgroup_enabled_mask = 0;
1685 int unit_search_main_pid(Unit *u, pid_t *ret) {
1686 _cleanup_fclose_ FILE *f = NULL;
1687 pid_t pid = 0, npid, mypid;
1693 if (!u->cgroup_path)
1696 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1700 mypid = getpid_cached();
1701 while (cg_read_pid(f, &npid) > 0) {
1707 /* Ignore processes that aren't our kids */
1708 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
1712 /* Dang, there's more than one daemonized PID
1713 in this group, so we don't know what process
1714 is the main process. */
1725 static int unit_watch_pids_in_path(Unit *u, const char *path) {
1726 _cleanup_closedir_ DIR *d = NULL;
1727 _cleanup_fclose_ FILE *f = NULL;
1733 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1739 while ((r = cg_read_pid(f, &pid)) > 0) {
1740 r = unit_watch_pid(u, pid);
1741 if (r < 0 && ret >= 0)
1745 if (r < 0 && ret >= 0)
1749 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1756 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1757 _cleanup_free_ char *p = NULL;
1759 p = strjoin(path, "/", fn);
1765 r = unit_watch_pids_in_path(u, p);
1766 if (r < 0 && ret >= 0)
1770 if (r < 0 && ret >= 0)
1777 int unit_watch_all_pids(Unit *u) {
1782 /* Adds all PIDs from our cgroup to the set of PIDs we
1783 * watch. This is a fallback logic for cases where we do not
1784 * get reliable cgroup empty notifications: we try to use
1785 * SIGCHLD as replacement. */
1787 if (!u->cgroup_path)
1790 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1793 if (r > 0) /* On unified we can use proper notifications */
1796 return unit_watch_pids_in_path(u, u->cgroup_path);
1799 static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
1800 Manager *m = userdata;
1807 u = m->cgroup_empty_queue;
1811 assert(u->in_cgroup_empty_queue);
1812 u->in_cgroup_empty_queue = false;
1813 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
1815 if (m->cgroup_empty_queue) {
1816 /* More stuff queued, let's make sure we remain enabled */
1817 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
1819 log_debug_errno(r, "Failed to reenable cgroup empty event source: %m");
1822 unit_add_to_gc_queue(u);
1824 if (UNIT_VTABLE(u)->notify_cgroup_empty)
1825 UNIT_VTABLE(u)->notify_cgroup_empty(u);
1830 void unit_add_to_cgroup_empty_queue(Unit *u) {
1835 /* Note that there are four different ways how cgroup empty events reach us:
1837 * 1. On the unified hierarchy we get an inotify event on the cgroup
1839 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
1841 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
1843 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
1844 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
1846 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
1847 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
1848 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
1849 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
1850 * case for scope units). */
1852 if (u->in_cgroup_empty_queue)
1855 /* Let's verify that the cgroup is really empty */
1856 if (!u->cgroup_path)
1858 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
1860 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", u->cgroup_path);
1866 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
1867 u->in_cgroup_empty_queue = true;
1869 /* Trigger the defer event */
1870 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
1872 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
1875 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1876 Manager *m = userdata;
1883 union inotify_event_buffer buffer;
1884 struct inotify_event *e;
1887 l = read(fd, &buffer, sizeof(buffer));
1889 if (IN_SET(errno, EINTR, EAGAIN))
1892 return log_error_errno(errno, "Failed to read control group inotify events: %m");
1895 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1899 /* Queue overflow has no watch descriptor */
1902 if (e->mask & IN_IGNORED)
1903 /* The watch was just removed */
1906 u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
1907 if (!u) /* Not that inotify might deliver
1908 * events for a watch even after it
1909 * was removed, because it was queued
1910 * before the removal. Let's ignore
1911 * this here safely. */
1914 unit_add_to_cgroup_empty_queue(u);
1920 int manager_setup_cgroup(Manager *m) {
1921 _cleanup_free_ char *path = NULL;
1922 const char *scope_path;
1929 /* 1. Determine hierarchy */
1930 m->cgroup_root = mfree(m->cgroup_root);
1931 #if 0 /// elogind is not init and must therefore search for PID 1 instead of self.
1932 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
1934 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &m->cgroup_root);
1937 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
1939 #if 0 /// elogind does not support systemd scopes and slices
1940 /* Chop off the init scope, if we are already located in it */
1941 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1943 /* LEGACY: Also chop off the system slice if we are in
1944 * it. This is to support live upgrades from older systemd
1945 * versions where PID 1 was moved there. Also see
1946 * cg_get_root_path(). */
1947 if (!e && MANAGER_IS_SYSTEM(m)) {
1948 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
1950 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
1956 /* And make sure to store away the root value without trailing
1957 * slash, even for the root dir, so that we can easily prepend
1959 while ((e = endswith(m->cgroup_root, "/")))
1961 log_debug_elogind("Cgroup Controller \"%s\" -> root \"%s\"",
1962 SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root);
1965 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
1967 return log_error_errno(r, "Cannot find cgroup mount point: %m");
1969 r = cg_unified_flush();
1971 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
1973 all_unified = cg_all_unified();
1975 return log_error_errno(r, "Couldn't determine whether we are in all unified mode: %m");
1977 log_debug("Unified cgroup hierarchy is located at %s.", path);
1979 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1981 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
1983 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
1985 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
1988 #if 0 /// elogind is not init, and does not install the agent here.
1989 /* 3. Allocate cgroup empty defer event source */
1990 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
1991 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
1993 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
1995 r = sd_event_source_set_priority(m->cgroup_empty_event_source, SD_EVENT_PRIORITY_NORMAL-5);
1997 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
1999 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
2001 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
2003 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
2005 /* 4. Install notifier inotify object, or agent */
2006 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
2008 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2010 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2011 safe_close(m->cgroup_inotify_fd);
2013 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
2014 if (m->cgroup_inotify_fd < 0)
2015 return log_error_errno(errno, "Failed to create control group inotify object: %m");
2017 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
2019 return log_error_errno(r, "Failed to watch control group inotify object: %m");
2021 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
2022 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2023 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-4);
2025 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
2027 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
2029 } else if (MANAGER_IS_SYSTEM(m) && m->test_run_flags == 0) {
2031 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2032 * since it does not generate events when control groups with children run empty. */
2034 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
2036 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
2038 log_debug("Installed release agent.");
2040 log_debug("Release agent already installed.");
2043 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2044 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2045 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2048 * This method is in core, and normally called by systemd
2049 * being init. As elogind is never init, we can not install
2050 * our agent here. We do so when mounting our cgroup file
2051 * system, so only if elogind is its own tiny controller.
2052 * Further, elogind is not meant to run in systemd init scope. */
2053 if (MANAGER_IS_SYSTEM(m))
2054 // we are our own cgroup controller
2055 scope_path = strjoina("");
2056 else if (streq(m->cgroup_root, "/elogind"))
2057 // root already is our cgroup
2058 scope_path = strjoina(m->cgroup_root);
2060 // we have to create our own group
2061 scope_path = strjoina(m->cgroup_root, "/elogind");
2062 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2065 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
2066 log_debug_elogind("Created control group \"%s\"", scope_path);
2068 #if 0 /// elogind is not a "sub-controller" like systemd, so migration is not needed.
2069 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2070 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2072 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
2075 /* 6. And pin it, so that it cannot be unmounted */
2076 safe_close(m->pin_cgroupfs_fd);
2077 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
2078 if (m->pin_cgroupfs_fd < 0)
2079 return log_error_errno(errno, "Failed to open pin file: %m");
2081 /* 7. Always enable hierarchical support if it exists... */
2082 if (!all_unified && m->test_run_flags == 0)
2083 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
2085 /* 8. Figure out which controllers are supported, and log about it */
2086 r = cg_mask_supported(&m->cgroup_supported);
2088 return log_error_errno(r, "Failed to determine supported controllers: %m");
2089 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
2090 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
2095 void manager_shutdown_cgroup(Manager *m, bool delete) {
2098 /* We can't really delete the group, since we are in it. But
2100 if (delete && m->cgroup_root)
2101 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
2103 #if 0 /// elogind does not support the unified hierarchy, yet.
2104 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2106 m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
2108 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2109 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
2112 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
2114 m->cgroup_root = mfree(m->cgroup_root);
2117 #if 0 /// UNNEEDED by elogind
2118 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
2125 u = hashmap_get(m->cgroup_unit, cgroup);
2129 p = strdupa(cgroup);
2133 e = strrchr(p, '/');
2135 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
2139 u = hashmap_get(m->cgroup_unit, p);
2145 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
2146 _cleanup_free_ char *cgroup = NULL;
2154 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
2158 return manager_get_unit_by_cgroup(m, cgroup);
2161 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
2170 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
2172 u = hashmap_get(m->watch_pids1, PID_TO_PTR(pid));
2176 u = hashmap_get(m->watch_pids2, PID_TO_PTR(pid));
2180 return manager_get_unit_by_pid_cgroup(m, pid);
2184 #if 0 /// elogind must substitute this with its own variant
2185 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
2191 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
2192 * or from the --system instance */
2194 log_debug("Got cgroup empty notification for: %s", cgroup);
2196 u = manager_get_unit_by_cgroup(m, cgroup);
2200 unit_add_to_cgroup_empty_queue(u);
2204 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
2210 log_debug("Got cgroup empty notification for: %s", cgroup);
2212 s = hashmap_get(m->sessions, cgroup);
2215 session_finalize(s);
2218 log_warning("Session not found: %s", cgroup);
2223 #if 0 /// UNNEEDED by elogind
2224 int unit_get_memory_current(Unit *u, uint64_t *ret) {
2225 _cleanup_free_ char *v = NULL;
2231 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
2234 if (!u->cgroup_path)
2237 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
2240 r = cg_all_unified();
2244 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
2246 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
2252 return safe_atou64(v, ret);
2255 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
2256 _cleanup_free_ char *v = NULL;
2262 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
2265 if (!u->cgroup_path)
2268 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
2271 r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
2277 return safe_atou64(v, ret);
2280 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
2281 _cleanup_free_ char *v = NULL;
2288 if (!u->cgroup_path)
2291 r = cg_all_unified();
2295 const char *keys[] = { "usage_usec", NULL };
2296 _cleanup_free_ char *val = NULL;
2299 if ((u->cgroup_realized_mask & CGROUP_MASK_CPU) == 0)
2302 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", keys, &val);
2306 r = safe_atou64(val, &us);
2310 ns = us * NSEC_PER_USEC;
2312 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
2315 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
2321 r = safe_atou64(v, &ns);
2330 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
2336 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2337 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2338 * call this function with a NULL return value. */
2340 if (!UNIT_CGROUP_BOOL(u, cpu_accounting))
2343 r = unit_get_cpu_usage_raw(u, &ns);
2344 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
2345 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2349 *ret = u->cpu_usage_last;
2355 if (ns > u->cpu_usage_base)
2356 ns -= u->cpu_usage_base;
2360 u->cpu_usage_last = ns;
2367 int unit_get_ip_accounting(
2369 CGroupIPAccountingMetric metric,
2376 assert(metric >= 0);
2377 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
2380 /* IP accounting is currently not recursive, and hence we refuse to return any data for slice nodes. Slices are
2381 * inner cgroup nodes and hence have no processes directly attached, hence their counters would be zero
2382 * anyway. And if we block this now we can later open this up, if the kernel learns recursive BPF cgroup
2384 if (u->type == UNIT_SLICE)
2387 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
2390 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
2391 u->ip_accounting_ingress_map_fd :
2392 u->ip_accounting_egress_map_fd;
2397 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
2398 r = bpf_firewall_read_accounting(fd, &value, NULL);
2400 r = bpf_firewall_read_accounting(fd, NULL, &value);
2404 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
2405 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
2406 * ip_accounting_extra[] field, and add them in here transparently. */
2408 *ret = value + u->ip_accounting_extra[metric];
2413 int unit_reset_cpu_accounting(Unit *u) {
2419 u->cpu_usage_last = NSEC_INFINITY;
2421 r = unit_get_cpu_usage_raw(u, &ns);
2423 u->cpu_usage_base = 0;
2427 u->cpu_usage_base = ns;
2431 int unit_reset_ip_accounting(Unit *u) {
2436 if (u->ip_accounting_ingress_map_fd >= 0)
2437 r = bpf_firewall_reset_accounting(u->ip_accounting_ingress_map_fd);
2439 if (u->ip_accounting_egress_map_fd >= 0)
2440 q = bpf_firewall_reset_accounting(u->ip_accounting_egress_map_fd);
2442 zero(u->ip_accounting_extra);
2444 return r < 0 ? r : q;
2447 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
2450 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2456 /* always invalidate compat pairs together */
2457 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
2458 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
2460 if (m & (CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT))
2461 m |= CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT;
2463 if ((u->cgroup_realized_mask & m) == 0)
2466 u->cgroup_realized_mask &= ~m;
2467 unit_add_to_cgroup_realize_queue(u);
2470 void unit_invalidate_cgroup_bpf(Unit *u) {
2473 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2476 if (u->cgroup_bpf_state == UNIT_CGROUP_BPF_INVALIDATED)
2479 u->cgroup_bpf_state = UNIT_CGROUP_BPF_INVALIDATED;
2480 unit_add_to_cgroup_realize_queue(u);
2482 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
2483 * list of our children includes our own. */
2484 if (u->type == UNIT_SLICE) {
2488 SET_FOREACH(member, u->dependencies[UNIT_BEFORE], i) {
2492 if (UNIT_DEREF(member->slice) != u)
2495 unit_invalidate_cgroup_bpf(member);
2500 void manager_invalidate_startup_units(Manager *m) {
2506 SET_FOREACH(u, m->startup_units, i)
2507 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
2510 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
2511 [CGROUP_AUTO] = "auto",
2512 [CGROUP_CLOSED] = "closed",
2513 [CGROUP_STRICT] = "strict",
2516 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);