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"
36 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
38 #if 0 /// UNNEEDED by elogind
39 void cgroup_context_init(CGroupContext *c) {
42 /* Initialize everything to the kernel defaults, assuming the
43 * structure is preinitialized to 0 */
45 c->cpu_shares = CGROUP_CPU_SHARES_INVALID;
46 c->startup_cpu_shares = CGROUP_CPU_SHARES_INVALID;
47 c->cpu_quota_per_sec_usec = USEC_INFINITY;
49 c->memory_high = CGROUP_LIMIT_MAX;
50 c->memory_max = CGROUP_LIMIT_MAX;
52 c->memory_limit = CGROUP_LIMIT_MAX;
54 c->io_weight = CGROUP_WEIGHT_INVALID;
55 c->startup_io_weight = CGROUP_WEIGHT_INVALID;
57 c->blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
58 c->startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
60 c->tasks_max = (uint64_t) -1;
63 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
67 LIST_REMOVE(device_allow, c->device_allow, a);
72 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
76 LIST_REMOVE(device_weights, c->io_device_weights, w);
81 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
85 LIST_REMOVE(device_limits, c->io_device_limits, l);
90 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
94 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
99 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
103 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
108 void cgroup_context_done(CGroupContext *c) {
111 while (c->io_device_weights)
112 cgroup_context_free_io_device_weight(c, c->io_device_weights);
114 while (c->io_device_limits)
115 cgroup_context_free_io_device_limit(c, c->io_device_limits);
117 while (c->blockio_device_weights)
118 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
120 while (c->blockio_device_bandwidths)
121 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
123 while (c->device_allow)
124 cgroup_context_free_device_allow(c, c->device_allow);
127 void cgroup_context_dump(CGroupContext *c, FILE* f, const char *prefix) {
128 CGroupIODeviceLimit *il;
129 CGroupIODeviceWeight *iw;
130 CGroupBlockIODeviceBandwidth *b;
131 CGroupBlockIODeviceWeight *w;
132 CGroupDeviceAllow *a;
133 char u[FORMAT_TIMESPAN_MAX];
138 prefix = strempty(prefix);
141 "%sCPUAccounting=%s\n"
142 "%sIOAccounting=%s\n"
143 "%sBlockIOAccounting=%s\n"
144 "%sMemoryAccounting=%s\n"
145 "%sTasksAccounting=%s\n"
146 "%sCPUShares=%" PRIu64 "\n"
147 "%sStartupCPUShares=%" PRIu64 "\n"
148 "%sCPUQuotaPerSecSec=%s\n"
149 "%sIOWeight=%" PRIu64 "\n"
150 "%sStartupIOWeight=%" PRIu64 "\n"
151 "%sBlockIOWeight=%" PRIu64 "\n"
152 "%sStartupBlockIOWeight=%" PRIu64 "\n"
153 "%sMemoryLow=%" PRIu64 "\n"
154 "%sMemoryHigh=%" PRIu64 "\n"
155 "%sMemoryMax=%" PRIu64 "\n"
156 "%sMemoryLimit=%" PRIu64 "\n"
157 "%sTasksMax=%" PRIu64 "\n"
158 "%sDevicePolicy=%s\n"
160 prefix, yes_no(c->cpu_accounting),
161 prefix, yes_no(c->io_accounting),
162 prefix, yes_no(c->blockio_accounting),
163 prefix, yes_no(c->memory_accounting),
164 prefix, yes_no(c->tasks_accounting),
165 prefix, c->cpu_shares,
166 prefix, c->startup_cpu_shares,
167 prefix, format_timespan(u, sizeof(u), c->cpu_quota_per_sec_usec, 1),
168 prefix, c->io_weight,
169 prefix, c->startup_io_weight,
170 prefix, c->blockio_weight,
171 prefix, c->startup_blockio_weight,
172 prefix, c->memory_low,
173 prefix, c->memory_high,
174 prefix, c->memory_max,
175 prefix, c->memory_limit,
176 prefix, c->tasks_max,
177 prefix, cgroup_device_policy_to_string(c->device_policy),
178 prefix, yes_no(c->delegate));
180 LIST_FOREACH(device_allow, a, c->device_allow)
182 "%sDeviceAllow=%s %s%s%s\n",
185 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
187 LIST_FOREACH(device_weights, iw, c->io_device_weights)
189 "%sIODeviceWeight=%s %" PRIu64,
194 LIST_FOREACH(device_limits, il, c->io_device_limits) {
195 char buf[FORMAT_BYTES_MAX];
196 CGroupIOLimitType type;
198 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
199 if (il->limits[type] != cgroup_io_limit_defaults[type])
203 cgroup_io_limit_type_to_string(type),
205 format_bytes(buf, sizeof(buf), il->limits[type]));
208 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
210 "%sBlockIODeviceWeight=%s %" PRIu64,
215 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
216 char buf[FORMAT_BYTES_MAX];
218 if (b->rbps != CGROUP_LIMIT_MAX)
220 "%sBlockIOReadBandwidth=%s %s\n",
223 format_bytes(buf, sizeof(buf), b->rbps));
224 if (b->wbps != CGROUP_LIMIT_MAX)
226 "%sBlockIOWriteBandwidth=%s %s\n",
229 format_bytes(buf, sizeof(buf), b->wbps));
233 static int lookup_block_device(const char *p, dev_t *dev) {
242 return log_warning_errno(errno, "Couldn't stat device %s: %m", p);
244 if (S_ISBLK(st.st_mode))
246 else if (major(st.st_dev) != 0) {
247 /* If this is not a device node then find the block
248 * device this file is stored on */
251 /* If this is a partition, try to get the originating
253 block_get_whole_disk(*dev, dev);
255 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p);
262 static int whitelist_device(const char *path, const char *node, const char *acc) {
263 char buf[2+DECIMAL_STR_MAX(dev_t)*2+2+4];
270 if (stat(node, &st) < 0) {
271 log_warning("Couldn't stat device %s", node);
275 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
276 log_warning("%s is not a device.", node);
282 S_ISCHR(st.st_mode) ? 'c' : 'b',
283 major(st.st_rdev), minor(st.st_rdev),
286 r = cg_set_attribute("devices", path, "devices.allow", buf);
288 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
289 "Failed to set devices.allow on %s: %m", path);
294 static int whitelist_major(const char *path, const char *name, char type, const char *acc) {
295 _cleanup_fclose_ FILE *f = NULL;
302 assert(type == 'b' || type == 'c');
304 f = fopen("/proc/devices", "re");
306 return log_warning_errno(errno, "Cannot open /proc/devices to resolve %s (%c): %m", name, type);
308 FOREACH_LINE(line, f, goto fail) {
309 char buf[2+DECIMAL_STR_MAX(unsigned)+3+4], *p, *w;
314 if (type == 'c' && streq(line, "Character devices:")) {
319 if (type == 'b' && streq(line, "Block devices:")) {
334 w = strpbrk(p, WHITESPACE);
339 r = safe_atou(p, &maj);
346 w += strspn(w, WHITESPACE);
348 if (fnmatch(name, w, 0) != 0)
357 r = cg_set_attribute("devices", path, "devices.allow", buf);
359 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
360 "Failed to set devices.allow on %s: %m", path);
366 log_warning_errno(errno, "Failed to read /proc/devices: %m");
370 static bool cgroup_context_has_io_config(CGroupContext *c) {
371 return c->io_accounting ||
372 c->io_weight != CGROUP_WEIGHT_INVALID ||
373 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
374 c->io_device_weights ||
378 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
379 return c->blockio_accounting ||
380 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
381 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
382 c->blockio_device_weights ||
383 c->blockio_device_bandwidths;
386 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
387 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
388 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
389 return c->startup_io_weight;
390 else if (c->io_weight != CGROUP_WEIGHT_INVALID)
393 return CGROUP_WEIGHT_DEFAULT;
396 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
397 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
398 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
399 return c->startup_blockio_weight;
400 else if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
401 return c->blockio_weight;
403 return CGROUP_BLKIO_WEIGHT_DEFAULT;
406 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
407 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
408 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
411 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
412 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
413 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
416 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
417 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
421 r = lookup_block_device(dev_path, &dev);
425 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), io_weight);
426 r = cg_set_attribute("io", u->cgroup_path, "io.weight", buf);
428 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
429 "Failed to set io.weight: %m");
432 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
433 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
437 r = lookup_block_device(dev_path, &dev);
441 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), blkio_weight);
442 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.weight_device", buf);
444 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
445 "Failed to set blkio.weight_device: %m");
448 static unsigned cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
449 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)];
450 char buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
451 CGroupIOLimitType type;
456 r = lookup_block_device(dev_path, &dev);
460 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++) {
461 if (limits[type] != cgroup_io_limit_defaults[type]) {
462 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
465 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
469 xsprintf(buf, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev), minor(dev),
470 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
471 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
472 r = cg_set_attribute("io", u->cgroup_path, "io.max", buf);
474 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
475 "Failed to set io.max: %m");
479 static unsigned cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
480 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
485 r = lookup_block_device(dev_path, &dev);
489 if (rbps != CGROUP_LIMIT_MAX)
491 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), rbps);
492 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.read_bps_device", buf);
494 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
495 "Failed to set blkio.throttle.read_bps_device: %m");
497 if (wbps != CGROUP_LIMIT_MAX)
499 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), wbps);
500 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.write_bps_device", buf);
502 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
503 "Failed to set blkio.throttle.write_bps_device: %m");
508 static bool cgroup_context_has_unified_memory_config(CGroupContext *c) {
509 return c->memory_low > 0 || c->memory_high != CGROUP_LIMIT_MAX || c->memory_max != CGROUP_LIMIT_MAX;
512 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
513 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
516 if (v != CGROUP_LIMIT_MAX)
517 xsprintf(buf, "%" PRIu64 "\n", v);
519 r = cg_set_attribute("memory", u->cgroup_path, file, buf);
521 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
522 "Failed to set %s: %m", file);
525 static void cgroup_context_apply(Unit *u, CGroupMask mask, ManagerState state) {
533 c = unit_get_cgroup_context(u);
534 path = u->cgroup_path;
542 /* Some cgroup attributes are not supported on the root cgroup,
543 * hence silently ignore */
544 is_root = isempty(path) || path_equal(path, "/");
546 /* Make sure we don't try to display messages with an empty path. */
549 /* We generally ignore errors caused by read-only mounted
550 * cgroup trees (assuming we are running in a container then),
551 * and missing cgroups, i.e. EROFS and ENOENT. */
553 if ((mask & CGROUP_MASK_CPU) && !is_root) {
554 char buf[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t)) + 1];
556 sprintf(buf, "%" PRIu64 "\n",
557 IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) && c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID ? c->startup_cpu_shares :
558 c->cpu_shares != CGROUP_CPU_SHARES_INVALID ? c->cpu_shares : CGROUP_CPU_SHARES_DEFAULT);
559 r = cg_set_attribute("cpu", path, "cpu.shares", buf);
561 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
562 "Failed to set cpu.shares: %m");
564 sprintf(buf, USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
565 r = cg_set_attribute("cpu", path, "cpu.cfs_period_us", buf);
567 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
568 "Failed to set cpu.cfs_period_us: %m");
570 if (c->cpu_quota_per_sec_usec != USEC_INFINITY) {
571 sprintf(buf, USEC_FMT "\n", c->cpu_quota_per_sec_usec * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC);
572 r = cg_set_attribute("cpu", path, "cpu.cfs_quota_us", buf);
574 r = cg_set_attribute("cpu", path, "cpu.cfs_quota_us", "-1");
576 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
577 "Failed to set cpu.cfs_quota_us: %m");
580 if (mask & CGROUP_MASK_IO) {
581 bool has_io = cgroup_context_has_io_config(c);
582 bool has_blockio = cgroup_context_has_blockio_config(c);
585 char buf[8+DECIMAL_STR_MAX(uint64_t)+1];
589 weight = cgroup_context_io_weight(c, state);
590 else if (has_blockio)
591 weight = cgroup_weight_blkio_to_io(cgroup_context_blkio_weight(c, state));
593 weight = CGROUP_WEIGHT_DEFAULT;
595 xsprintf(buf, "default %" PRIu64 "\n", weight);
596 r = cg_set_attribute("io", path, "io.weight", buf);
598 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
599 "Failed to set io.weight: %m");
602 CGroupIODeviceWeight *w;
604 /* FIXME: no way to reset this list */
605 LIST_FOREACH(device_weights, w, c->io_device_weights)
606 cgroup_apply_io_device_weight(u, w->path, w->weight);
607 } else if (has_blockio) {
608 CGroupBlockIODeviceWeight *w;
610 /* FIXME: no way to reset this list */
611 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
612 cgroup_apply_io_device_weight(u, w->path, cgroup_weight_blkio_to_io(w->weight));
616 /* Apply limits and free ones without config. */
618 CGroupIODeviceLimit *l, *next;
620 LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
621 if (!cgroup_apply_io_device_limit(u, l->path, l->limits))
622 cgroup_context_free_io_device_limit(c, l);
624 } else if (has_blockio) {
625 CGroupBlockIODeviceBandwidth *b, *next;
627 LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths) {
628 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
629 CGroupIOLimitType type;
631 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
632 limits[type] = cgroup_io_limit_defaults[type];
634 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
635 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
637 if (!cgroup_apply_io_device_limit(u, b->path, limits))
638 cgroup_context_free_blockio_device_bandwidth(c, b);
643 if (mask & CGROUP_MASK_BLKIO) {
644 bool has_io = cgroup_context_has_io_config(c);
645 bool has_blockio = cgroup_context_has_blockio_config(c);
648 char buf[DECIMAL_STR_MAX(uint64_t)+1];
652 weight = cgroup_context_blkio_weight(c, state);
654 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
656 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
658 xsprintf(buf, "%" PRIu64 "\n", weight);
659 r = cg_set_attribute("blkio", path, "blkio.weight", buf);
661 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
662 "Failed to set blkio.weight: %m");
665 CGroupBlockIODeviceWeight *w;
667 /* FIXME: no way to reset this list */
668 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
669 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
671 CGroupIODeviceWeight *w;
673 /* FIXME: no way to reset this list */
674 LIST_FOREACH(device_weights, w, c->io_device_weights)
675 cgroup_apply_blkio_device_weight(u, w->path, cgroup_weight_io_to_blkio(w->weight));
679 /* Apply limits and free ones without config. */
681 CGroupBlockIODeviceBandwidth *b, *next;
683 LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths) {
684 if (!cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps))
685 cgroup_context_free_blockio_device_bandwidth(c, b);
688 CGroupIODeviceLimit *l, *next;
690 LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
691 if (!cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]))
692 cgroup_context_free_io_device_limit(c, l);
697 if ((mask & CGROUP_MASK_MEMORY) && !is_root) {
698 if (cg_unified() > 0) {
699 uint64_t max = c->memory_max;
701 if (cgroup_context_has_unified_memory_config(c))
704 max = c->memory_limit;
706 cgroup_apply_unified_memory_limit(u, "memory.low", c->memory_low);
707 cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
708 cgroup_apply_unified_memory_limit(u, "memory.max", max);
710 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
712 if (c->memory_limit != CGROUP_LIMIT_MAX)
713 xsprintf(buf, "%" PRIu64 "\n", c->memory_limit);
715 xsprintf(buf, "%" PRIu64 "\n", c->memory_max);
717 r = cg_set_attribute("memory", path, "memory.limit_in_bytes", buf);
719 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
720 "Failed to set memory.limit_in_bytes: %m");
724 if ((mask & CGROUP_MASK_DEVICES) && !is_root) {
725 CGroupDeviceAllow *a;
727 /* Changing the devices list of a populated cgroup
728 * might result in EINVAL, hence ignore EINVAL
731 if (c->device_allow || c->device_policy != CGROUP_AUTO)
732 r = cg_set_attribute("devices", path, "devices.deny", "a");
734 r = cg_set_attribute("devices", path, "devices.allow", "a");
736 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
737 "Failed to reset devices.list: %m");
739 if (c->device_policy == CGROUP_CLOSED ||
740 (c->device_policy == CGROUP_AUTO && c->device_allow)) {
741 static const char auto_devices[] =
742 "/dev/null\0" "rwm\0"
743 "/dev/zero\0" "rwm\0"
744 "/dev/full\0" "rwm\0"
745 "/dev/random\0" "rwm\0"
746 "/dev/urandom\0" "rwm\0"
748 "/dev/pts/ptmx\0" "rw\0" /* /dev/pts/ptmx may not be duplicated, but accessed */
749 /* Allow /run/elogind/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
750 "/run/elogind/inaccessible/chr\0" "rwm\0"
751 "/run/elogind/inaccessible/blk\0" "rwm\0";
755 NULSTR_FOREACH_PAIR(x, y, auto_devices)
756 whitelist_device(path, x, y);
758 whitelist_major(path, "pts", 'c', "rw");
759 whitelist_major(path, "kdbus", 'c', "rw");
760 whitelist_major(path, "kdbus/*", 'c', "rw");
763 LIST_FOREACH(device_allow, a, c->device_allow) {
779 if (startswith(a->path, "/dev/"))
780 whitelist_device(path, a->path, acc);
781 else if (startswith(a->path, "block-"))
782 whitelist_major(path, a->path + 6, 'b', acc);
783 else if (startswith(a->path, "char-"))
784 whitelist_major(path, a->path + 5, 'c', acc);
786 log_unit_debug(u, "Ignoring device %s while writing cgroup attribute.", a->path);
790 if ((mask & CGROUP_MASK_PIDS) && !is_root) {
792 if (c->tasks_max != (uint64_t) -1) {
793 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
795 sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
796 r = cg_set_attribute("pids", path, "pids.max", buf);
798 r = cg_set_attribute("pids", path, "pids.max", "max");
801 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
802 "Failed to set pids.max: %m");
806 CGroupMask cgroup_context_get_mask(CGroupContext *c) {
809 /* Figure out which controllers we need */
811 if (c->cpu_accounting ||
812 c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
813 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID ||
814 c->cpu_quota_per_sec_usec != USEC_INFINITY)
815 mask |= CGROUP_MASK_CPUACCT | CGROUP_MASK_CPU;
817 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
818 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
820 if (c->memory_accounting ||
821 c->memory_limit != CGROUP_LIMIT_MAX ||
822 cgroup_context_has_unified_memory_config(c))
823 mask |= CGROUP_MASK_MEMORY;
825 if (c->device_allow ||
826 c->device_policy != CGROUP_AUTO)
827 mask |= CGROUP_MASK_DEVICES;
829 if (c->tasks_accounting ||
830 c->tasks_max != (uint64_t) -1)
831 mask |= CGROUP_MASK_PIDS;
836 CGroupMask unit_get_own_mask(Unit *u) {
839 /* Returns the mask of controllers the unit needs for itself */
841 c = unit_get_cgroup_context(u);
845 /* If delegation is turned on, then turn on all cgroups,
846 * unless we are on the legacy hierarchy and the process we
847 * fork into it is known to drop privileges, and hence
848 * shouldn't get access to the controllers.
850 * Note that on the unified hierarchy it is safe to delegate
851 * controllers to unprivileged services. */
856 e = unit_get_exec_context(u);
858 exec_context_maintains_privileges(e) ||
860 return _CGROUP_MASK_ALL;
863 return cgroup_context_get_mask(c);
866 CGroupMask unit_get_members_mask(Unit *u) {
869 /* Returns the mask of controllers all of the unit's children
872 if (u->cgroup_members_mask_valid)
873 return u->cgroup_members_mask;
875 u->cgroup_members_mask = 0;
877 if (u->type == UNIT_SLICE) {
881 SET_FOREACH(member, u->dependencies[UNIT_BEFORE], i) {
886 if (UNIT_DEREF(member->slice) != u)
889 u->cgroup_members_mask |=
890 unit_get_own_mask(member) |
891 unit_get_members_mask(member);
895 u->cgroup_members_mask_valid = true;
896 return u->cgroup_members_mask;
899 CGroupMask unit_get_siblings_mask(Unit *u) {
902 /* Returns the mask of controllers all of the unit's siblings
903 * require, i.e. the members mask of the unit's parent slice
904 * if there is one. */
906 if (UNIT_ISSET(u->slice))
907 return unit_get_members_mask(UNIT_DEREF(u->slice));
909 return unit_get_own_mask(u) | unit_get_members_mask(u);
912 CGroupMask unit_get_subtree_mask(Unit *u) {
914 /* Returns the mask of this subtree, meaning of the group
915 * itself and its children. */
917 return unit_get_own_mask(u) | unit_get_members_mask(u);
920 CGroupMask unit_get_target_mask(Unit *u) {
923 /* This returns the cgroup mask of all controllers to enable
924 * for a specific cgroup, i.e. everything it needs itself,
925 * plus all that its children need, plus all that its siblings
926 * need. This is primarily useful on the legacy cgroup
927 * hierarchy, where we need to duplicate each cgroup in each
928 * hierarchy that shall be enabled for it. */
930 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
931 mask &= u->manager->cgroup_supported;
936 CGroupMask unit_get_enable_mask(Unit *u) {
939 /* This returns the cgroup mask of all controllers to enable
940 * for the children of a specific cgroup. This is primarily
941 * useful for the unified cgroup hierarchy, where each cgroup
942 * controls which controllers are enabled for its children. */
944 mask = unit_get_members_mask(u);
945 mask &= u->manager->cgroup_supported;
950 /* Recurse from a unit up through its containing slices, propagating
951 * mask bits upward. A unit is also member of itself. */
952 void unit_update_cgroup_members_masks(Unit *u) {
958 /* Calculate subtree mask */
959 m = unit_get_subtree_mask(u);
961 /* See if anything changed from the previous invocation. If
962 * not, we're done. */
963 if (u->cgroup_subtree_mask_valid && m == u->cgroup_subtree_mask)
967 u->cgroup_subtree_mask_valid &&
968 ((m & ~u->cgroup_subtree_mask) != 0) &&
969 ((~m & u->cgroup_subtree_mask) == 0);
971 u->cgroup_subtree_mask = m;
972 u->cgroup_subtree_mask_valid = true;
974 if (UNIT_ISSET(u->slice)) {
975 Unit *s = UNIT_DEREF(u->slice);
978 /* There's more set now than before. We
979 * propagate the new mask to the parent's mask
980 * (not caring if it actually was valid or
983 s->cgroup_members_mask |= m;
986 /* There's less set now than before (or we
987 * don't know), we need to recalculate
988 * everything, so let's invalidate the
989 * parent's members mask */
991 s->cgroup_members_mask_valid = false;
993 /* And now make sure that this change also hits our
995 unit_update_cgroup_members_masks(s);
999 static const char *migrate_callback(CGroupMask mask, void *userdata) {
1006 if (u->cgroup_path &&
1007 u->cgroup_realized &&
1008 (u->cgroup_realized_mask & mask) == mask)
1009 return u->cgroup_path;
1011 u = UNIT_DEREF(u->slice);
1017 char *unit_default_cgroup_path(Unit *u) {
1018 _cleanup_free_ char *escaped = NULL, *slice = NULL;
1023 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1024 return strdup(u->manager->cgroup_root);
1026 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1027 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1032 escaped = cg_escape(u->id);
1037 return strjoin(u->manager->cgroup_root, "/", slice, "/", escaped, NULL);
1039 return strjoin(u->manager->cgroup_root, "/", escaped, NULL);
1042 int unit_set_cgroup_path(Unit *u, const char *path) {
1043 _cleanup_free_ char *p = NULL;
1055 if (streq_ptr(u->cgroup_path, p))
1059 r = hashmap_put(u->manager->cgroup_unit, p, u);
1064 unit_release_cgroup(u);
1072 int unit_watch_cgroup(Unit *u) {
1073 _cleanup_free_ char *events = NULL;
1078 if (!u->cgroup_path)
1081 if (u->cgroup_inotify_wd >= 0)
1084 /* Only applies to the unified hierarchy */
1087 return log_unit_error_errno(u, r, "Failed detect whether the unified hierarchy is used: %m");
1091 /* Don't watch the root slice, it's pointless. */
1092 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1095 r = hashmap_ensure_allocated(&u->manager->cgroup_inotify_wd_unit, &trivial_hash_ops);
1099 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1103 u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1104 if (u->cgroup_inotify_wd < 0) {
1106 if (errno == ENOENT) /* If the directory is already
1107 * gone we don't need to track
1108 * it, so this is not an error */
1111 return log_unit_error_errno(u, errno, "Failed to add inotify watch descriptor for control group %s: %m", u->cgroup_path);
1114 r = hashmap_put(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd), u);
1116 return log_unit_error_errno(u, r, "Failed to add inotify watch descriptor to hash map: %m");
1121 static int unit_create_cgroup(
1123 CGroupMask target_mask,
1124 CGroupMask enable_mask) {
1131 c = unit_get_cgroup_context(u);
1135 if (!u->cgroup_path) {
1136 _cleanup_free_ char *path = NULL;
1138 path = unit_default_cgroup_path(u);
1142 r = unit_set_cgroup_path(u, path);
1144 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1146 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1149 /* First, create our own group */
1150 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1152 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1154 /* Start watching it */
1155 (void) unit_watch_cgroup(u);
1157 /* Enable all controllers we need */
1158 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path);
1160 log_unit_warning_errno(u, r, "Failed to enable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
1162 /* Keep track that this is now realized */
1163 u->cgroup_realized = true;
1164 u->cgroup_realized_mask = target_mask;
1165 u->cgroup_enabled_mask = enable_mask;
1167 if (u->type != UNIT_SLICE && !c->delegate) {
1169 /* Then, possibly move things over, but not if
1170 * subgroups may contain processes, which is the case
1171 * for slice and delegation units. */
1172 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1174 log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
1180 int unit_attach_pids_to_cgroup(Unit *u) {
1184 r = unit_realize_cgroup(u);
1188 r = cg_attach_many_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->pids, migrate_callback, u);
1195 static bool unit_has_mask_realized(Unit *u, CGroupMask target_mask, CGroupMask enable_mask) {
1198 return u->cgroup_realized && u->cgroup_realized_mask == target_mask && u->cgroup_enabled_mask == enable_mask;
1201 /* Check if necessary controllers and attributes for a unit are in place.
1203 * If so, do nothing.
1204 * If not, create paths, move processes over, and set attributes.
1206 * Returns 0 on success and < 0 on failure. */
1207 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
1208 CGroupMask target_mask, enable_mask;
1213 if (u->in_cgroup_queue) {
1214 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
1215 u->in_cgroup_queue = false;
1218 target_mask = unit_get_target_mask(u);
1219 enable_mask = unit_get_enable_mask(u);
1221 if (unit_has_mask_realized(u, target_mask, enable_mask))
1224 /* First, realize parents */
1225 if (UNIT_ISSET(u->slice)) {
1226 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
1231 /* And then do the real work */
1232 r = unit_create_cgroup(u, target_mask, enable_mask);
1236 /* Finally, apply the necessary attributes. */
1237 cgroup_context_apply(u, target_mask, state);
1242 static void unit_add_to_cgroup_queue(Unit *u) {
1244 if (u->in_cgroup_queue)
1247 LIST_PREPEND(cgroup_queue, u->manager->cgroup_queue, u);
1248 u->in_cgroup_queue = true;
1251 unsigned manager_dispatch_cgroup_queue(Manager *m) {
1257 state = manager_state(m);
1259 while ((i = m->cgroup_queue)) {
1260 assert(i->in_cgroup_queue);
1262 r = unit_realize_cgroup_now(i, state);
1264 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
1272 static void unit_queue_siblings(Unit *u) {
1275 /* This adds the siblings of the specified unit and the
1276 * siblings of all parent units to the cgroup queue. (But
1277 * neither the specified unit itself nor the parents.) */
1279 while ((slice = UNIT_DEREF(u->slice))) {
1283 SET_FOREACH(m, slice->dependencies[UNIT_BEFORE], i) {
1287 /* Skip units that have a dependency on the slice
1288 * but aren't actually in it. */
1289 if (UNIT_DEREF(m->slice) != slice)
1292 /* No point in doing cgroup application for units
1293 * without active processes. */
1294 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
1297 /* If the unit doesn't need any new controllers
1298 * and has current ones realized, it doesn't need
1300 if (unit_has_mask_realized(m, unit_get_target_mask(m), unit_get_enable_mask(m)))
1303 unit_add_to_cgroup_queue(m);
1310 int unit_realize_cgroup(Unit *u) {
1313 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1316 /* So, here's the deal: when realizing the cgroups for this
1317 * unit, we need to first create all parents, but there's more
1318 * actually: for the weight-based controllers we also need to
1319 * make sure that all our siblings (i.e. units that are in the
1320 * same slice as we are) have cgroups, too. Otherwise, things
1321 * would become very uneven as each of their processes would
1322 * get as much resources as all our group together. This call
1323 * will synchronously create the parent cgroups, but will
1324 * defer work on the siblings to the next event loop
1327 /* Add all sibling slices to the cgroup queue. */
1328 unit_queue_siblings(u);
1330 /* And realize this one now (and apply the values) */
1331 return unit_realize_cgroup_now(u, manager_state(u->manager));
1334 void unit_release_cgroup(Unit *u) {
1337 /* Forgets all cgroup details for this cgroup */
1339 if (u->cgroup_path) {
1340 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1341 u->cgroup_path = mfree(u->cgroup_path);
1344 if (u->cgroup_inotify_wd >= 0) {
1345 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1346 log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1348 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1349 u->cgroup_inotify_wd = -1;
1353 void unit_prune_cgroup(Unit *u) {
1359 /* Removes the cgroup, if empty and possible, and stops watching it. */
1361 if (!u->cgroup_path)
1364 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1366 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
1368 log_unit_debug_errno(u, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
1375 unit_release_cgroup(u);
1377 u->cgroup_realized = false;
1378 u->cgroup_realized_mask = 0;
1379 u->cgroup_enabled_mask = 0;
1382 int unit_search_main_pid(Unit *u, pid_t *ret) {
1383 _cleanup_fclose_ FILE *f = NULL;
1384 pid_t pid = 0, npid, mypid;
1390 if (!u->cgroup_path)
1393 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1398 while (cg_read_pid(f, &npid) > 0) {
1404 /* Ignore processes that aren't our kids */
1405 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
1409 /* Dang, there's more than one daemonized PID
1410 in this group, so we don't know what process
1411 is the main process. */
1422 static int unit_watch_pids_in_path(Unit *u, const char *path) {
1423 _cleanup_closedir_ DIR *d = NULL;
1424 _cleanup_fclose_ FILE *f = NULL;
1430 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1436 while ((r = cg_read_pid(f, &pid)) > 0) {
1437 r = unit_watch_pid(u, pid);
1438 if (r < 0 && ret >= 0)
1442 if (r < 0 && ret >= 0)
1446 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1453 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1454 _cleanup_free_ char *p = NULL;
1456 p = strjoin(path, "/", fn, NULL);
1462 r = unit_watch_pids_in_path(u, p);
1463 if (r < 0 && ret >= 0)
1467 if (r < 0 && ret >= 0)
1474 int unit_watch_all_pids(Unit *u) {
1477 /* Adds all PIDs from our cgroup to the set of PIDs we
1478 * watch. This is a fallback logic for cases where we do not
1479 * get reliable cgroup empty notifications: we try to use
1480 * SIGCHLD as replacement. */
1482 if (!u->cgroup_path)
1485 if (cg_unified() > 0) /* On unified we can use proper notifications */
1488 return unit_watch_pids_in_path(u, u->cgroup_path);
1491 int unit_notify_cgroup_empty(Unit *u) {
1496 if (!u->cgroup_path)
1499 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
1503 unit_add_to_gc_queue(u);
1505 if (UNIT_VTABLE(u)->notify_cgroup_empty)
1506 UNIT_VTABLE(u)->notify_cgroup_empty(u);
1511 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1512 Manager *m = userdata;
1519 union inotify_event_buffer buffer;
1520 struct inotify_event *e;
1523 l = read(fd, &buffer, sizeof(buffer));
1525 if (errno == EINTR || errno == EAGAIN)
1528 return log_error_errno(errno, "Failed to read control group inotify events: %m");
1531 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1535 /* Queue overflow has no watch descriptor */
1538 if (e->mask & IN_IGNORED)
1539 /* The watch was just removed */
1542 u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
1543 if (!u) /* Not that inotify might deliver
1544 * events for a watch even after it
1545 * was removed, because it was queued
1546 * before the removal. Let's ignore
1547 * this here safely. */
1550 (void) unit_notify_cgroup_empty(u);
1556 int manager_setup_cgroup(Manager *m) {
1557 _cleanup_free_ char *path = NULL;
1564 /* 1. Determine hierarchy */
1565 m->cgroup_root = mfree(m->cgroup_root);
1566 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
1568 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
1570 #if 0 /// elogind does not support systemd scopes and slices
1571 /* Chop off the init scope, if we are already located in it */
1572 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1574 /* LEGACY: Also chop off the system slice if we are in
1575 * it. This is to support live upgrades from older systemd
1576 * versions where PID 1 was moved there. Also see
1577 * cg_get_root_path(). */
1578 if (!e && MANAGER_IS_SYSTEM(m)) {
1579 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
1581 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
1587 /* And make sure to store away the root value without trailing
1588 * slash, even for the root dir, so that we can easily prepend
1590 while ((e = endswith(m->cgroup_root, "/")))
1592 log_debug_elogind("Cgroup Controller \"%s\" -> root \"%s\"",
1593 SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root);
1596 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
1598 return log_error_errno(r, "Cannot find cgroup mount point: %m");
1600 unified = cg_unified();
1602 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
1604 log_debug("Unified cgroup hierarchy is located at %s.", path);
1606 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER ". File system hierarchy is at %s.", path);
1609 const char *scope_path;
1611 /* 3. Install agent */
1614 /* In the unified hierarchy we can can get
1615 * cgroup empty notifications via inotify. */
1617 #if 0 /// elogind does not support the unified hierarchy, yet.
1618 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1619 safe_close(m->cgroup_inotify_fd);
1621 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1622 if (m->cgroup_inotify_fd < 0)
1623 return log_error_errno(errno, "Failed to create control group inotify object: %m");
1625 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
1627 return log_error_errno(r, "Failed to watch control group inotify object: %m");
1629 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
1630 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
1631 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-5);
1633 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
1635 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
1638 return log_error_errno(EOPNOTSUPP, "Unified cgroup hierarchy not supported: %m");
1640 } else if (MANAGER_IS_SYSTEM(m)) {
1642 /* On the legacy hierarchy we only get
1643 * notifications via cgroup agents. (Which
1644 * isn't really reliable, since it does not
1645 * generate events when control groups with
1646 * children run empty. */
1648 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
1650 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
1652 log_debug("Installed release agent.");
1654 log_debug("Release agent already installed.");
1657 #if 0 /// elogind is not meant to run in systemd init scope
1658 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1659 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1660 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1662 if (streq(SYSTEMD_CGROUP_CONTROLLER, "name=elogind"))
1663 // we are our own cgroup controller
1664 scope_path = strjoina("");
1665 else if (streq(m->cgroup_root, "/elogind"))
1666 // root already is our cgroup
1667 scope_path = strjoina(m->cgroup_root);
1669 // we have to create our own group
1670 scope_path = strjoina(m->cgroup_root, "/elogind");
1671 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1674 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
1675 log_debug_elogind("Created control group \"%s\"", scope_path);
1677 /* also, move all other userspace processes remaining
1678 * in the root cgroup into that scope. */
1679 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1681 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
1683 /* 5. And pin it, so that it cannot be unmounted */
1684 safe_close(m->pin_cgroupfs_fd);
1685 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
1686 if (m->pin_cgroupfs_fd < 0)
1687 return log_error_errno(errno, "Failed to open pin file: %m");
1689 /* 6. Always enable hierarchical support if it exists... */
1691 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
1694 /* 7. Figure out which controllers are supported */
1695 r = cg_mask_supported(&m->cgroup_supported);
1697 return log_error_errno(r, "Failed to determine supported controllers: %m");
1699 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
1700 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
1705 void manager_shutdown_cgroup(Manager *m, bool delete) {
1708 /* We can't really delete the group, since we are in it. But
1710 if (delete && m->cgroup_root)
1711 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
1713 #if 0 /// elogind does not support the unified hierarchy, yet.
1714 m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
1716 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1717 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
1720 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
1722 m->cgroup_root = mfree(m->cgroup_root);
1725 #if 0 /// UNNEEDED by elogind
1726 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
1733 u = hashmap_get(m->cgroup_unit, cgroup);
1737 p = strdupa(cgroup);
1741 e = strrchr(p, '/');
1743 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
1747 u = hashmap_get(m->cgroup_unit, p);
1753 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
1754 _cleanup_free_ char *cgroup = NULL;
1762 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
1766 return manager_get_unit_by_cgroup(m, cgroup);
1769 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
1778 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
1780 u = hashmap_get(m->watch_pids1, PID_TO_PTR(pid));
1784 u = hashmap_get(m->watch_pids2, PID_TO_PTR(pid));
1788 return manager_get_unit_by_pid_cgroup(m, pid);
1791 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
1797 log_debug("Got cgroup empty notification for: %s", cgroup);
1799 u = manager_get_unit_by_cgroup(m, cgroup);
1803 return unit_notify_cgroup_empty(u);
1806 int unit_get_memory_current(Unit *u, uint64_t *ret) {
1807 _cleanup_free_ char *v = NULL;
1813 if (!u->cgroup_path)
1816 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
1819 if (cg_unified() <= 0)
1820 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
1822 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
1828 return safe_atou64(v, ret);
1831 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
1832 _cleanup_free_ char *v = NULL;
1838 if (!u->cgroup_path)
1841 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
1844 r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
1850 return safe_atou64(v, ret);
1853 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
1854 _cleanup_free_ char *v = NULL;
1861 if (!u->cgroup_path)
1864 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
1867 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
1873 r = safe_atou64(v, &ns);
1881 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
1885 r = unit_get_cpu_usage_raw(u, &ns);
1889 if (ns > u->cpuacct_usage_base)
1890 ns -= u->cpuacct_usage_base;
1898 int unit_reset_cpu_usage(Unit *u) {
1904 r = unit_get_cpu_usage_raw(u, &ns);
1906 u->cpuacct_usage_base = 0;
1910 u->cpuacct_usage_base = ns;
1914 bool unit_cgroup_delegate(Unit *u) {
1919 c = unit_get_cgroup_context(u);
1926 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
1929 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1935 /* always invalidate compat pairs together */
1936 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
1937 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
1939 if ((u->cgroup_realized_mask & m) == 0)
1942 u->cgroup_realized_mask &= ~m;
1943 unit_add_to_cgroup_queue(u);
1946 void manager_invalidate_startup_units(Manager *m) {
1952 SET_FOREACH(u, m->startup_units, i)
1953 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
1956 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
1957 [CGROUP_AUTO] = "auto",
1958 [CGROUP_CLOSED] = "closed",
1959 [CGROUP_STRICT] = "strict",
1962 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);