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 "cgroup-util.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "process-util.h"
32 //#include "special.h"
33 #include "string-table.h"
34 #include "string-util.h"
35 #include "stdio-util.h"
37 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
39 #if 0 /// UNNEEDED by elogind
40 static void cgroup_compat_warn(void) {
41 static bool cgroup_compat_warned = false;
43 if (cgroup_compat_warned)
46 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. See cgroup-compat debug messages for details.");
47 cgroup_compat_warned = true;
50 #define log_cgroup_compat(unit, fmt, ...) do { \
51 cgroup_compat_warn(); \
52 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
55 void cgroup_context_init(CGroupContext *c) {
58 /* Initialize everything to the kernel defaults, assuming the
59 * structure is preinitialized to 0 */
61 c->cpu_weight = CGROUP_WEIGHT_INVALID;
62 c->startup_cpu_weight = CGROUP_WEIGHT_INVALID;
63 c->cpu_quota_per_sec_usec = USEC_INFINITY;
65 c->cpu_shares = CGROUP_CPU_SHARES_INVALID;
66 c->startup_cpu_shares = CGROUP_CPU_SHARES_INVALID;
68 c->memory_high = CGROUP_LIMIT_MAX;
69 c->memory_max = CGROUP_LIMIT_MAX;
70 c->memory_swap_max = CGROUP_LIMIT_MAX;
72 c->memory_limit = CGROUP_LIMIT_MAX;
74 c->io_weight = CGROUP_WEIGHT_INVALID;
75 c->startup_io_weight = CGROUP_WEIGHT_INVALID;
77 c->blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
78 c->startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
80 c->tasks_max = (uint64_t) -1;
83 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
87 LIST_REMOVE(device_allow, c->device_allow, a);
92 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
96 LIST_REMOVE(device_weights, c->io_device_weights, w);
101 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
105 LIST_REMOVE(device_limits, c->io_device_limits, l);
110 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
114 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
119 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
123 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
128 void cgroup_context_done(CGroupContext *c) {
131 while (c->io_device_weights)
132 cgroup_context_free_io_device_weight(c, c->io_device_weights);
134 while (c->io_device_limits)
135 cgroup_context_free_io_device_limit(c, c->io_device_limits);
137 while (c->blockio_device_weights)
138 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
140 while (c->blockio_device_bandwidths)
141 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
143 while (c->device_allow)
144 cgroup_context_free_device_allow(c, c->device_allow);
147 void cgroup_context_dump(CGroupContext *c, FILE* f, const char *prefix) {
148 CGroupIODeviceLimit *il;
149 CGroupIODeviceWeight *iw;
150 CGroupBlockIODeviceBandwidth *b;
151 CGroupBlockIODeviceWeight *w;
152 CGroupDeviceAllow *a;
153 char u[FORMAT_TIMESPAN_MAX];
158 prefix = strempty(prefix);
161 "%sCPUAccounting=%s\n"
162 "%sIOAccounting=%s\n"
163 "%sBlockIOAccounting=%s\n"
164 "%sMemoryAccounting=%s\n"
165 "%sTasksAccounting=%s\n"
166 "%sCPUWeight=%" PRIu64 "\n"
167 "%sStartupCPUWeight=%" PRIu64 "\n"
168 "%sCPUShares=%" PRIu64 "\n"
169 "%sStartupCPUShares=%" PRIu64 "\n"
170 "%sCPUQuotaPerSecSec=%s\n"
171 "%sIOWeight=%" PRIu64 "\n"
172 "%sStartupIOWeight=%" PRIu64 "\n"
173 "%sBlockIOWeight=%" PRIu64 "\n"
174 "%sStartupBlockIOWeight=%" PRIu64 "\n"
175 "%sMemoryLow=%" PRIu64 "\n"
176 "%sMemoryHigh=%" PRIu64 "\n"
177 "%sMemoryMax=%" PRIu64 "\n"
178 "%sMemorySwapMax=%" PRIu64 "\n"
179 "%sMemoryLimit=%" PRIu64 "\n"
180 "%sTasksMax=%" PRIu64 "\n"
181 "%sDevicePolicy=%s\n"
183 prefix, yes_no(c->cpu_accounting),
184 prefix, yes_no(c->io_accounting),
185 prefix, yes_no(c->blockio_accounting),
186 prefix, yes_no(c->memory_accounting),
187 prefix, yes_no(c->tasks_accounting),
188 prefix, c->cpu_weight,
189 prefix, c->startup_cpu_weight,
190 prefix, c->cpu_shares,
191 prefix, c->startup_cpu_shares,
192 prefix, format_timespan(u, sizeof(u), c->cpu_quota_per_sec_usec, 1),
193 prefix, c->io_weight,
194 prefix, c->startup_io_weight,
195 prefix, c->blockio_weight,
196 prefix, c->startup_blockio_weight,
197 prefix, c->memory_low,
198 prefix, c->memory_high,
199 prefix, c->memory_max,
200 prefix, c->memory_swap_max,
201 prefix, c->memory_limit,
202 prefix, c->tasks_max,
203 prefix, cgroup_device_policy_to_string(c->device_policy),
204 prefix, yes_no(c->delegate));
206 LIST_FOREACH(device_allow, a, c->device_allow)
208 "%sDeviceAllow=%s %s%s%s\n",
211 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
213 LIST_FOREACH(device_weights, iw, c->io_device_weights)
215 "%sIODeviceWeight=%s %" PRIu64,
220 LIST_FOREACH(device_limits, il, c->io_device_limits) {
221 char buf[FORMAT_BYTES_MAX];
222 CGroupIOLimitType type;
224 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
225 if (il->limits[type] != cgroup_io_limit_defaults[type])
229 cgroup_io_limit_type_to_string(type),
231 format_bytes(buf, sizeof(buf), il->limits[type]));
234 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
236 "%sBlockIODeviceWeight=%s %" PRIu64,
241 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
242 char buf[FORMAT_BYTES_MAX];
244 if (b->rbps != CGROUP_LIMIT_MAX)
246 "%sBlockIOReadBandwidth=%s %s\n",
249 format_bytes(buf, sizeof(buf), b->rbps));
250 if (b->wbps != CGROUP_LIMIT_MAX)
252 "%sBlockIOWriteBandwidth=%s %s\n",
255 format_bytes(buf, sizeof(buf), b->wbps));
259 static int lookup_block_device(const char *p, dev_t *dev) {
268 return log_warning_errno(errno, "Couldn't stat device %s: %m", p);
270 if (S_ISBLK(st.st_mode))
272 else if (major(st.st_dev) != 0) {
273 /* If this is not a device node then find the block
274 * device this file is stored on */
277 /* If this is a partition, try to get the originating
279 block_get_whole_disk(*dev, dev);
281 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p);
288 static int whitelist_device(const char *path, const char *node, const char *acc) {
289 char buf[2+DECIMAL_STR_MAX(dev_t)*2+2+4];
291 bool ignore_notfound;
297 if (node[0] == '-') {
298 /* Non-existent paths starting with "-" must be silently ignored */
300 ignore_notfound = true;
302 ignore_notfound = false;
304 if (stat(node, &st) < 0) {
305 if (errno == ENOENT && ignore_notfound)
308 return log_warning_errno(errno, "Couldn't stat device %s: %m", node);
311 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
312 log_warning("%s is not a device.", node);
318 S_ISCHR(st.st_mode) ? 'c' : 'b',
319 major(st.st_rdev), minor(st.st_rdev),
322 r = cg_set_attribute("devices", path, "devices.allow", buf);
324 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
325 "Failed to set devices.allow on %s: %m", path);
330 static int whitelist_major(const char *path, const char *name, char type, const char *acc) {
331 _cleanup_fclose_ FILE *f = NULL;
338 assert(type == 'b' || type == 'c');
340 f = fopen("/proc/devices", "re");
342 return log_warning_errno(errno, "Cannot open /proc/devices to resolve %s (%c): %m", name, type);
344 FOREACH_LINE(line, f, goto fail) {
345 char buf[2+DECIMAL_STR_MAX(unsigned)+3+4], *p, *w;
350 if (type == 'c' && streq(line, "Character devices:")) {
355 if (type == 'b' && streq(line, "Block devices:")) {
370 w = strpbrk(p, WHITESPACE);
375 r = safe_atou(p, &maj);
382 w += strspn(w, WHITESPACE);
384 if (fnmatch(name, w, 0) != 0)
393 r = cg_set_attribute("devices", path, "devices.allow", buf);
395 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
396 "Failed to set devices.allow on %s: %m", path);
402 return log_warning_errno(errno, "Failed to read /proc/devices: %m");
405 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
406 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
407 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
410 static bool cgroup_context_has_cpu_shares(CGroupContext *c) {
411 return c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
412 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID;
415 static uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
416 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
417 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
418 return c->startup_cpu_weight;
419 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
420 return c->cpu_weight;
422 return CGROUP_WEIGHT_DEFAULT;
425 static uint64_t cgroup_context_cpu_shares(CGroupContext *c, ManagerState state) {
426 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
427 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID)
428 return c->startup_cpu_shares;
429 else if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID)
430 return c->cpu_shares;
432 return CGROUP_CPU_SHARES_DEFAULT;
435 static void cgroup_apply_unified_cpu_config(Unit *u, uint64_t weight, uint64_t quota) {
436 char buf[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t) + 1) * 2)];
439 xsprintf(buf, "%" PRIu64 "\n", weight);
440 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.weight", buf);
442 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
443 "Failed to set cpu.weight: %m");
445 if (quota != USEC_INFINITY)
446 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
447 quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC, CGROUP_CPU_QUOTA_PERIOD_USEC);
449 xsprintf(buf, "max " USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
451 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.max", buf);
454 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
455 "Failed to set cpu.max: %m");
458 static void cgroup_apply_legacy_cpu_config(Unit *u, uint64_t shares, uint64_t quota) {
459 char buf[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t)) + 1];
462 xsprintf(buf, "%" PRIu64 "\n", shares);
463 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.shares", buf);
465 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
466 "Failed to set cpu.shares: %m");
468 xsprintf(buf, USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
469 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_period_us", buf);
471 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
472 "Failed to set cpu.cfs_period_us: %m");
474 if (quota != USEC_INFINITY) {
475 xsprintf(buf, USEC_FMT "\n", quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC);
476 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", buf);
478 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", "-1");
480 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
481 "Failed to set cpu.cfs_quota_us: %m");
484 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares) {
485 return CLAMP(shares * CGROUP_WEIGHT_DEFAULT / CGROUP_CPU_SHARES_DEFAULT,
486 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
489 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight) {
490 return CLAMP(weight * CGROUP_CPU_SHARES_DEFAULT / CGROUP_WEIGHT_DEFAULT,
491 CGROUP_CPU_SHARES_MIN, CGROUP_CPU_SHARES_MAX);
494 static bool cgroup_context_has_io_config(CGroupContext *c) {
495 return c->io_accounting ||
496 c->io_weight != CGROUP_WEIGHT_INVALID ||
497 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
498 c->io_device_weights ||
502 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
503 return c->blockio_accounting ||
504 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
505 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
506 c->blockio_device_weights ||
507 c->blockio_device_bandwidths;
510 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
511 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
512 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
513 return c->startup_io_weight;
514 else if (c->io_weight != CGROUP_WEIGHT_INVALID)
517 return CGROUP_WEIGHT_DEFAULT;
520 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
521 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
522 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
523 return c->startup_blockio_weight;
524 else if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
525 return c->blockio_weight;
527 return CGROUP_BLKIO_WEIGHT_DEFAULT;
530 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
531 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
532 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
535 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
536 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
537 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
540 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
541 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
545 r = lookup_block_device(dev_path, &dev);
549 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), io_weight);
550 r = cg_set_attribute("io", u->cgroup_path, "io.weight", buf);
552 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
553 "Failed to set io.weight: %m");
556 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
557 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
561 r = lookup_block_device(dev_path, &dev);
565 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), blkio_weight);
566 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.weight_device", buf);
568 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
569 "Failed to set blkio.weight_device: %m");
572 static unsigned cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
573 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)];
574 char buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
575 CGroupIOLimitType type;
580 r = lookup_block_device(dev_path, &dev);
584 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++) {
585 if (limits[type] != cgroup_io_limit_defaults[type]) {
586 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
589 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
593 xsprintf(buf, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev), minor(dev),
594 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
595 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
596 r = cg_set_attribute("io", u->cgroup_path, "io.max", buf);
598 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
599 "Failed to set io.max: %m");
603 static unsigned cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
604 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
609 r = lookup_block_device(dev_path, &dev);
613 if (rbps != CGROUP_LIMIT_MAX)
615 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), rbps);
616 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.read_bps_device", buf);
618 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
619 "Failed to set blkio.throttle.read_bps_device: %m");
621 if (wbps != CGROUP_LIMIT_MAX)
623 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), wbps);
624 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.write_bps_device", buf);
626 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
627 "Failed to set blkio.throttle.write_bps_device: %m");
632 static bool cgroup_context_has_unified_memory_config(CGroupContext *c) {
633 return c->memory_low > 0 || c->memory_high != CGROUP_LIMIT_MAX || c->memory_max != CGROUP_LIMIT_MAX || c->memory_swap_max != CGROUP_LIMIT_MAX;
636 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
637 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
640 if (v != CGROUP_LIMIT_MAX)
641 xsprintf(buf, "%" PRIu64 "\n", v);
643 r = cg_set_attribute("memory", u->cgroup_path, file, buf);
645 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
646 "Failed to set %s: %m", file);
649 static void cgroup_context_apply(Unit *u, CGroupMask mask, ManagerState state) {
657 c = unit_get_cgroup_context(u);
658 path = u->cgroup_path;
666 /* Some cgroup attributes are not supported on the root cgroup,
667 * hence silently ignore */
668 is_root = isempty(path) || path_equal(path, "/");
670 /* Make sure we don't try to display messages with an empty path. */
673 /* We generally ignore errors caused by read-only mounted
674 * cgroup trees (assuming we are running in a container then),
675 * and missing cgroups, i.e. EROFS and ENOENT. */
677 if ((mask & CGROUP_MASK_CPU) && !is_root) {
678 bool has_weight = cgroup_context_has_cpu_weight(c);
679 bool has_shares = cgroup_context_has_cpu_shares(c);
681 if (cg_all_unified() > 0) {
685 weight = cgroup_context_cpu_weight(c, state);
686 else if (has_shares) {
687 uint64_t shares = cgroup_context_cpu_shares(c, state);
689 weight = cgroup_cpu_shares_to_weight(shares);
691 log_cgroup_compat(u, "Applying [Startup]CpuShares %" PRIu64 " as [Startup]CpuWeight %" PRIu64 " on %s",
692 shares, weight, path);
694 weight = CGROUP_WEIGHT_DEFAULT;
696 cgroup_apply_unified_cpu_config(u, weight, c->cpu_quota_per_sec_usec);
701 uint64_t weight = cgroup_context_cpu_weight(c, state);
703 shares = cgroup_cpu_weight_to_shares(weight);
705 log_cgroup_compat(u, "Applying [Startup]CpuWeight %" PRIu64 " as [Startup]CpuShares %" PRIu64 " on %s",
706 weight, shares, path);
707 } else if (has_shares)
708 shares = cgroup_context_cpu_shares(c, state);
710 shares = CGROUP_CPU_SHARES_DEFAULT;
712 cgroup_apply_legacy_cpu_config(u, shares, c->cpu_quota_per_sec_usec);
716 if (mask & CGROUP_MASK_IO) {
717 bool has_io = cgroup_context_has_io_config(c);
718 bool has_blockio = cgroup_context_has_blockio_config(c);
721 char buf[8+DECIMAL_STR_MAX(uint64_t)+1];
725 weight = cgroup_context_io_weight(c, state);
726 else if (has_blockio) {
727 uint64_t blkio_weight = cgroup_context_blkio_weight(c, state);
729 weight = cgroup_weight_blkio_to_io(blkio_weight);
731 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight %" PRIu64 " as [Startup]IOWeight %" PRIu64,
732 blkio_weight, weight);
734 weight = CGROUP_WEIGHT_DEFAULT;
736 xsprintf(buf, "default %" PRIu64 "\n", weight);
737 r = cg_set_attribute("io", path, "io.weight", buf);
739 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
740 "Failed to set io.weight: %m");
743 CGroupIODeviceWeight *w;
745 /* FIXME: no way to reset this list */
746 LIST_FOREACH(device_weights, w, c->io_device_weights)
747 cgroup_apply_io_device_weight(u, w->path, w->weight);
748 } else if (has_blockio) {
749 CGroupBlockIODeviceWeight *w;
751 /* FIXME: no way to reset this list */
752 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
753 weight = cgroup_weight_blkio_to_io(w->weight);
755 log_cgroup_compat(u, "Applying BlockIODeviceWeight %" PRIu64 " as IODeviceWeight %" PRIu64 " for %s",
756 w->weight, weight, w->path);
758 cgroup_apply_io_device_weight(u, w->path, weight);
763 /* Apply limits and free ones without config. */
765 CGroupIODeviceLimit *l, *next;
767 LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
768 if (!cgroup_apply_io_device_limit(u, l->path, l->limits))
769 cgroup_context_free_io_device_limit(c, l);
771 } else if (has_blockio) {
772 CGroupBlockIODeviceBandwidth *b, *next;
774 LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths) {
775 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
776 CGroupIOLimitType type;
778 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
779 limits[type] = cgroup_io_limit_defaults[type];
781 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
782 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
784 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax for %s",
785 b->rbps, b->wbps, b->path);
787 if (!cgroup_apply_io_device_limit(u, b->path, limits))
788 cgroup_context_free_blockio_device_bandwidth(c, b);
793 if (mask & CGROUP_MASK_BLKIO) {
794 bool has_io = cgroup_context_has_io_config(c);
795 bool has_blockio = cgroup_context_has_blockio_config(c);
798 char buf[DECIMAL_STR_MAX(uint64_t)+1];
802 uint64_t io_weight = cgroup_context_io_weight(c, state);
804 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
806 log_cgroup_compat(u, "Applying [Startup]IOWeight %" PRIu64 " as [Startup]BlockIOWeight %" PRIu64,
808 } else if (has_blockio)
809 weight = cgroup_context_blkio_weight(c, state);
811 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
813 xsprintf(buf, "%" PRIu64 "\n", weight);
814 r = cg_set_attribute("blkio", path, "blkio.weight", buf);
816 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
817 "Failed to set blkio.weight: %m");
820 CGroupIODeviceWeight *w;
822 /* FIXME: no way to reset this list */
823 LIST_FOREACH(device_weights, w, c->io_device_weights) {
824 weight = cgroup_weight_io_to_blkio(w->weight);
826 log_cgroup_compat(u, "Applying IODeviceWeight %" PRIu64 " as BlockIODeviceWeight %" PRIu64 " for %s",
827 w->weight, weight, w->path);
829 cgroup_apply_blkio_device_weight(u, w->path, weight);
831 } else if (has_blockio) {
832 CGroupBlockIODeviceWeight *w;
834 /* FIXME: no way to reset this list */
835 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
836 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
840 /* Apply limits and free ones without config. */
842 CGroupIODeviceLimit *l, *next;
844 LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
845 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax for %s",
846 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
848 if (!cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]))
849 cgroup_context_free_io_device_limit(c, l);
851 } else if (has_blockio) {
852 CGroupBlockIODeviceBandwidth *b, *next;
854 LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths)
855 if (!cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps))
856 cgroup_context_free_blockio_device_bandwidth(c, b);
860 if ((mask & CGROUP_MASK_MEMORY) && !is_root) {
861 if (cg_all_unified() > 0) {
862 uint64_t max, swap_max = CGROUP_LIMIT_MAX;
864 if (cgroup_context_has_unified_memory_config(c)) {
866 swap_max = c->memory_swap_max;
868 max = c->memory_limit;
870 if (max != CGROUP_LIMIT_MAX)
871 log_cgroup_compat(u, "Applying MemoryLimit %" PRIu64 " as MemoryMax", max);
874 cgroup_apply_unified_memory_limit(u, "memory.low", c->memory_low);
875 cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
876 cgroup_apply_unified_memory_limit(u, "memory.max", max);
877 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
879 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
882 if (cgroup_context_has_unified_memory_config(c)) {
884 log_cgroup_compat(u, "Applying MemoryMax %" PRIi64 " as MemoryLimit", val);
886 val = c->memory_limit;
888 if (val == CGROUP_LIMIT_MAX)
889 strncpy(buf, "-1\n", sizeof(buf));
891 xsprintf(buf, "%" PRIu64 "\n", val);
893 r = cg_set_attribute("memory", path, "memory.limit_in_bytes", buf);
895 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
896 "Failed to set memory.limit_in_bytes: %m");
900 if ((mask & CGROUP_MASK_DEVICES) && !is_root) {
901 CGroupDeviceAllow *a;
903 /* Changing the devices list of a populated cgroup
904 * might result in EINVAL, hence ignore EINVAL
907 if (c->device_allow || c->device_policy != CGROUP_AUTO)
908 r = cg_set_attribute("devices", path, "devices.deny", "a");
910 r = cg_set_attribute("devices", path, "devices.allow", "a");
912 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
913 "Failed to reset devices.list: %m");
915 if (c->device_policy == CGROUP_CLOSED ||
916 (c->device_policy == CGROUP_AUTO && c->device_allow)) {
917 static const char auto_devices[] =
918 "/dev/null\0" "rwm\0"
919 "/dev/zero\0" "rwm\0"
920 "/dev/full\0" "rwm\0"
921 "/dev/random\0" "rwm\0"
922 "/dev/urandom\0" "rwm\0"
924 "/dev/pts/ptmx\0" "rw\0" /* /dev/pts/ptmx may not be duplicated, but accessed */
925 /* Allow /run/elogind/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
926 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
927 "-/run/systemd/inaccessible/chr\0" "rwm\0"
928 "-/run/systemd/inaccessible/blk\0" "rwm\0";
932 NULSTR_FOREACH_PAIR(x, y, auto_devices)
933 whitelist_device(path, x, y);
935 whitelist_major(path, "pts", 'c', "rw");
936 whitelist_major(path, "kdbus", 'c', "rw");
937 whitelist_major(path, "kdbus/*", 'c', "rw");
940 LIST_FOREACH(device_allow, a, c->device_allow) {
956 if (startswith(a->path, "/dev/"))
957 whitelist_device(path, a->path, acc);
958 else if ((val = startswith(a->path, "block-")))
959 whitelist_major(path, val, 'b', acc);
960 else if ((val = startswith(a->path, "char-")))
961 whitelist_major(path, val, 'c', acc);
963 log_unit_debug(u, "Ignoring device %s while writing cgroup attribute.", a->path);
967 if ((mask & CGROUP_MASK_PIDS) && !is_root) {
969 if (c->tasks_max != CGROUP_LIMIT_MAX) {
970 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
972 sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
973 r = cg_set_attribute("pids", path, "pids.max", buf);
975 r = cg_set_attribute("pids", path, "pids.max", "max");
978 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
979 "Failed to set pids.max: %m");
983 CGroupMask cgroup_context_get_mask(CGroupContext *c) {
986 /* Figure out which controllers we need */
988 if (c->cpu_accounting ||
989 cgroup_context_has_cpu_weight(c) ||
990 cgroup_context_has_cpu_shares(c) ||
991 c->cpu_quota_per_sec_usec != USEC_INFINITY)
992 mask |= CGROUP_MASK_CPUACCT | CGROUP_MASK_CPU;
994 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
995 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
997 if (c->memory_accounting ||
998 c->memory_limit != CGROUP_LIMIT_MAX ||
999 cgroup_context_has_unified_memory_config(c))
1000 mask |= CGROUP_MASK_MEMORY;
1002 if (c->device_allow ||
1003 c->device_policy != CGROUP_AUTO)
1004 mask |= CGROUP_MASK_DEVICES;
1006 if (c->tasks_accounting ||
1007 c->tasks_max != (uint64_t) -1)
1008 mask |= CGROUP_MASK_PIDS;
1013 CGroupMask unit_get_own_mask(Unit *u) {
1016 /* Returns the mask of controllers the unit needs for itself */
1018 c = unit_get_cgroup_context(u);
1022 /* If delegation is turned on, then turn on all cgroups,
1023 * unless we are on the legacy hierarchy and the process we
1024 * fork into it is known to drop privileges, and hence
1025 * shouldn't get access to the controllers.
1027 * Note that on the unified hierarchy it is safe to delegate
1028 * controllers to unprivileged services. */
1033 e = unit_get_exec_context(u);
1035 exec_context_maintains_privileges(e) ||
1036 cg_all_unified() > 0)
1037 return _CGROUP_MASK_ALL;
1040 return cgroup_context_get_mask(c);
1043 CGroupMask unit_get_members_mask(Unit *u) {
1046 /* Returns the mask of controllers all of the unit's children
1047 * require, merged */
1049 if (u->cgroup_members_mask_valid)
1050 return u->cgroup_members_mask;
1052 u->cgroup_members_mask = 0;
1054 if (u->type == UNIT_SLICE) {
1058 SET_FOREACH(member, u->dependencies[UNIT_BEFORE], i) {
1063 if (UNIT_DEREF(member->slice) != u)
1066 u->cgroup_members_mask |=
1067 unit_get_own_mask(member) |
1068 unit_get_members_mask(member);
1072 u->cgroup_members_mask_valid = true;
1073 return u->cgroup_members_mask;
1076 CGroupMask unit_get_siblings_mask(Unit *u) {
1079 /* Returns the mask of controllers all of the unit's siblings
1080 * require, i.e. the members mask of the unit's parent slice
1081 * if there is one. */
1083 if (UNIT_ISSET(u->slice))
1084 return unit_get_members_mask(UNIT_DEREF(u->slice));
1086 return unit_get_own_mask(u) | unit_get_members_mask(u);
1089 CGroupMask unit_get_subtree_mask(Unit *u) {
1091 /* Returns the mask of this subtree, meaning of the group
1092 * itself and its children. */
1094 return unit_get_own_mask(u) | unit_get_members_mask(u);
1097 CGroupMask unit_get_target_mask(Unit *u) {
1100 /* This returns the cgroup mask of all controllers to enable
1101 * for a specific cgroup, i.e. everything it needs itself,
1102 * plus all that its children need, plus all that its siblings
1103 * need. This is primarily useful on the legacy cgroup
1104 * hierarchy, where we need to duplicate each cgroup in each
1105 * hierarchy that shall be enabled for it. */
1107 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
1108 mask &= u->manager->cgroup_supported;
1113 CGroupMask unit_get_enable_mask(Unit *u) {
1116 /* This returns the cgroup mask of all controllers to enable
1117 * for the children of a specific cgroup. This is primarily
1118 * useful for the unified cgroup hierarchy, where each cgroup
1119 * controls which controllers are enabled for its children. */
1121 mask = unit_get_members_mask(u);
1122 mask &= u->manager->cgroup_supported;
1127 /* Recurse from a unit up through its containing slices, propagating
1128 * mask bits upward. A unit is also member of itself. */
1129 void unit_update_cgroup_members_masks(Unit *u) {
1135 /* Calculate subtree mask */
1136 m = unit_get_subtree_mask(u);
1138 /* See if anything changed from the previous invocation. If
1139 * not, we're done. */
1140 if (u->cgroup_subtree_mask_valid && m == u->cgroup_subtree_mask)
1144 u->cgroup_subtree_mask_valid &&
1145 ((m & ~u->cgroup_subtree_mask) != 0) &&
1146 ((~m & u->cgroup_subtree_mask) == 0);
1148 u->cgroup_subtree_mask = m;
1149 u->cgroup_subtree_mask_valid = true;
1151 if (UNIT_ISSET(u->slice)) {
1152 Unit *s = UNIT_DEREF(u->slice);
1155 /* There's more set now than before. We
1156 * propagate the new mask to the parent's mask
1157 * (not caring if it actually was valid or
1160 s->cgroup_members_mask |= m;
1163 /* There's less set now than before (or we
1164 * don't know), we need to recalculate
1165 * everything, so let's invalidate the
1166 * parent's members mask */
1168 s->cgroup_members_mask_valid = false;
1170 /* And now make sure that this change also hits our
1172 unit_update_cgroup_members_masks(s);
1176 static const char *migrate_callback(CGroupMask mask, void *userdata) {
1183 if (u->cgroup_path &&
1184 u->cgroup_realized &&
1185 (u->cgroup_realized_mask & mask) == mask)
1186 return u->cgroup_path;
1188 u = UNIT_DEREF(u->slice);
1194 char *unit_default_cgroup_path(Unit *u) {
1195 _cleanup_free_ char *escaped = NULL, *slice = NULL;
1200 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1201 return strdup(u->manager->cgroup_root);
1203 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1204 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1209 escaped = cg_escape(u->id);
1214 return strjoin(u->manager->cgroup_root, "/", slice, "/",
1217 return strjoin(u->manager->cgroup_root, "/", escaped);
1220 int unit_set_cgroup_path(Unit *u, const char *path) {
1221 _cleanup_free_ char *p = NULL;
1233 if (streq_ptr(u->cgroup_path, p))
1237 r = hashmap_put(u->manager->cgroup_unit, p, u);
1242 unit_release_cgroup(u);
1250 int unit_watch_cgroup(Unit *u) {
1251 _cleanup_free_ char *events = NULL;
1256 if (!u->cgroup_path)
1259 if (u->cgroup_inotify_wd >= 0)
1262 /* Only applies to the unified hierarchy */
1263 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1265 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1269 /* Don't watch the root slice, it's pointless. */
1270 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1273 r = hashmap_ensure_allocated(&u->manager->cgroup_inotify_wd_unit, &trivial_hash_ops);
1277 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1281 u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1282 if (u->cgroup_inotify_wd < 0) {
1284 if (errno == ENOENT) /* If the directory is already
1285 * gone we don't need to track
1286 * it, so this is not an error */
1289 return log_unit_error_errno(u, errno, "Failed to add inotify watch descriptor for control group %s: %m", u->cgroup_path);
1292 r = hashmap_put(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd), u);
1294 return log_unit_error_errno(u, r, "Failed to add inotify watch descriptor to hash map: %m");
1299 static int unit_create_cgroup(
1301 CGroupMask target_mask,
1302 CGroupMask enable_mask) {
1309 c = unit_get_cgroup_context(u);
1313 if (!u->cgroup_path) {
1314 _cleanup_free_ char *path = NULL;
1316 path = unit_default_cgroup_path(u);
1320 r = unit_set_cgroup_path(u, path);
1322 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1324 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1327 /* First, create our own group */
1328 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1330 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1332 /* Start watching it */
1333 (void) unit_watch_cgroup(u);
1335 /* Enable all controllers we need */
1336 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path);
1338 log_unit_warning_errno(u, r, "Failed to enable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
1340 /* Keep track that this is now realized */
1341 u->cgroup_realized = true;
1342 u->cgroup_realized_mask = target_mask;
1343 u->cgroup_enabled_mask = enable_mask;
1345 if (u->type != UNIT_SLICE && !c->delegate) {
1347 /* Then, possibly move things over, but not if
1348 * subgroups may contain processes, which is the case
1349 * for slice and delegation units. */
1350 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1352 log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
1358 int unit_attach_pids_to_cgroup(Unit *u) {
1362 r = unit_realize_cgroup(u);
1366 r = cg_attach_many_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->pids, migrate_callback, u);
1373 static void cgroup_xattr_apply(Unit *u) {
1374 char ids[SD_ID128_STRING_MAX];
1379 if (!MANAGER_IS_SYSTEM(u->manager))
1382 if (sd_id128_is_null(u->invocation_id))
1385 r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
1386 "trusted.invocation_id",
1387 sd_id128_to_string(u->invocation_id, ids), 32,
1390 log_unit_warning_errno(u, r, "Failed to set invocation ID on control group %s, ignoring: %m", u->cgroup_path);
1393 static bool unit_has_mask_realized(Unit *u, CGroupMask target_mask, CGroupMask enable_mask) {
1396 return u->cgroup_realized && u->cgroup_realized_mask == target_mask && u->cgroup_enabled_mask == enable_mask;
1399 /* Check if necessary controllers and attributes for a unit are in place.
1401 * If so, do nothing.
1402 * If not, create paths, move processes over, and set attributes.
1404 * Returns 0 on success and < 0 on failure. */
1405 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
1406 CGroupMask target_mask, enable_mask;
1411 if (u->in_cgroup_queue) {
1412 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
1413 u->in_cgroup_queue = false;
1416 target_mask = unit_get_target_mask(u);
1417 enable_mask = unit_get_enable_mask(u);
1419 if (unit_has_mask_realized(u, target_mask, enable_mask))
1422 /* First, realize parents */
1423 if (UNIT_ISSET(u->slice)) {
1424 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
1429 /* And then do the real work */
1430 r = unit_create_cgroup(u, target_mask, enable_mask);
1434 /* Finally, apply the necessary attributes. */
1435 cgroup_context_apply(u, target_mask, state);
1436 cgroup_xattr_apply(u);
1441 static void unit_add_to_cgroup_queue(Unit *u) {
1443 if (u->in_cgroup_queue)
1446 LIST_PREPEND(cgroup_queue, u->manager->cgroup_queue, u);
1447 u->in_cgroup_queue = true;
1450 unsigned manager_dispatch_cgroup_queue(Manager *m) {
1456 state = manager_state(m);
1458 while ((i = m->cgroup_queue)) {
1459 assert(i->in_cgroup_queue);
1461 r = unit_realize_cgroup_now(i, state);
1463 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
1471 static void unit_queue_siblings(Unit *u) {
1474 /* This adds the siblings of the specified unit and the
1475 * siblings of all parent units to the cgroup queue. (But
1476 * neither the specified unit itself nor the parents.) */
1478 while ((slice = UNIT_DEREF(u->slice))) {
1482 SET_FOREACH(m, slice->dependencies[UNIT_BEFORE], i) {
1486 /* Skip units that have a dependency on the slice
1487 * but aren't actually in it. */
1488 if (UNIT_DEREF(m->slice) != slice)
1491 /* No point in doing cgroup application for units
1492 * without active processes. */
1493 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
1496 /* If the unit doesn't need any new controllers
1497 * and has current ones realized, it doesn't need
1499 if (unit_has_mask_realized(m, unit_get_target_mask(m), unit_get_enable_mask(m)))
1502 unit_add_to_cgroup_queue(m);
1509 int unit_realize_cgroup(Unit *u) {
1512 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1515 /* So, here's the deal: when realizing the cgroups for this
1516 * unit, we need to first create all parents, but there's more
1517 * actually: for the weight-based controllers we also need to
1518 * make sure that all our siblings (i.e. units that are in the
1519 * same slice as we are) have cgroups, too. Otherwise, things
1520 * would become very uneven as each of their processes would
1521 * get as much resources as all our group together. This call
1522 * will synchronously create the parent cgroups, but will
1523 * defer work on the siblings to the next event loop
1526 /* Add all sibling slices to the cgroup queue. */
1527 unit_queue_siblings(u);
1529 /* And realize this one now (and apply the values) */
1530 return unit_realize_cgroup_now(u, manager_state(u->manager));
1533 void unit_release_cgroup(Unit *u) {
1536 /* Forgets all cgroup details for this cgroup */
1538 if (u->cgroup_path) {
1539 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1540 u->cgroup_path = mfree(u->cgroup_path);
1543 if (u->cgroup_inotify_wd >= 0) {
1544 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1545 log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1547 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1548 u->cgroup_inotify_wd = -1;
1552 void unit_prune_cgroup(Unit *u) {
1558 /* Removes the cgroup, if empty and possible, and stops watching it. */
1560 if (!u->cgroup_path)
1563 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
1565 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1567 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
1569 log_unit_debug_errno(u, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
1576 unit_release_cgroup(u);
1578 u->cgroup_realized = false;
1579 u->cgroup_realized_mask = 0;
1580 u->cgroup_enabled_mask = 0;
1583 int unit_search_main_pid(Unit *u, pid_t *ret) {
1584 _cleanup_fclose_ FILE *f = NULL;
1585 pid_t pid = 0, npid, mypid;
1591 if (!u->cgroup_path)
1594 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1599 while (cg_read_pid(f, &npid) > 0) {
1605 /* Ignore processes that aren't our kids */
1606 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
1610 /* Dang, there's more than one daemonized PID
1611 in this group, so we don't know what process
1612 is the main process. */
1623 static int unit_watch_pids_in_path(Unit *u, const char *path) {
1624 _cleanup_closedir_ DIR *d = NULL;
1625 _cleanup_fclose_ FILE *f = NULL;
1631 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1637 while ((r = cg_read_pid(f, &pid)) > 0) {
1638 r = unit_watch_pid(u, pid);
1639 if (r < 0 && ret >= 0)
1643 if (r < 0 && ret >= 0)
1647 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1654 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1655 _cleanup_free_ char *p = NULL;
1657 p = strjoin(path, "/", fn);
1663 r = unit_watch_pids_in_path(u, p);
1664 if (r < 0 && ret >= 0)
1668 if (r < 0 && ret >= 0)
1675 int unit_watch_all_pids(Unit *u) {
1680 /* Adds all PIDs from our cgroup to the set of PIDs we
1681 * watch. This is a fallback logic for cases where we do not
1682 * get reliable cgroup empty notifications: we try to use
1683 * SIGCHLD as replacement. */
1685 if (!u->cgroup_path)
1688 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1691 if (r > 0) /* On unified we can use proper notifications */
1694 return unit_watch_pids_in_path(u, u->cgroup_path);
1697 int unit_notify_cgroup_empty(Unit *u) {
1702 if (!u->cgroup_path)
1705 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
1709 unit_add_to_gc_queue(u);
1711 if (UNIT_VTABLE(u)->notify_cgroup_empty)
1712 UNIT_VTABLE(u)->notify_cgroup_empty(u);
1717 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1718 Manager *m = userdata;
1725 union inotify_event_buffer buffer;
1726 struct inotify_event *e;
1729 l = read(fd, &buffer, sizeof(buffer));
1731 if (errno == EINTR || errno == EAGAIN)
1734 return log_error_errno(errno, "Failed to read control group inotify events: %m");
1737 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1741 /* Queue overflow has no watch descriptor */
1744 if (e->mask & IN_IGNORED)
1745 /* The watch was just removed */
1748 u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
1749 if (!u) /* Not that inotify might deliver
1750 * events for a watch even after it
1751 * was removed, because it was queued
1752 * before the removal. Let's ignore
1753 * this here safely. */
1756 (void) unit_notify_cgroup_empty(u);
1762 int manager_setup_cgroup(Manager *m) {
1763 _cleanup_free_ char *path = NULL;
1770 /* 1. Determine hierarchy */
1771 m->cgroup_root = mfree(m->cgroup_root);
1772 #if 0 /// elogind is not init and must therefore search for PID 1 instead of self.
1773 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
1775 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &m->cgroup_root);
1778 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
1780 #if 0 /// elogind does not support systemd scopes and slices
1781 /* Chop off the init scope, if we are already located in it */
1782 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1784 /* LEGACY: Also chop off the system slice if we are in
1785 * it. This is to support live upgrades from older systemd
1786 * versions where PID 1 was moved there. Also see
1787 * cg_get_root_path(). */
1788 if (!e && MANAGER_IS_SYSTEM(m)) {
1789 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
1791 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
1797 /* And make sure to store away the root value without trailing
1798 * slash, even for the root dir, so that we can easily prepend
1800 while ((e = endswith(m->cgroup_root, "/")))
1802 log_debug_elogind("Cgroup Controller \"%s\" -> root \"%s\"",
1803 SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root);
1806 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
1808 return log_error_errno(r, "Cannot find cgroup mount point: %m");
1810 r = cg_unified_flush();
1812 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
1814 all_unified = cg_all_unified();
1816 return log_error_errno(r, "Couldn't determine whether we are in all unified mode: %m");
1818 log_debug("Unified cgroup hierarchy is located at %s.", path);
1820 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1822 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
1824 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
1826 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
1830 const char *scope_path;
1832 #if 0 /// elogind is not init, and does not install the agent here.
1833 /* 3. Install agent */
1834 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
1836 /* In the unified hierarchy we can get
1837 * cgroup empty notifications via inotify. */
1839 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1840 safe_close(m->cgroup_inotify_fd);
1842 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1843 if (m->cgroup_inotify_fd < 0)
1844 return log_error_errno(errno, "Failed to create control group inotify object: %m");
1846 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
1848 return log_error_errno(r, "Failed to watch control group inotify object: %m");
1850 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
1851 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
1852 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-5);
1854 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
1856 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
1858 } else if (MANAGER_IS_SYSTEM(m)) {
1860 /* On the legacy hierarchy we only get
1861 * notifications via cgroup agents. (Which
1862 * isn't really reliable, since it does not
1863 * generate events when control groups with
1864 * children run empty. */
1866 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
1868 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
1870 log_debug("Installed release agent.");
1872 log_debug("Release agent already installed.");
1875 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1876 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1877 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1880 * This method is in core, and normally called by systemd
1881 * being init. As elogind is never init, we can not install
1882 * our agent here. We do so when mounting our cgroup file
1883 * system, so only if elogind is its own tiny controller.
1884 * Further, elogind is not meant to run in systemd init scope. */
1885 if (MANAGER_IS_SYSTEM(m))
1886 // we are our own cgroup controller
1887 scope_path = strjoina("");
1888 else if (streq(m->cgroup_root, "/elogind"))
1889 // root already is our cgroup
1890 scope_path = strjoina(m->cgroup_root);
1892 // we have to create our own group
1893 scope_path = strjoina(m->cgroup_root, "/elogind");
1894 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1897 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
1898 log_debug_elogind("Created control group \"%s\"", scope_path);
1900 #if 0 /// elogind is not a "sub-controller" like systemd, so migration is not needed.
1901 /* also, move all other userspace processes remaining
1902 * in the root cgroup into that scope. */
1903 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1905 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
1908 /* 5. And pin it, so that it cannot be unmounted */
1909 safe_close(m->pin_cgroupfs_fd);
1910 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
1911 if (m->pin_cgroupfs_fd < 0)
1912 return log_error_errno(errno, "Failed to open pin file: %m");
1914 /* 6. Always enable hierarchical support if it exists... */
1916 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
1919 /* 7. Figure out which controllers are supported */
1920 r = cg_mask_supported(&m->cgroup_supported);
1922 return log_error_errno(r, "Failed to determine supported controllers: %m");
1924 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
1925 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
1930 void manager_shutdown_cgroup(Manager *m, bool delete) {
1933 /* We can't really delete the group, since we are in it. But
1935 if (delete && m->cgroup_root)
1936 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
1938 #if 0 /// elogind does not support the unified hierarchy, yet.
1939 m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
1941 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1942 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
1945 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
1947 m->cgroup_root = mfree(m->cgroup_root);
1950 #if 0 /// UNNEEDED by elogind
1951 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
1958 u = hashmap_get(m->cgroup_unit, cgroup);
1962 p = strdupa(cgroup);
1966 e = strrchr(p, '/');
1968 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
1972 u = hashmap_get(m->cgroup_unit, p);
1978 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
1979 _cleanup_free_ char *cgroup = NULL;
1987 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
1991 return manager_get_unit_by_cgroup(m, cgroup);
1994 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
2003 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
2005 u = hashmap_get(m->watch_pids1, PID_TO_PTR(pid));
2009 u = hashmap_get(m->watch_pids2, PID_TO_PTR(pid));
2013 return manager_get_unit_by_pid_cgroup(m, pid);
2017 #if 0 /// elogind must substitute this with its own variant
2018 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
2024 log_debug("Got cgroup empty notification for: %s", cgroup);
2026 u = manager_get_unit_by_cgroup(m, cgroup);
2030 return unit_notify_cgroup_empty(u);
2033 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
2039 log_debug("Got cgroup empty notification for: %s", cgroup);
2041 s = hashmap_get(m->sessions, cgroup);
2044 session_finalize(s);
2047 log_warning("Session not found: %s", cgroup);
2052 #if 0 /// UNNEEDED by elogind
2053 int unit_get_memory_current(Unit *u, uint64_t *ret) {
2054 _cleanup_free_ char *v = NULL;
2060 if (!u->cgroup_path)
2063 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
2066 r = cg_all_unified();
2070 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
2072 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
2078 return safe_atou64(v, ret);
2081 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
2082 _cleanup_free_ char *v = NULL;
2088 if (!u->cgroup_path)
2091 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
2094 r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
2100 return safe_atou64(v, ret);
2103 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
2104 _cleanup_free_ char *v = NULL;
2111 if (!u->cgroup_path)
2114 r = cg_all_unified();
2118 const char *keys[] = { "usage_usec", NULL };
2119 _cleanup_free_ char *val = NULL;
2122 if ((u->cgroup_realized_mask & CGROUP_MASK_CPU) == 0)
2125 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", keys, &val);
2129 r = safe_atou64(val, &us);
2133 ns = us * NSEC_PER_USEC;
2135 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
2138 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
2144 r = safe_atou64(v, &ns);
2153 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
2159 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2160 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2161 * call this function with a NULL return value. */
2163 r = unit_get_cpu_usage_raw(u, &ns);
2164 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
2165 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2169 *ret = u->cpu_usage_last;
2175 if (ns > u->cpu_usage_base)
2176 ns -= u->cpu_usage_base;
2180 u->cpu_usage_last = ns;
2187 int unit_reset_cpu_usage(Unit *u) {
2193 u->cpu_usage_last = NSEC_INFINITY;
2195 r = unit_get_cpu_usage_raw(u, &ns);
2197 u->cpu_usage_base = 0;
2201 u->cpu_usage_base = ns;
2205 bool unit_cgroup_delegate(Unit *u) {
2210 c = unit_get_cgroup_context(u);
2217 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
2220 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2226 /* always invalidate compat pairs together */
2227 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
2228 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
2230 if ((u->cgroup_realized_mask & m) == 0)
2233 u->cgroup_realized_mask &= ~m;
2234 unit_add_to_cgroup_queue(u);
2237 void manager_invalidate_startup_units(Manager *m) {
2243 SET_FOREACH(u, m->startup_units, i)
2244 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
2247 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
2248 [CGROUP_AUTO] = "auto",
2249 [CGROUP_CLOSED] = "closed",
2250 [CGROUP_STRICT] = "strict",
2253 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);