]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/cgroup.c
pid1: do not say "(null)" if no disabled controllers
[thirdparty/systemd.git] / src / core / cgroup.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <fcntl.h>
4 #include <fnmatch.h>
5
6 #include "sd-messages.h"
7
8 #include "alloc-util.h"
9 #include "blockdev-util.h"
10 #include "bpf-devices.h"
11 #include "bpf-firewall.h"
12 #include "btrfs-util.h"
13 #include "bus-error.h"
14 #include "cgroup-util.h"
15 #include "cgroup.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "fs-util.h"
19 #include "nulstr-util.h"
20 #include "parse-util.h"
21 #include "path-util.h"
22 #include "process-util.h"
23 #include "procfs-util.h"
24 #include "special.h"
25 #include "stat-util.h"
26 #include "stdio-util.h"
27 #include "string-table.h"
28 #include "string-util.h"
29 #include "virt.h"
30
31 #define CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
32
33 /* Returns the log level to use when cgroup attribute writes fail. When an attribute is missing or we have access
34 * problems we downgrade to LOG_DEBUG. This is supposed to be nice to container managers and kernels which want to mask
35 * out specific attributes from us. */
36 #define LOG_LEVEL_CGROUP_WRITE(r) (IN_SET(abs(r), ENOENT, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING)
37
38 bool manager_owns_host_root_cgroup(Manager *m) {
39 assert(m);
40
41 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
42 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
43 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
44 * we run in any kind of container virtualization. */
45
46 if (MANAGER_IS_USER(m))
47 return false;
48
49 if (detect_container() > 0)
50 return false;
51
52 return empty_or_root(m->cgroup_root);
53 }
54
55 bool unit_has_host_root_cgroup(Unit *u) {
56 assert(u);
57
58 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
59 * the manager manages the root cgroup. */
60
61 if (!manager_owns_host_root_cgroup(u->manager))
62 return false;
63
64 return unit_has_name(u, SPECIAL_ROOT_SLICE);
65 }
66
67 static int set_attribute_and_warn(Unit *u, const char *controller, const char *attribute, const char *value) {
68 int r;
69
70 r = cg_set_attribute(controller, u->cgroup_path, attribute, value);
71 if (r < 0)
72 log_unit_full(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to set '%s' attribute on '%s' to '%.*s': %m",
73 strna(attribute), isempty(u->cgroup_path) ? "/" : u->cgroup_path, (int) strcspn(value, NEWLINE), value);
74
75 return r;
76 }
77
78 static void cgroup_compat_warn(void) {
79 static bool cgroup_compat_warned = false;
80
81 if (cgroup_compat_warned)
82 return;
83
84 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
85 "See cgroup-compat debug messages for details.");
86
87 cgroup_compat_warned = true;
88 }
89
90 #define log_cgroup_compat(unit, fmt, ...) do { \
91 cgroup_compat_warn(); \
92 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
93 } while (false)
94
95 void cgroup_context_init(CGroupContext *c) {
96 assert(c);
97
98 /* Initialize everything to the kernel defaults. */
99
100 *c = (CGroupContext) {
101 .cpu_weight = CGROUP_WEIGHT_INVALID,
102 .startup_cpu_weight = CGROUP_WEIGHT_INVALID,
103 .cpu_quota_per_sec_usec = USEC_INFINITY,
104 .cpu_quota_period_usec = USEC_INFINITY,
105
106 .cpu_shares = CGROUP_CPU_SHARES_INVALID,
107 .startup_cpu_shares = CGROUP_CPU_SHARES_INVALID,
108
109 .memory_high = CGROUP_LIMIT_MAX,
110 .memory_max = CGROUP_LIMIT_MAX,
111 .memory_swap_max = CGROUP_LIMIT_MAX,
112
113 .memory_limit = CGROUP_LIMIT_MAX,
114
115 .io_weight = CGROUP_WEIGHT_INVALID,
116 .startup_io_weight = CGROUP_WEIGHT_INVALID,
117
118 .blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
119 .startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
120
121 .tasks_max = CGROUP_LIMIT_MAX,
122 };
123 }
124
125 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
126 assert(c);
127 assert(a);
128
129 LIST_REMOVE(device_allow, c->device_allow, a);
130 free(a->path);
131 free(a);
132 }
133
134 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
135 assert(c);
136 assert(w);
137
138 LIST_REMOVE(device_weights, c->io_device_weights, w);
139 free(w->path);
140 free(w);
141 }
142
143 void cgroup_context_free_io_device_latency(CGroupContext *c, CGroupIODeviceLatency *l) {
144 assert(c);
145 assert(l);
146
147 LIST_REMOVE(device_latencies, c->io_device_latencies, l);
148 free(l->path);
149 free(l);
150 }
151
152 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
153 assert(c);
154 assert(l);
155
156 LIST_REMOVE(device_limits, c->io_device_limits, l);
157 free(l->path);
158 free(l);
159 }
160
161 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
162 assert(c);
163 assert(w);
164
165 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
166 free(w->path);
167 free(w);
168 }
169
170 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
171 assert(c);
172 assert(b);
173
174 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
175 free(b->path);
176 free(b);
177 }
178
179 void cgroup_context_done(CGroupContext *c) {
180 assert(c);
181
182 while (c->io_device_weights)
183 cgroup_context_free_io_device_weight(c, c->io_device_weights);
184
185 while (c->io_device_latencies)
186 cgroup_context_free_io_device_latency(c, c->io_device_latencies);
187
188 while (c->io_device_limits)
189 cgroup_context_free_io_device_limit(c, c->io_device_limits);
190
191 while (c->blockio_device_weights)
192 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
193
194 while (c->blockio_device_bandwidths)
195 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
196
197 while (c->device_allow)
198 cgroup_context_free_device_allow(c, c->device_allow);
199
200 c->ip_address_allow = ip_address_access_free_all(c->ip_address_allow);
201 c->ip_address_deny = ip_address_access_free_all(c->ip_address_deny);
202
203 c->ip_filters_ingress = strv_free(c->ip_filters_ingress);
204 c->ip_filters_egress = strv_free(c->ip_filters_egress);
205 }
206
207 void cgroup_context_dump(CGroupContext *c, FILE* f, const char *prefix) {
208 _cleanup_free_ char *disable_controllers_str = NULL;
209 CGroupIODeviceLimit *il;
210 CGroupIODeviceWeight *iw;
211 CGroupIODeviceLatency *l;
212 CGroupBlockIODeviceBandwidth *b;
213 CGroupBlockIODeviceWeight *w;
214 CGroupDeviceAllow *a;
215 IPAddressAccessItem *iaai;
216 char **path;
217 char u[FORMAT_TIMESPAN_MAX];
218 char v[FORMAT_TIMESPAN_MAX];
219
220 assert(c);
221 assert(f);
222
223 prefix = strempty(prefix);
224
225 (void) cg_mask_to_string(c->disable_controllers, &disable_controllers_str);
226
227 fprintf(f,
228 "%sCPUAccounting=%s\n"
229 "%sIOAccounting=%s\n"
230 "%sBlockIOAccounting=%s\n"
231 "%sMemoryAccounting=%s\n"
232 "%sTasksAccounting=%s\n"
233 "%sIPAccounting=%s\n"
234 "%sCPUWeight=%" PRIu64 "\n"
235 "%sStartupCPUWeight=%" PRIu64 "\n"
236 "%sCPUShares=%" PRIu64 "\n"
237 "%sStartupCPUShares=%" PRIu64 "\n"
238 "%sCPUQuotaPerSecSec=%s\n"
239 "%sCPUQuotaPeriodSec=%s\n"
240 "%sIOWeight=%" PRIu64 "\n"
241 "%sStartupIOWeight=%" PRIu64 "\n"
242 "%sBlockIOWeight=%" PRIu64 "\n"
243 "%sStartupBlockIOWeight=%" PRIu64 "\n"
244 "%sDefaultMemoryMin=%" PRIu64 "\n"
245 "%sDefaultMemoryLow=%" PRIu64 "\n"
246 "%sMemoryMin=%" PRIu64 "\n"
247 "%sMemoryLow=%" PRIu64 "\n"
248 "%sMemoryHigh=%" PRIu64 "\n"
249 "%sMemoryMax=%" PRIu64 "\n"
250 "%sMemorySwapMax=%" PRIu64 "\n"
251 "%sMemoryLimit=%" PRIu64 "\n"
252 "%sTasksMax=%" PRIu64 "\n"
253 "%sDevicePolicy=%s\n"
254 "%sDisableControllers=%s\n"
255 "%sDelegate=%s\n",
256 prefix, yes_no(c->cpu_accounting),
257 prefix, yes_no(c->io_accounting),
258 prefix, yes_no(c->blockio_accounting),
259 prefix, yes_no(c->memory_accounting),
260 prefix, yes_no(c->tasks_accounting),
261 prefix, yes_no(c->ip_accounting),
262 prefix, c->cpu_weight,
263 prefix, c->startup_cpu_weight,
264 prefix, c->cpu_shares,
265 prefix, c->startup_cpu_shares,
266 prefix, format_timespan(u, sizeof(u), c->cpu_quota_per_sec_usec, 1),
267 prefix, format_timespan(v, sizeof(v), c->cpu_quota_period_usec, 1),
268 prefix, c->io_weight,
269 prefix, c->startup_io_weight,
270 prefix, c->blockio_weight,
271 prefix, c->startup_blockio_weight,
272 prefix, c->default_memory_min,
273 prefix, c->default_memory_low,
274 prefix, c->memory_min,
275 prefix, c->memory_low,
276 prefix, c->memory_high,
277 prefix, c->memory_max,
278 prefix, c->memory_swap_max,
279 prefix, c->memory_limit,
280 prefix, c->tasks_max,
281 prefix, cgroup_device_policy_to_string(c->device_policy),
282 prefix, strempty(disable_controllers_str),
283 prefix, yes_no(c->delegate));
284
285 if (c->delegate) {
286 _cleanup_free_ char *t = NULL;
287
288 (void) cg_mask_to_string(c->delegate_controllers, &t);
289
290 fprintf(f, "%sDelegateControllers=%s\n",
291 prefix,
292 strempty(t));
293 }
294
295 LIST_FOREACH(device_allow, a, c->device_allow)
296 fprintf(f,
297 "%sDeviceAllow=%s %s%s%s\n",
298 prefix,
299 a->path,
300 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
301
302 LIST_FOREACH(device_weights, iw, c->io_device_weights)
303 fprintf(f,
304 "%sIODeviceWeight=%s %" PRIu64 "\n",
305 prefix,
306 iw->path,
307 iw->weight);
308
309 LIST_FOREACH(device_latencies, l, c->io_device_latencies)
310 fprintf(f,
311 "%sIODeviceLatencyTargetSec=%s %s\n",
312 prefix,
313 l->path,
314 format_timespan(u, sizeof(u), l->target_usec, 1));
315
316 LIST_FOREACH(device_limits, il, c->io_device_limits) {
317 char buf[FORMAT_BYTES_MAX];
318 CGroupIOLimitType type;
319
320 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
321 if (il->limits[type] != cgroup_io_limit_defaults[type])
322 fprintf(f,
323 "%s%s=%s %s\n",
324 prefix,
325 cgroup_io_limit_type_to_string(type),
326 il->path,
327 format_bytes(buf, sizeof(buf), il->limits[type]));
328 }
329
330 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
331 fprintf(f,
332 "%sBlockIODeviceWeight=%s %" PRIu64,
333 prefix,
334 w->path,
335 w->weight);
336
337 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
338 char buf[FORMAT_BYTES_MAX];
339
340 if (b->rbps != CGROUP_LIMIT_MAX)
341 fprintf(f,
342 "%sBlockIOReadBandwidth=%s %s\n",
343 prefix,
344 b->path,
345 format_bytes(buf, sizeof(buf), b->rbps));
346 if (b->wbps != CGROUP_LIMIT_MAX)
347 fprintf(f,
348 "%sBlockIOWriteBandwidth=%s %s\n",
349 prefix,
350 b->path,
351 format_bytes(buf, sizeof(buf), b->wbps));
352 }
353
354 LIST_FOREACH(items, iaai, c->ip_address_allow) {
355 _cleanup_free_ char *k = NULL;
356
357 (void) in_addr_to_string(iaai->family, &iaai->address, &k);
358 fprintf(f, "%sIPAddressAllow=%s/%u\n", prefix, strnull(k), iaai->prefixlen);
359 }
360
361 LIST_FOREACH(items, iaai, c->ip_address_deny) {
362 _cleanup_free_ char *k = NULL;
363
364 (void) in_addr_to_string(iaai->family, &iaai->address, &k);
365 fprintf(f, "%sIPAddressDeny=%s/%u\n", prefix, strnull(k), iaai->prefixlen);
366 }
367
368 STRV_FOREACH(path, c->ip_filters_ingress)
369 fprintf(f, "%sIPIngressFilterPath=%s\n", prefix, *path);
370
371 STRV_FOREACH(path, c->ip_filters_egress)
372 fprintf(f, "%sIPEgressFilterPath=%s\n", prefix, *path);
373 }
374
375 int cgroup_add_device_allow(CGroupContext *c, const char *dev, const char *mode) {
376 _cleanup_free_ CGroupDeviceAllow *a = NULL;
377 _cleanup_free_ char *d = NULL;
378
379 assert(c);
380 assert(dev);
381 assert(isempty(mode) || in_charset(mode, "rwm"));
382
383 a = new(CGroupDeviceAllow, 1);
384 if (!a)
385 return -ENOMEM;
386
387 d = strdup(dev);
388 if (!d)
389 return -ENOMEM;
390
391 *a = (CGroupDeviceAllow) {
392 .path = TAKE_PTR(d),
393 .r = isempty(mode) || strchr(mode, 'r'),
394 .w = isempty(mode) || strchr(mode, 'w'),
395 .m = isempty(mode) || strchr(mode, 'm'),
396 };
397
398 LIST_PREPEND(device_allow, c->device_allow, a);
399 TAKE_PTR(a);
400
401 return 0;
402 }
403
404 #define UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(entry) \
405 uint64_t unit_get_ancestor_##entry(Unit *u) { \
406 CGroupContext *c; \
407 \
408 /* 1. Is entry set in this unit? If so, use that. \
409 * 2. Is the default for this entry set in any \
410 * ancestor? If so, use that. \
411 * 3. Otherwise, return CGROUP_LIMIT_MIN. */ \
412 \
413 assert(u); \
414 \
415 c = unit_get_cgroup_context(u); \
416 if (c && c->entry##_set) \
417 return c->entry; \
418 \
419 while ((u = UNIT_DEREF(u->slice))) { \
420 c = unit_get_cgroup_context(u); \
421 if (c && c->default_##entry##_set) \
422 return c->default_##entry; \
423 } \
424 \
425 /* We've reached the root, but nobody had default for \
426 * this entry set, so set it to the kernel default. */ \
427 return CGROUP_LIMIT_MIN; \
428 }
429
430 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_low);
431 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_min);
432
433 static void cgroup_xattr_apply(Unit *u) {
434 char ids[SD_ID128_STRING_MAX];
435 int r;
436
437 assert(u);
438
439 if (!MANAGER_IS_SYSTEM(u->manager))
440 return;
441
442 if (sd_id128_is_null(u->invocation_id))
443 return;
444
445 r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
446 "trusted.invocation_id",
447 sd_id128_to_string(u->invocation_id, ids), 32,
448 0);
449 if (r < 0)
450 log_unit_debug_errno(u, r, "Failed to set invocation ID on control group %s, ignoring: %m", u->cgroup_path);
451 }
452
453 static int lookup_block_device(const char *p, dev_t *ret) {
454 dev_t rdev, dev = 0;
455 mode_t mode;
456 int r;
457
458 assert(p);
459 assert(ret);
460
461 r = device_path_parse_major_minor(p, &mode, &rdev);
462 if (r == -ENODEV) { /* not a parsable device node, need to go to disk */
463 struct stat st;
464 if (stat(p, &st) < 0)
465 return log_warning_errno(errno, "Couldn't stat device '%s': %m", p);
466 rdev = (dev_t)st.st_rdev;
467 dev = (dev_t)st.st_dev;
468 mode = st.st_mode;
469 } else if (r < 0)
470 return log_warning_errno(r, "Failed to parse major/minor from path '%s': %m", p);
471
472 if (S_ISCHR(mode)) {
473 log_warning("Device node '%s' is a character device, but block device needed.", p);
474 return -ENOTBLK;
475 } else if (S_ISBLK(mode))
476 *ret = rdev;
477 else if (major(dev) != 0)
478 *ret = dev; /* If this is not a device node then use the block device this file is stored on */
479 else {
480 /* If this is btrfs, getting the backing block device is a bit harder */
481 r = btrfs_get_block_device(p, ret);
482 if (r < 0 && r != -ENOTTY)
483 return log_warning_errno(r, "Failed to determine block device backing btrfs file system '%s': %m", p);
484 if (r == -ENOTTY) {
485 log_warning("'%s' is not a block device node, and file system block device cannot be determined or is not local.", p);
486 return -ENODEV;
487 }
488 }
489
490 /* If this is a LUKS device, try to get the originating block device */
491 (void) block_get_originating(*ret, ret);
492
493 /* If this is a partition, try to get the originating block device */
494 (void) block_get_whole_disk(*ret, ret);
495 return 0;
496 }
497
498 static int whitelist_device(BPFProgram *prog, const char *path, const char *node, const char *acc) {
499 dev_t rdev;
500 mode_t mode;
501 int r;
502
503 assert(path);
504 assert(acc);
505
506 /* Some special handling for /dev/block/%u:%u, /dev/char/%u:%u, /run/systemd/inaccessible/chr and
507 * /run/systemd/inaccessible/blk paths. Instead of stat()ing these we parse out the major/minor directly. This
508 * means clients can use these path without the device node actually around */
509 r = device_path_parse_major_minor(node, &mode, &rdev);
510 if (r < 0) {
511 if (r != -ENODEV)
512 return log_warning_errno(r, "Couldn't parse major/minor from device path '%s': %m", node);
513
514 struct stat st;
515 if (stat(node, &st) < 0)
516 return log_warning_errno(errno, "Couldn't stat device %s: %m", node);
517
518 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
519 log_warning("%s is not a device.", node);
520 return -ENODEV;
521 }
522 rdev = (dev_t) st.st_rdev;
523 mode = st.st_mode;
524 }
525
526 if (cg_all_unified() > 0) {
527 if (!prog)
528 return 0;
529
530 return cgroup_bpf_whitelist_device(prog, S_ISCHR(mode) ? BPF_DEVCG_DEV_CHAR : BPF_DEVCG_DEV_BLOCK,
531 major(rdev), minor(rdev), acc);
532
533 } else {
534 char buf[2+DECIMAL_STR_MAX(dev_t)*2+2+4];
535
536 sprintf(buf,
537 "%c %u:%u %s",
538 S_ISCHR(mode) ? 'c' : 'b',
539 major(rdev), minor(rdev),
540 acc);
541
542 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore EINVAL here. */
543
544 r = cg_set_attribute("devices", path, "devices.allow", buf);
545 if (r < 0)
546 return log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING,
547 r, "Failed to set devices.allow on %s: %m", path);
548
549 return 0;
550 }
551 }
552
553 static int whitelist_major(BPFProgram *prog, const char *path, const char *name, char type, const char *acc) {
554 _cleanup_fclose_ FILE *f = NULL;
555 char buf[2+DECIMAL_STR_MAX(unsigned)+3+4];
556 bool good = false;
557 unsigned maj;
558 int r;
559
560 assert(path);
561 assert(acc);
562 assert(IN_SET(type, 'b', 'c'));
563
564 if (streq(name, "*")) {
565 /* If the name is a wildcard, then apply this list to all devices of this type */
566
567 if (cg_all_unified() > 0) {
568 if (!prog)
569 return 0;
570
571 (void) cgroup_bpf_whitelist_class(prog, type == 'c' ? BPF_DEVCG_DEV_CHAR : BPF_DEVCG_DEV_BLOCK, acc);
572 } else {
573 xsprintf(buf, "%c *:* %s", type, acc);
574
575 r = cg_set_attribute("devices", path, "devices.allow", buf);
576 if (r < 0)
577 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
578 "Failed to set devices.allow on %s: %m", path);
579 return 0;
580 }
581 }
582
583 if (safe_atou(name, &maj) >= 0 && DEVICE_MAJOR_VALID(maj)) {
584 /* The name is numeric and suitable as major. In that case, let's take is major, and create the entry
585 * directly */
586
587 if (cg_all_unified() > 0) {
588 if (!prog)
589 return 0;
590
591 (void) cgroup_bpf_whitelist_major(prog,
592 type == 'c' ? BPF_DEVCG_DEV_CHAR : BPF_DEVCG_DEV_BLOCK,
593 maj, acc);
594 } else {
595 xsprintf(buf, "%c %u:* %s", type, maj, acc);
596
597 r = cg_set_attribute("devices", path, "devices.allow", buf);
598 if (r < 0)
599 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
600 "Failed to set devices.allow on %s: %m", path);
601 }
602
603 return 0;
604 }
605
606 f = fopen("/proc/devices", "re");
607 if (!f)
608 return log_warning_errno(errno, "Cannot open /proc/devices to resolve %s (%c): %m", name, type);
609
610 for (;;) {
611 _cleanup_free_ char *line = NULL;
612 char *w, *p;
613
614 r = read_line(f, LONG_LINE_MAX, &line);
615 if (r < 0)
616 return log_warning_errno(r, "Failed to read /proc/devices: %m");
617 if (r == 0)
618 break;
619
620 if (type == 'c' && streq(line, "Character devices:")) {
621 good = true;
622 continue;
623 }
624
625 if (type == 'b' && streq(line, "Block devices:")) {
626 good = true;
627 continue;
628 }
629
630 if (isempty(line)) {
631 good = false;
632 continue;
633 }
634
635 if (!good)
636 continue;
637
638 p = strstrip(line);
639
640 w = strpbrk(p, WHITESPACE);
641 if (!w)
642 continue;
643 *w = 0;
644
645 r = safe_atou(p, &maj);
646 if (r < 0)
647 continue;
648 if (maj <= 0)
649 continue;
650
651 w++;
652 w += strspn(w, WHITESPACE);
653
654 if (fnmatch(name, w, 0) != 0)
655 continue;
656
657 if (cg_all_unified() > 0) {
658 if (!prog)
659 continue;
660
661 (void) cgroup_bpf_whitelist_major(prog,
662 type == 'c' ? BPF_DEVCG_DEV_CHAR : BPF_DEVCG_DEV_BLOCK,
663 maj, acc);
664 } else {
665 sprintf(buf,
666 "%c %u:* %s",
667 type,
668 maj,
669 acc);
670
671 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore EINVAL
672 * here. */
673
674 r = cg_set_attribute("devices", path, "devices.allow", buf);
675 if (r < 0)
676 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING,
677 r, "Failed to set devices.allow on %s: %m", path);
678 }
679 }
680
681 return 0;
682 }
683
684 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
685 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
686 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
687 }
688
689 static bool cgroup_context_has_cpu_shares(CGroupContext *c) {
690 return c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
691 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID;
692 }
693
694 static uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
695 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
696 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
697 return c->startup_cpu_weight;
698 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
699 return c->cpu_weight;
700 else
701 return CGROUP_WEIGHT_DEFAULT;
702 }
703
704 static uint64_t cgroup_context_cpu_shares(CGroupContext *c, ManagerState state) {
705 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
706 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID)
707 return c->startup_cpu_shares;
708 else if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID)
709 return c->cpu_shares;
710 else
711 return CGROUP_CPU_SHARES_DEFAULT;
712 }
713
714 usec_t cgroup_cpu_adjust_period(usec_t period, usec_t quota, usec_t resolution, usec_t max_period) {
715 /* kernel uses a minimum resolution of 1ms, so both period and (quota * period)
716 * need to be higher than that boundary. quota is specified in USecPerSec.
717 * Additionally, period must be at most max_period. */
718 assert(quota > 0);
719
720 return MIN(MAX3(period, resolution, resolution * USEC_PER_SEC / quota), max_period);
721 }
722
723 static usec_t cgroup_cpu_adjust_period_and_log(Unit *u, usec_t period, usec_t quota) {
724 usec_t new_period;
725
726 if (quota == USEC_INFINITY)
727 /* Always use default period for infinity quota. */
728 return CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
729
730 if (period == USEC_INFINITY)
731 /* Default period was requested. */
732 period = CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
733
734 /* Clamp to interval [1ms, 1s] */
735 new_period = cgroup_cpu_adjust_period(period, quota, USEC_PER_MSEC, USEC_PER_SEC);
736
737 if (new_period != period) {
738 char v[FORMAT_TIMESPAN_MAX];
739 log_unit_full(u, u->warned_clamping_cpu_quota_period ? LOG_DEBUG : LOG_WARNING, 0,
740 "Clamping CPU interval for cpu.max: period is now %s",
741 format_timespan(v, sizeof(v), new_period, 1));
742 u->warned_clamping_cpu_quota_period = true;
743 }
744
745 return new_period;
746 }
747
748 static void cgroup_apply_unified_cpu_weight(Unit *u, uint64_t weight) {
749 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
750
751 xsprintf(buf, "%" PRIu64 "\n", weight);
752 (void) set_attribute_and_warn(u, "cpu", "cpu.weight", buf);
753 }
754
755 static void cgroup_apply_unified_cpu_quota(Unit *u, usec_t quota, usec_t period) {
756 char buf[(DECIMAL_STR_MAX(usec_t) + 1) * 2 + 1];
757
758 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
759 if (quota != USEC_INFINITY)
760 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
761 MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC), period);
762 else
763 xsprintf(buf, "max " USEC_FMT "\n", period);
764 (void) set_attribute_and_warn(u, "cpu", "cpu.max", buf);
765 }
766
767 static void cgroup_apply_legacy_cpu_shares(Unit *u, uint64_t shares) {
768 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
769
770 xsprintf(buf, "%" PRIu64 "\n", shares);
771 (void) set_attribute_and_warn(u, "cpu", "cpu.shares", buf);
772 }
773
774 static void cgroup_apply_legacy_cpu_quota(Unit *u, usec_t quota, usec_t period) {
775 char buf[DECIMAL_STR_MAX(usec_t) + 2];
776
777 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
778
779 xsprintf(buf, USEC_FMT "\n", period);
780 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_period_us", buf);
781
782 if (quota != USEC_INFINITY) {
783 xsprintf(buf, USEC_FMT "\n", MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC));
784 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", buf);
785 } else
786 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", "-1\n");
787 }
788
789 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares) {
790 return CLAMP(shares * CGROUP_WEIGHT_DEFAULT / CGROUP_CPU_SHARES_DEFAULT,
791 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
792 }
793
794 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight) {
795 return CLAMP(weight * CGROUP_CPU_SHARES_DEFAULT / CGROUP_WEIGHT_DEFAULT,
796 CGROUP_CPU_SHARES_MIN, CGROUP_CPU_SHARES_MAX);
797 }
798
799 static bool cgroup_context_has_io_config(CGroupContext *c) {
800 return c->io_accounting ||
801 c->io_weight != CGROUP_WEIGHT_INVALID ||
802 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
803 c->io_device_weights ||
804 c->io_device_latencies ||
805 c->io_device_limits;
806 }
807
808 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
809 return c->blockio_accounting ||
810 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
811 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
812 c->blockio_device_weights ||
813 c->blockio_device_bandwidths;
814 }
815
816 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
817 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
818 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
819 return c->startup_io_weight;
820 else if (c->io_weight != CGROUP_WEIGHT_INVALID)
821 return c->io_weight;
822 else
823 return CGROUP_WEIGHT_DEFAULT;
824 }
825
826 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
827 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
828 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
829 return c->startup_blockio_weight;
830 else if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
831 return c->blockio_weight;
832 else
833 return CGROUP_BLKIO_WEIGHT_DEFAULT;
834 }
835
836 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
837 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
838 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
839 }
840
841 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
842 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
843 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
844 }
845
846 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
847 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
848 dev_t dev;
849 int r;
850
851 r = lookup_block_device(dev_path, &dev);
852 if (r < 0)
853 return;
854
855 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), io_weight);
856 (void) set_attribute_and_warn(u, "io", "io.weight", buf);
857 }
858
859 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
860 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
861 dev_t dev;
862 int r;
863
864 r = lookup_block_device(dev_path, &dev);
865 if (r < 0)
866 return;
867
868 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), blkio_weight);
869 (void) set_attribute_and_warn(u, "blkio", "blkio.weight_device", buf);
870 }
871
872 static void cgroup_apply_io_device_latency(Unit *u, const char *dev_path, usec_t target) {
873 char buf[DECIMAL_STR_MAX(dev_t)*2+2+7+DECIMAL_STR_MAX(uint64_t)+1];
874 dev_t dev;
875 int r;
876
877 r = lookup_block_device(dev_path, &dev);
878 if (r < 0)
879 return;
880
881 if (target != USEC_INFINITY)
882 xsprintf(buf, "%u:%u target=%" PRIu64 "\n", major(dev), minor(dev), target);
883 else
884 xsprintf(buf, "%u:%u target=max\n", major(dev), minor(dev));
885
886 (void) set_attribute_and_warn(u, "io", "io.latency", buf);
887 }
888
889 static void cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
890 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)];
891 char buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
892 CGroupIOLimitType type;
893 dev_t dev;
894 int r;
895
896 r = lookup_block_device(dev_path, &dev);
897 if (r < 0)
898 return;
899
900 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
901 if (limits[type] != cgroup_io_limit_defaults[type])
902 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
903 else
904 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
905
906 xsprintf(buf, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev), minor(dev),
907 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
908 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
909 (void) set_attribute_and_warn(u, "io", "io.max", buf);
910 }
911
912 static void cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
913 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
914 dev_t dev;
915 int r;
916
917 r = lookup_block_device(dev_path, &dev);
918 if (r < 0)
919 return;
920
921 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), rbps);
922 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.read_bps_device", buf);
923
924 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), wbps);
925 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.write_bps_device", buf);
926 }
927
928 static bool unit_has_unified_memory_config(Unit *u) {
929 CGroupContext *c;
930
931 assert(u);
932
933 c = unit_get_cgroup_context(u);
934 assert(c);
935
936 return c->memory_min > 0 || unit_get_ancestor_memory_low(u) > 0 ||
937 c->memory_high != CGROUP_LIMIT_MAX || c->memory_max != CGROUP_LIMIT_MAX ||
938 c->memory_swap_max != CGROUP_LIMIT_MAX;
939 }
940
941 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
942 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max\n";
943
944 if (v != CGROUP_LIMIT_MAX)
945 xsprintf(buf, "%" PRIu64 "\n", v);
946
947 (void) set_attribute_and_warn(u, "memory", file, buf);
948 }
949
950 static void cgroup_apply_firewall(Unit *u) {
951 assert(u);
952
953 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
954
955 if (bpf_firewall_compile(u) < 0)
956 return;
957
958 (void) bpf_firewall_load_custom(u);
959 (void) bpf_firewall_install(u);
960 }
961
962 static void cgroup_context_apply(
963 Unit *u,
964 CGroupMask apply_mask,
965 ManagerState state) {
966
967 const char *path;
968 CGroupContext *c;
969 bool is_host_root, is_local_root;
970 int r;
971
972 assert(u);
973
974 /* Nothing to do? Exit early! */
975 if (apply_mask == 0)
976 return;
977
978 /* Some cgroup attributes are not supported on the host root cgroup, hence silently ignore them here. And other
979 * attributes should only be managed for cgroups further down the tree. */
980 is_local_root = unit_has_name(u, SPECIAL_ROOT_SLICE);
981 is_host_root = unit_has_host_root_cgroup(u);
982
983 assert_se(c = unit_get_cgroup_context(u));
984 assert_se(path = u->cgroup_path);
985
986 if (is_local_root) /* Make sure we don't try to display messages with an empty path. */
987 path = "/";
988
989 /* We generally ignore errors caused by read-only mounted cgroup trees (assuming we are running in a container
990 * then), and missing cgroups, i.e. EROFS and ENOENT. */
991
992 /* In fully unified mode these attributes don't exist on the host cgroup root. On legacy the weights exist, but
993 * setting the weight makes very little sense on the host root cgroup, as there are no other cgroups at this
994 * level. The quota exists there too, but any attempt to write to it is refused with EINVAL. Inside of
995 * containers we want to leave control of these to the container manager (and if cgroup v2 delegation is used
996 * we couldn't even write to them if we wanted to). */
997 if ((apply_mask & CGROUP_MASK_CPU) && !is_local_root) {
998
999 if (cg_all_unified() > 0) {
1000 uint64_t weight;
1001
1002 if (cgroup_context_has_cpu_weight(c))
1003 weight = cgroup_context_cpu_weight(c, state);
1004 else if (cgroup_context_has_cpu_shares(c)) {
1005 uint64_t shares;
1006
1007 shares = cgroup_context_cpu_shares(c, state);
1008 weight = cgroup_cpu_shares_to_weight(shares);
1009
1010 log_cgroup_compat(u, "Applying [Startup]CPUShares=%" PRIu64 " as [Startup]CPUWeight=%" PRIu64 " on %s",
1011 shares, weight, path);
1012 } else
1013 weight = CGROUP_WEIGHT_DEFAULT;
1014
1015 cgroup_apply_unified_cpu_weight(u, weight);
1016 cgroup_apply_unified_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
1017
1018 } else {
1019 uint64_t shares;
1020
1021 if (cgroup_context_has_cpu_weight(c)) {
1022 uint64_t weight;
1023
1024 weight = cgroup_context_cpu_weight(c, state);
1025 shares = cgroup_cpu_weight_to_shares(weight);
1026
1027 log_cgroup_compat(u, "Applying [Startup]CPUWeight=%" PRIu64 " as [Startup]CPUShares=%" PRIu64 " on %s",
1028 weight, shares, path);
1029 } else if (cgroup_context_has_cpu_shares(c))
1030 shares = cgroup_context_cpu_shares(c, state);
1031 else
1032 shares = CGROUP_CPU_SHARES_DEFAULT;
1033
1034 cgroup_apply_legacy_cpu_shares(u, shares);
1035 cgroup_apply_legacy_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
1036 }
1037 }
1038
1039 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroup v2
1040 * controller), and in case of containers we want to leave control of these attributes to the container manager
1041 * (and we couldn't access that stuff anyway, even if we tried if proper delegation is used). */
1042 if ((apply_mask & CGROUP_MASK_IO) && !is_local_root) {
1043 char buf[8+DECIMAL_STR_MAX(uint64_t)+1];
1044 bool has_io, has_blockio;
1045 uint64_t weight;
1046
1047 has_io = cgroup_context_has_io_config(c);
1048 has_blockio = cgroup_context_has_blockio_config(c);
1049
1050 if (has_io)
1051 weight = cgroup_context_io_weight(c, state);
1052 else if (has_blockio) {
1053 uint64_t blkio_weight;
1054
1055 blkio_weight = cgroup_context_blkio_weight(c, state);
1056 weight = cgroup_weight_blkio_to_io(blkio_weight);
1057
1058 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight=%" PRIu64 " as [Startup]IOWeight=%" PRIu64,
1059 blkio_weight, weight);
1060 } else
1061 weight = CGROUP_WEIGHT_DEFAULT;
1062
1063 xsprintf(buf, "default %" PRIu64 "\n", weight);
1064 (void) set_attribute_and_warn(u, "io", "io.weight", buf);
1065
1066 if (has_io) {
1067 CGroupIODeviceLatency *latency;
1068 CGroupIODeviceLimit *limit;
1069 CGroupIODeviceWeight *w;
1070
1071 LIST_FOREACH(device_weights, w, c->io_device_weights)
1072 cgroup_apply_io_device_weight(u, w->path, w->weight);
1073
1074 LIST_FOREACH(device_limits, limit, c->io_device_limits)
1075 cgroup_apply_io_device_limit(u, limit->path, limit->limits);
1076
1077 LIST_FOREACH(device_latencies, latency, c->io_device_latencies)
1078 cgroup_apply_io_device_latency(u, latency->path, latency->target_usec);
1079
1080 } else if (has_blockio) {
1081 CGroupBlockIODeviceWeight *w;
1082 CGroupBlockIODeviceBandwidth *b;
1083
1084 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
1085 weight = cgroup_weight_blkio_to_io(w->weight);
1086
1087 log_cgroup_compat(u, "Applying BlockIODeviceWeight=%" PRIu64 " as IODeviceWeight=%" PRIu64 " for %s",
1088 w->weight, weight, w->path);
1089
1090 cgroup_apply_io_device_weight(u, w->path, weight);
1091 }
1092
1093 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
1094 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
1095 CGroupIOLimitType type;
1096
1097 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
1098 limits[type] = cgroup_io_limit_defaults[type];
1099
1100 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
1101 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
1102
1103 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax= for %s",
1104 b->rbps, b->wbps, b->path);
1105
1106 cgroup_apply_io_device_limit(u, b->path, limits);
1107 }
1108 }
1109 }
1110
1111 if (apply_mask & CGROUP_MASK_BLKIO) {
1112 bool has_io, has_blockio;
1113
1114 has_io = cgroup_context_has_io_config(c);
1115 has_blockio = cgroup_context_has_blockio_config(c);
1116
1117 /* Applying a 'weight' never makes sense for the host root cgroup, and for containers this should be
1118 * left to our container manager, too. */
1119 if (!is_local_root) {
1120 char buf[DECIMAL_STR_MAX(uint64_t)+1];
1121 uint64_t weight;
1122
1123 if (has_io) {
1124 uint64_t io_weight;
1125
1126 io_weight = cgroup_context_io_weight(c, state);
1127 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
1128
1129 log_cgroup_compat(u, "Applying [Startup]IOWeight=%" PRIu64 " as [Startup]BlockIOWeight=%" PRIu64,
1130 io_weight, weight);
1131 } else if (has_blockio)
1132 weight = cgroup_context_blkio_weight(c, state);
1133 else
1134 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
1135
1136 xsprintf(buf, "%" PRIu64 "\n", weight);
1137 (void) set_attribute_and_warn(u, "blkio", "blkio.weight", buf);
1138
1139 if (has_io) {
1140 CGroupIODeviceWeight *w;
1141
1142 LIST_FOREACH(device_weights, w, c->io_device_weights) {
1143 weight = cgroup_weight_io_to_blkio(w->weight);
1144
1145 log_cgroup_compat(u, "Applying IODeviceWeight=%" PRIu64 " as BlockIODeviceWeight=%" PRIu64 " for %s",
1146 w->weight, weight, w->path);
1147
1148 cgroup_apply_blkio_device_weight(u, w->path, weight);
1149 }
1150 } else if (has_blockio) {
1151 CGroupBlockIODeviceWeight *w;
1152
1153 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
1154 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
1155 }
1156 }
1157
1158 /* The bandwidth limits are something that make sense to be applied to the host's root but not container
1159 * roots, as there we want the container manager to handle it */
1160 if (is_host_root || !is_local_root) {
1161 if (has_io) {
1162 CGroupIODeviceLimit *l;
1163
1164 LIST_FOREACH(device_limits, l, c->io_device_limits) {
1165 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax= for %s",
1166 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
1167
1168 cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]);
1169 }
1170 } else if (has_blockio) {
1171 CGroupBlockIODeviceBandwidth *b;
1172
1173 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
1174 cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps);
1175 }
1176 }
1177 }
1178
1179 /* In unified mode 'memory' attributes do not exist on the root cgroup. In legacy mode 'memory.limit_in_bytes'
1180 * exists on the root cgroup, but any writes to it are refused with EINVAL. And if we run in a container we
1181 * want to leave control to the container manager (and if proper cgroup v2 delegation is used we couldn't even
1182 * write to this if we wanted to.) */
1183 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_local_root) {
1184
1185 if (cg_all_unified() > 0) {
1186 uint64_t max, swap_max = CGROUP_LIMIT_MAX;
1187
1188 if (unit_has_unified_memory_config(u)) {
1189 max = c->memory_max;
1190 swap_max = c->memory_swap_max;
1191 } else {
1192 max = c->memory_limit;
1193
1194 if (max != CGROUP_LIMIT_MAX)
1195 log_cgroup_compat(u, "Applying MemoryLimit=%" PRIu64 " as MemoryMax=", max);
1196 }
1197
1198 cgroup_apply_unified_memory_limit(u, "memory.min", c->memory_min);
1199 cgroup_apply_unified_memory_limit(u, "memory.low", unit_get_ancestor_memory_low(u));
1200 cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
1201 cgroup_apply_unified_memory_limit(u, "memory.max", max);
1202 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
1203
1204 (void) set_attribute_and_warn(u, "memory", "memory.oom.group", one_zero(c->memory_oom_group));
1205
1206 } else {
1207 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
1208 uint64_t val;
1209
1210 if (unit_has_unified_memory_config(u)) {
1211 val = c->memory_max;
1212 log_cgroup_compat(u, "Applying MemoryMax=%" PRIi64 " as MemoryLimit=", val);
1213 } else
1214 val = c->memory_limit;
1215
1216 if (val == CGROUP_LIMIT_MAX)
1217 strncpy(buf, "-1\n", sizeof(buf));
1218 else
1219 xsprintf(buf, "%" PRIu64 "\n", val);
1220
1221 (void) set_attribute_and_warn(u, "memory", "memory.limit_in_bytes", buf);
1222 }
1223 }
1224
1225 /* On cgroup v2 we can apply BPF everywhere. On cgroup v1 we apply it everywhere except for the root of
1226 * containers, where we leave this to the manager */
1227 if ((apply_mask & (CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES)) &&
1228 (is_host_root || cg_all_unified() > 0 || !is_local_root)) {
1229 _cleanup_(bpf_program_unrefp) BPFProgram *prog = NULL;
1230 CGroupDeviceAllow *a;
1231
1232 if (cg_all_unified() > 0) {
1233 r = cgroup_init_device_bpf(&prog, c->device_policy, c->device_allow);
1234 if (r < 0)
1235 log_unit_warning_errno(u, r, "Failed to initialize device control bpf program: %m");
1236 } else {
1237 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore EINVAL
1238 * here. */
1239
1240 if (c->device_allow || c->device_policy != CGROUP_AUTO)
1241 r = cg_set_attribute("devices", path, "devices.deny", "a");
1242 else
1243 r = cg_set_attribute("devices", path, "devices.allow", "a");
1244 if (r < 0)
1245 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING, r,
1246 "Failed to reset devices.allow/devices.deny: %m");
1247 }
1248
1249 if (c->device_policy == CGROUP_CLOSED ||
1250 (c->device_policy == CGROUP_AUTO && c->device_allow)) {
1251 static const char auto_devices[] =
1252 "/dev/null\0" "rwm\0"
1253 "/dev/zero\0" "rwm\0"
1254 "/dev/full\0" "rwm\0"
1255 "/dev/random\0" "rwm\0"
1256 "/dev/urandom\0" "rwm\0"
1257 "/dev/tty\0" "rwm\0"
1258 "/dev/ptmx\0" "rwm\0"
1259 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
1260 "/run/systemd/inaccessible/chr\0" "rwm\0"
1261 "/run/systemd/inaccessible/blk\0" "rwm\0";
1262
1263 const char *x, *y;
1264
1265 NULSTR_FOREACH_PAIR(x, y, auto_devices)
1266 (void) whitelist_device(prog, path, x, y);
1267
1268 /* PTS (/dev/pts) devices may not be duplicated, but accessed */
1269 (void) whitelist_major(prog, path, "pts", 'c', "rw");
1270 }
1271
1272 LIST_FOREACH(device_allow, a, c->device_allow) {
1273 char acc[4], *val;
1274 unsigned k = 0;
1275
1276 if (a->r)
1277 acc[k++] = 'r';
1278 if (a->w)
1279 acc[k++] = 'w';
1280 if (a->m)
1281 acc[k++] = 'm';
1282
1283 if (k == 0)
1284 continue;
1285
1286 acc[k++] = 0;
1287
1288 if (path_startswith(a->path, "/dev/"))
1289 (void) whitelist_device(prog, path, a->path, acc);
1290 else if ((val = startswith(a->path, "block-")))
1291 (void) whitelist_major(prog, path, val, 'b', acc);
1292 else if ((val = startswith(a->path, "char-")))
1293 (void) whitelist_major(prog, path, val, 'c', acc);
1294 else
1295 log_unit_debug(u, "Ignoring device '%s' while writing cgroup attribute.", a->path);
1296 }
1297
1298 r = cgroup_apply_device_bpf(u, prog, c->device_policy, c->device_allow);
1299 if (r < 0) {
1300 static bool warned = false;
1301
1302 log_full_errno(warned ? LOG_DEBUG : LOG_WARNING, r,
1303 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1304 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1305 "(This warning is only shown for the first loaded unit using device ACL.)", u->id);
1306
1307 warned = true;
1308 }
1309 }
1310
1311 if (apply_mask & CGROUP_MASK_PIDS) {
1312
1313 if (is_host_root) {
1314 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1315 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1316 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1317 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1318 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1319 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1320 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1321 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1322 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1323 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1324 * which is desirable so that there's an official way to release control of the sysctl from
1325 * systemd: set the limit to unbounded and reload. */
1326
1327 if (c->tasks_max != CGROUP_LIMIT_MAX) {
1328 u->manager->sysctl_pid_max_changed = true;
1329 r = procfs_tasks_set_limit(c->tasks_max);
1330 } else if (u->manager->sysctl_pid_max_changed)
1331 r = procfs_tasks_set_limit(TASKS_MAX);
1332 else
1333 r = 0;
1334 if (r < 0)
1335 log_unit_full(u, LOG_LEVEL_CGROUP_WRITE(r), r,
1336 "Failed to write to tasks limit sysctls: %m");
1337 }
1338
1339 /* The attribute itself is not available on the host root cgroup, and in the container case we want to
1340 * leave it for the container manager. */
1341 if (!is_local_root) {
1342 if (c->tasks_max != CGROUP_LIMIT_MAX) {
1343 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1344
1345 sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
1346 (void) set_attribute_and_warn(u, "pids", "pids.max", buf);
1347 } else
1348 (void) set_attribute_and_warn(u, "pids", "pids.max", "max\n");
1349 }
1350 }
1351
1352 if (apply_mask & CGROUP_MASK_BPF_FIREWALL)
1353 cgroup_apply_firewall(u);
1354 }
1355
1356 static bool unit_get_needs_bpf_firewall(Unit *u) {
1357 CGroupContext *c;
1358 Unit *p;
1359 assert(u);
1360
1361 c = unit_get_cgroup_context(u);
1362 if (!c)
1363 return false;
1364
1365 if (c->ip_accounting ||
1366 c->ip_address_allow ||
1367 c->ip_address_deny ||
1368 c->ip_filters_ingress ||
1369 c->ip_filters_egress)
1370 return true;
1371
1372 /* If any parent slice has an IP access list defined, it applies too */
1373 for (p = UNIT_DEREF(u->slice); p; p = UNIT_DEREF(p->slice)) {
1374 c = unit_get_cgroup_context(p);
1375 if (!c)
1376 return false;
1377
1378 if (c->ip_address_allow ||
1379 c->ip_address_deny)
1380 return true;
1381 }
1382
1383 return false;
1384 }
1385
1386 static CGroupMask unit_get_cgroup_mask(Unit *u) {
1387 CGroupMask mask = 0;
1388 CGroupContext *c;
1389
1390 assert(u);
1391
1392 c = unit_get_cgroup_context(u);
1393
1394 assert(c);
1395
1396 /* Figure out which controllers we need, based on the cgroup context object */
1397
1398 if (c->cpu_accounting)
1399 mask |= get_cpu_accounting_mask();
1400
1401 if (cgroup_context_has_cpu_weight(c) ||
1402 cgroup_context_has_cpu_shares(c) ||
1403 c->cpu_quota_per_sec_usec != USEC_INFINITY)
1404 mask |= CGROUP_MASK_CPU;
1405
1406 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
1407 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
1408
1409 if (c->memory_accounting ||
1410 c->memory_limit != CGROUP_LIMIT_MAX ||
1411 unit_has_unified_memory_config(u))
1412 mask |= CGROUP_MASK_MEMORY;
1413
1414 if (c->device_allow ||
1415 c->device_policy != CGROUP_AUTO)
1416 mask |= CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES;
1417
1418 if (c->tasks_accounting ||
1419 c->tasks_max != CGROUP_LIMIT_MAX)
1420 mask |= CGROUP_MASK_PIDS;
1421
1422 return CGROUP_MASK_EXTEND_JOINED(mask);
1423 }
1424
1425 static CGroupMask unit_get_bpf_mask(Unit *u) {
1426 CGroupMask mask = 0;
1427
1428 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
1429 * too. */
1430
1431 if (unit_get_needs_bpf_firewall(u))
1432 mask |= CGROUP_MASK_BPF_FIREWALL;
1433
1434 return mask;
1435 }
1436
1437 CGroupMask unit_get_own_mask(Unit *u) {
1438 CGroupContext *c;
1439
1440 /* Returns the mask of controllers the unit needs for itself. If a unit is not properly loaded, return an empty
1441 * mask, as we shouldn't reflect it in the cgroup hierarchy then. */
1442
1443 if (u->load_state != UNIT_LOADED)
1444 return 0;
1445
1446 c = unit_get_cgroup_context(u);
1447 if (!c)
1448 return 0;
1449
1450 return (unit_get_cgroup_mask(u) | unit_get_bpf_mask(u) | unit_get_delegate_mask(u)) & ~unit_get_ancestor_disable_mask(u);
1451 }
1452
1453 CGroupMask unit_get_delegate_mask(Unit *u) {
1454 CGroupContext *c;
1455
1456 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1457 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
1458 *
1459 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1460
1461 if (!unit_cgroup_delegate(u))
1462 return 0;
1463
1464 if (cg_all_unified() <= 0) {
1465 ExecContext *e;
1466
1467 e = unit_get_exec_context(u);
1468 if (e && !exec_context_maintains_privileges(e))
1469 return 0;
1470 }
1471
1472 assert_se(c = unit_get_cgroup_context(u));
1473 return CGROUP_MASK_EXTEND_JOINED(c->delegate_controllers);
1474 }
1475
1476 CGroupMask unit_get_members_mask(Unit *u) {
1477 assert(u);
1478
1479 /* Returns the mask of controllers all of the unit's children require, merged */
1480
1481 if (u->cgroup_members_mask_valid)
1482 return u->cgroup_members_mask; /* Use cached value if possible */
1483
1484 u->cgroup_members_mask = 0;
1485
1486 if (u->type == UNIT_SLICE) {
1487 void *v;
1488 Unit *member;
1489 Iterator i;
1490
1491 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE], i) {
1492 if (UNIT_DEREF(member->slice) == u)
1493 u->cgroup_members_mask |= unit_get_subtree_mask(member); /* note that this calls ourselves again, for the children */
1494 }
1495 }
1496
1497 u->cgroup_members_mask_valid = true;
1498 return u->cgroup_members_mask;
1499 }
1500
1501 CGroupMask unit_get_siblings_mask(Unit *u) {
1502 assert(u);
1503
1504 /* Returns the mask of controllers all of the unit's siblings
1505 * require, i.e. the members mask of the unit's parent slice
1506 * if there is one. */
1507
1508 if (UNIT_ISSET(u->slice))
1509 return unit_get_members_mask(UNIT_DEREF(u->slice));
1510
1511 return unit_get_subtree_mask(u); /* we are the top-level slice */
1512 }
1513
1514 CGroupMask unit_get_disable_mask(Unit *u) {
1515 CGroupContext *c;
1516
1517 c = unit_get_cgroup_context(u);
1518 if (!c)
1519 return 0;
1520
1521 return c->disable_controllers;
1522 }
1523
1524 CGroupMask unit_get_ancestor_disable_mask(Unit *u) {
1525 CGroupMask mask;
1526
1527 assert(u);
1528 mask = unit_get_disable_mask(u);
1529
1530 /* Returns the mask of controllers which are marked as forcibly
1531 * disabled in any ancestor unit or the unit in question. */
1532
1533 if (UNIT_ISSET(u->slice))
1534 mask |= unit_get_ancestor_disable_mask(UNIT_DEREF(u->slice));
1535
1536 return mask;
1537 }
1538
1539 CGroupMask unit_get_subtree_mask(Unit *u) {
1540
1541 /* Returns the mask of this subtree, meaning of the group
1542 * itself and its children. */
1543
1544 return unit_get_own_mask(u) | unit_get_members_mask(u);
1545 }
1546
1547 CGroupMask unit_get_target_mask(Unit *u) {
1548 CGroupMask mask;
1549
1550 /* This returns the cgroup mask of all controllers to enable
1551 * for a specific cgroup, i.e. everything it needs itself,
1552 * plus all that its children need, plus all that its siblings
1553 * need. This is primarily useful on the legacy cgroup
1554 * hierarchy, where we need to duplicate each cgroup in each
1555 * hierarchy that shall be enabled for it. */
1556
1557 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
1558
1559 if (mask & CGROUP_MASK_BPF_FIREWALL & ~u->manager->cgroup_supported)
1560 emit_bpf_firewall_warning(u);
1561
1562 mask &= u->manager->cgroup_supported;
1563 mask &= ~unit_get_ancestor_disable_mask(u);
1564
1565 return mask;
1566 }
1567
1568 CGroupMask unit_get_enable_mask(Unit *u) {
1569 CGroupMask mask;
1570
1571 /* This returns the cgroup mask of all controllers to enable
1572 * for the children of a specific cgroup. This is primarily
1573 * useful for the unified cgroup hierarchy, where each cgroup
1574 * controls which controllers are enabled for its children. */
1575
1576 mask = unit_get_members_mask(u);
1577 mask &= u->manager->cgroup_supported;
1578 mask &= ~unit_get_ancestor_disable_mask(u);
1579
1580 return mask;
1581 }
1582
1583 void unit_invalidate_cgroup_members_masks(Unit *u) {
1584 assert(u);
1585
1586 /* Recurse invalidate the member masks cache all the way up the tree */
1587 u->cgroup_members_mask_valid = false;
1588
1589 if (UNIT_ISSET(u->slice))
1590 unit_invalidate_cgroup_members_masks(UNIT_DEREF(u->slice));
1591 }
1592
1593 const char *unit_get_realized_cgroup_path(Unit *u, CGroupMask mask) {
1594
1595 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
1596
1597 while (u) {
1598
1599 if (u->cgroup_path &&
1600 u->cgroup_realized &&
1601 FLAGS_SET(u->cgroup_realized_mask, mask))
1602 return u->cgroup_path;
1603
1604 u = UNIT_DEREF(u->slice);
1605 }
1606
1607 return NULL;
1608 }
1609
1610 static const char *migrate_callback(CGroupMask mask, void *userdata) {
1611 return unit_get_realized_cgroup_path(userdata, mask);
1612 }
1613
1614 char *unit_default_cgroup_path(const Unit *u) {
1615 _cleanup_free_ char *escaped = NULL, *slice = NULL;
1616 int r;
1617
1618 assert(u);
1619
1620 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1621 return strdup(u->manager->cgroup_root);
1622
1623 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1624 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1625 if (r < 0)
1626 return NULL;
1627 }
1628
1629 escaped = cg_escape(u->id);
1630 if (!escaped)
1631 return NULL;
1632
1633 return path_join(empty_to_root(u->manager->cgroup_root), slice, escaped);
1634 }
1635
1636 int unit_set_cgroup_path(Unit *u, const char *path) {
1637 _cleanup_free_ char *p = NULL;
1638 int r;
1639
1640 assert(u);
1641
1642 if (streq_ptr(u->cgroup_path, path))
1643 return 0;
1644
1645 if (path) {
1646 p = strdup(path);
1647 if (!p)
1648 return -ENOMEM;
1649 }
1650
1651 if (p) {
1652 r = hashmap_put(u->manager->cgroup_unit, p, u);
1653 if (r < 0)
1654 return r;
1655 }
1656
1657 unit_release_cgroup(u);
1658 u->cgroup_path = TAKE_PTR(p);
1659
1660 return 1;
1661 }
1662
1663 int unit_watch_cgroup(Unit *u) {
1664 _cleanup_free_ char *events = NULL;
1665 int r;
1666
1667 assert(u);
1668
1669 /* Watches the "cgroups.events" attribute of this unit's cgroup for "empty" events, but only if
1670 * cgroupv2 is available. */
1671
1672 if (!u->cgroup_path)
1673 return 0;
1674
1675 if (u->cgroup_control_inotify_wd >= 0)
1676 return 0;
1677
1678 /* Only applies to the unified hierarchy */
1679 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1680 if (r < 0)
1681 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1682 if (r == 0)
1683 return 0;
1684
1685 /* No point in watch the top-level slice, it's never going to run empty. */
1686 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1687 return 0;
1688
1689 r = hashmap_ensure_allocated(&u->manager->cgroup_control_inotify_wd_unit, &trivial_hash_ops);
1690 if (r < 0)
1691 return log_oom();
1692
1693 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1694 if (r < 0)
1695 return log_oom();
1696
1697 u->cgroup_control_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1698 if (u->cgroup_control_inotify_wd < 0) {
1699
1700 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
1701 * is not an error */
1702 return 0;
1703
1704 return log_unit_error_errno(u, errno, "Failed to add control inotify watch descriptor for control group %s: %m", u->cgroup_path);
1705 }
1706
1707 r = hashmap_put(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd), u);
1708 if (r < 0)
1709 return log_unit_error_errno(u, r, "Failed to add control inotify watch descriptor to hash map: %m");
1710
1711 return 0;
1712 }
1713
1714 int unit_watch_cgroup_memory(Unit *u) {
1715 _cleanup_free_ char *events = NULL;
1716 CGroupContext *c;
1717 int r;
1718
1719 assert(u);
1720
1721 /* Watches the "memory.events" attribute of this unit's cgroup for "oom_kill" events, but only if
1722 * cgroupv2 is available. */
1723
1724 if (!u->cgroup_path)
1725 return 0;
1726
1727 c = unit_get_cgroup_context(u);
1728 if (!c)
1729 return 0;
1730
1731 /* The "memory.events" attribute is only available if the memory controller is on. Let's hence tie
1732 * this to memory accounting, in a way watching for OOM kills is a form of memory accounting after
1733 * all. */
1734 if (!c->memory_accounting)
1735 return 0;
1736
1737 /* Don't watch inner nodes, as the kernel doesn't report oom_kill events recursively currently, and
1738 * we also don't want to generate a log message for each parent cgroup of a process. */
1739 if (u->type == UNIT_SLICE)
1740 return 0;
1741
1742 if (u->cgroup_memory_inotify_wd >= 0)
1743 return 0;
1744
1745 /* Only applies to the unified hierarchy */
1746 r = cg_all_unified();
1747 if (r < 0)
1748 return log_error_errno(r, "Failed to determine whether the memory controller is unified: %m");
1749 if (r == 0)
1750 return 0;
1751
1752 r = hashmap_ensure_allocated(&u->manager->cgroup_memory_inotify_wd_unit, &trivial_hash_ops);
1753 if (r < 0)
1754 return log_oom();
1755
1756 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "memory.events", &events);
1757 if (r < 0)
1758 return log_oom();
1759
1760 u->cgroup_memory_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1761 if (u->cgroup_memory_inotify_wd < 0) {
1762
1763 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
1764 * is not an error */
1765 return 0;
1766
1767 return log_unit_error_errno(u, errno, "Failed to add memory inotify watch descriptor for control group %s: %m", u->cgroup_path);
1768 }
1769
1770 r = hashmap_put(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd), u);
1771 if (r < 0)
1772 return log_unit_error_errno(u, r, "Failed to add memory inotify watch descriptor to hash map: %m");
1773
1774 return 0;
1775 }
1776
1777 int unit_pick_cgroup_path(Unit *u) {
1778 _cleanup_free_ char *path = NULL;
1779 int r;
1780
1781 assert(u);
1782
1783 if (u->cgroup_path)
1784 return 0;
1785
1786 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1787 return -EINVAL;
1788
1789 path = unit_default_cgroup_path(u);
1790 if (!path)
1791 return log_oom();
1792
1793 r = unit_set_cgroup_path(u, path);
1794 if (r == -EEXIST)
1795 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1796 if (r < 0)
1797 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1798
1799 return 0;
1800 }
1801
1802 static int unit_create_cgroup(
1803 Unit *u,
1804 CGroupMask target_mask,
1805 CGroupMask enable_mask,
1806 ManagerState state) {
1807
1808 bool created;
1809 int r;
1810
1811 assert(u);
1812
1813 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1814 return 0;
1815
1816 /* Figure out our cgroup path */
1817 r = unit_pick_cgroup_path(u);
1818 if (r < 0)
1819 return r;
1820
1821 /* First, create our own group */
1822 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1823 if (r < 0)
1824 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1825 created = r;
1826
1827 /* Start watching it */
1828 (void) unit_watch_cgroup(u);
1829 (void) unit_watch_cgroup_memory(u);
1830
1831 /* Preserve enabled controllers in delegated units, adjust others. */
1832 if (created || !u->cgroup_realized || !unit_cgroup_delegate(u)) {
1833 CGroupMask result_mask = 0;
1834
1835 /* Enable all controllers we need */
1836 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path, &result_mask);
1837 if (r < 0)
1838 log_unit_warning_errno(u, r, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
1839
1840 /* If we just turned off a controller, this might release the controller for our parent too, let's
1841 * enqueue the parent for re-realization in that case again. */
1842 if (UNIT_ISSET(u->slice)) {
1843 CGroupMask turned_off;
1844
1845 turned_off = (u->cgroup_realized ? u->cgroup_enabled_mask & ~result_mask : 0);
1846 if (turned_off != 0) {
1847 Unit *parent;
1848
1849 /* Force the parent to propagate the enable mask to the kernel again, by invalidating
1850 * the controller we just turned off. */
1851
1852 for (parent = UNIT_DEREF(u->slice); parent; parent = UNIT_DEREF(parent->slice))
1853 unit_invalidate_cgroup(parent, turned_off);
1854 }
1855 }
1856
1857 /* Remember what's actually enabled now */
1858 u->cgroup_enabled_mask = result_mask;
1859 }
1860
1861 /* Keep track that this is now realized */
1862 u->cgroup_realized = true;
1863 u->cgroup_realized_mask = target_mask;
1864
1865 if (u->type != UNIT_SLICE && !unit_cgroup_delegate(u)) {
1866
1867 /* Then, possibly move things over, but not if
1868 * subgroups may contain processes, which is the case
1869 * for slice and delegation units. */
1870 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1871 if (r < 0)
1872 log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
1873 }
1874
1875 /* Set attributes */
1876 cgroup_context_apply(u, target_mask, state);
1877 cgroup_xattr_apply(u);
1878
1879 return 0;
1880 }
1881
1882 static int unit_attach_pid_to_cgroup_via_bus(Unit *u, pid_t pid, const char *suffix_path) {
1883 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1884 char *pp;
1885 int r;
1886
1887 assert(u);
1888
1889 if (MANAGER_IS_SYSTEM(u->manager))
1890 return -EINVAL;
1891
1892 if (!u->manager->system_bus)
1893 return -EIO;
1894
1895 if (!u->cgroup_path)
1896 return -EINVAL;
1897
1898 /* Determine this unit's cgroup path relative to our cgroup root */
1899 pp = path_startswith(u->cgroup_path, u->manager->cgroup_root);
1900 if (!pp)
1901 return -EINVAL;
1902
1903 pp = strjoina("/", pp, suffix_path);
1904 path_simplify(pp, false);
1905
1906 r = sd_bus_call_method(u->manager->system_bus,
1907 "org.freedesktop.systemd1",
1908 "/org/freedesktop/systemd1",
1909 "org.freedesktop.systemd1.Manager",
1910 "AttachProcessesToUnit",
1911 &error, NULL,
1912 "ssau",
1913 NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
1914 if (r < 0)
1915 return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
1916
1917 return 0;
1918 }
1919
1920 int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
1921 CGroupMask delegated_mask;
1922 const char *p;
1923 Iterator i;
1924 void *pidp;
1925 int r, q;
1926
1927 assert(u);
1928
1929 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1930 return -EINVAL;
1931
1932 if (set_isempty(pids))
1933 return 0;
1934
1935 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
1936 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
1937 r = bpf_firewall_load_custom(u);
1938 if (r < 0)
1939 return r;
1940
1941 r = unit_realize_cgroup(u);
1942 if (r < 0)
1943 return r;
1944
1945 if (isempty(suffix_path))
1946 p = u->cgroup_path;
1947 else
1948 p = prefix_roota(u->cgroup_path, suffix_path);
1949
1950 delegated_mask = unit_get_delegate_mask(u);
1951
1952 r = 0;
1953 SET_FOREACH(pidp, pids, i) {
1954 pid_t pid = PTR_TO_PID(pidp);
1955 CGroupController c;
1956
1957 /* First, attach the PID to the main cgroup hierarchy */
1958 q = cg_attach(SYSTEMD_CGROUP_CONTROLLER, p, pid);
1959 if (q < 0) {
1960 log_unit_debug_errno(u, q, "Couldn't move process " PID_FMT " to requested cgroup '%s': %m", pid, p);
1961
1962 if (MANAGER_IS_USER(u->manager) && IN_SET(q, -EPERM, -EACCES)) {
1963 int z;
1964
1965 /* If we are in a user instance, and we can't move the process ourselves due to
1966 * permission problems, let's ask the system instance about it instead. Since it's more
1967 * privileged it might be able to move the process across the leaves of a subtree who's
1968 * top node is not owned by us. */
1969
1970 z = unit_attach_pid_to_cgroup_via_bus(u, pid, suffix_path);
1971 if (z < 0)
1972 log_unit_debug_errno(u, z, "Couldn't move process " PID_FMT " to requested cgroup '%s' via the system bus either: %m", pid, p);
1973 else
1974 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1975 }
1976
1977 if (r >= 0)
1978 r = q; /* Remember first error */
1979
1980 continue;
1981 }
1982
1983 q = cg_all_unified();
1984 if (q < 0)
1985 return q;
1986 if (q > 0)
1987 continue;
1988
1989 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
1990 * innermost realized one */
1991
1992 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1993 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1994 const char *realized;
1995
1996 if (!(u->manager->cgroup_supported & bit))
1997 continue;
1998
1999 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
2000 if (delegated_mask & u->cgroup_realized_mask & bit) {
2001 q = cg_attach(cgroup_controller_to_string(c), p, pid);
2002 if (q >= 0)
2003 continue; /* Success! */
2004
2005 log_unit_debug_errno(u, q, "Failed to attach PID " PID_FMT " to requested cgroup %s in controller %s, falling back to unit's cgroup: %m",
2006 pid, p, cgroup_controller_to_string(c));
2007 }
2008
2009 /* So this controller is either not delegate or realized, or something else weird happened. In
2010 * that case let's attach the PID at least to the closest cgroup up the tree that is
2011 * realized. */
2012 realized = unit_get_realized_cgroup_path(u, bit);
2013 if (!realized)
2014 continue; /* Not even realized in the root slice? Then let's not bother */
2015
2016 q = cg_attach(cgroup_controller_to_string(c), realized, pid);
2017 if (q < 0)
2018 log_unit_debug_errno(u, q, "Failed to attach PID " PID_FMT " to realized cgroup %s in controller %s, ignoring: %m",
2019 pid, realized, cgroup_controller_to_string(c));
2020 }
2021 }
2022
2023 return r;
2024 }
2025
2026 static bool unit_has_mask_realized(
2027 Unit *u,
2028 CGroupMask target_mask,
2029 CGroupMask enable_mask) {
2030
2031 assert(u);
2032
2033 /* Returns true if this unit is fully realized. We check four things:
2034 *
2035 * 1. Whether the cgroup was created at all
2036 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
2037 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
2038 * 4. Whether the invalidation mask is currently zero
2039 *
2040 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
2041 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
2042 * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
2043 * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
2044 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
2045 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
2046 * simply don't matter. */
2047
2048 return u->cgroup_realized &&
2049 ((u->cgroup_realized_mask ^ target_mask) & CGROUP_MASK_V1) == 0 &&
2050 ((u->cgroup_enabled_mask ^ enable_mask) & CGROUP_MASK_V2) == 0 &&
2051 u->cgroup_invalidated_mask == 0;
2052 }
2053
2054 static bool unit_has_mask_disables_realized(
2055 Unit *u,
2056 CGroupMask target_mask,
2057 CGroupMask enable_mask) {
2058
2059 assert(u);
2060
2061 /* Returns true if all controllers which should be disabled are indeed disabled.
2062 *
2063 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
2064 * already removed. */
2065
2066 return !u->cgroup_realized ||
2067 (FLAGS_SET(u->cgroup_realized_mask, target_mask & CGROUP_MASK_V1) &&
2068 FLAGS_SET(u->cgroup_enabled_mask, enable_mask & CGROUP_MASK_V2));
2069 }
2070
2071 static bool unit_has_mask_enables_realized(
2072 Unit *u,
2073 CGroupMask target_mask,
2074 CGroupMask enable_mask) {
2075
2076 assert(u);
2077
2078 /* Returns true if all controllers which should be enabled are indeed enabled.
2079 *
2080 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
2081 * we want to add is already added. */
2082
2083 return u->cgroup_realized &&
2084 ((u->cgroup_realized_mask | target_mask) & CGROUP_MASK_V1) == (u->cgroup_realized_mask & CGROUP_MASK_V1) &&
2085 ((u->cgroup_enabled_mask | enable_mask) & CGROUP_MASK_V2) == (u->cgroup_enabled_mask & CGROUP_MASK_V2);
2086 }
2087
2088 void unit_add_to_cgroup_realize_queue(Unit *u) {
2089 assert(u);
2090
2091 if (u->in_cgroup_realize_queue)
2092 return;
2093
2094 LIST_PREPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2095 u->in_cgroup_realize_queue = true;
2096 }
2097
2098 static void unit_remove_from_cgroup_realize_queue(Unit *u) {
2099 assert(u);
2100
2101 if (!u->in_cgroup_realize_queue)
2102 return;
2103
2104 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2105 u->in_cgroup_realize_queue = false;
2106 }
2107
2108 /* Controllers can only be enabled breadth-first, from the root of the
2109 * hierarchy downwards to the unit in question. */
2110 static int unit_realize_cgroup_now_enable(Unit *u, ManagerState state) {
2111 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2112 int r;
2113
2114 assert(u);
2115
2116 /* First go deal with this unit's parent, or we won't be able to enable
2117 * any new controllers at this layer. */
2118 if (UNIT_ISSET(u->slice)) {
2119 r = unit_realize_cgroup_now_enable(UNIT_DEREF(u->slice), state);
2120 if (r < 0)
2121 return r;
2122 }
2123
2124 target_mask = unit_get_target_mask(u);
2125 enable_mask = unit_get_enable_mask(u);
2126
2127 /* We can only enable in this direction, don't try to disable anything.
2128 */
2129 if (unit_has_mask_enables_realized(u, target_mask, enable_mask))
2130 return 0;
2131
2132 new_target_mask = u->cgroup_realized_mask | target_mask;
2133 new_enable_mask = u->cgroup_enabled_mask | enable_mask;
2134
2135 return unit_create_cgroup(u, new_target_mask, new_enable_mask, state);
2136 }
2137
2138 /* Controllers can only be disabled depth-first, from the leaves of the
2139 * hierarchy upwards to the unit in question. */
2140 static int unit_realize_cgroup_now_disable(Unit *u, ManagerState state) {
2141 Iterator i;
2142 Unit *m;
2143 void *v;
2144
2145 assert(u);
2146
2147 if (u->type != UNIT_SLICE)
2148 return 0;
2149
2150 HASHMAP_FOREACH_KEY(v, m, u->dependencies[UNIT_BEFORE], i) {
2151 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2152 int r;
2153
2154 if (UNIT_DEREF(m->slice) != u)
2155 continue;
2156
2157 /* The cgroup for this unit might not actually be fully
2158 * realised yet, in which case it isn't holding any controllers
2159 * open anyway. */
2160 if (!m->cgroup_path)
2161 continue;
2162
2163 /* We must disable those below us first in order to release the
2164 * controller. */
2165 if (m->type == UNIT_SLICE)
2166 (void) unit_realize_cgroup_now_disable(m, state);
2167
2168 target_mask = unit_get_target_mask(m);
2169 enable_mask = unit_get_enable_mask(m);
2170
2171 /* We can only disable in this direction, don't try to enable
2172 * anything. */
2173 if (unit_has_mask_disables_realized(m, target_mask, enable_mask))
2174 continue;
2175
2176 new_target_mask = m->cgroup_realized_mask & target_mask;
2177 new_enable_mask = m->cgroup_enabled_mask & enable_mask;
2178
2179 r = unit_create_cgroup(m, new_target_mask, new_enable_mask, state);
2180 if (r < 0)
2181 return r;
2182 }
2183
2184 return 0;
2185 }
2186
2187 /* Check if necessary controllers and attributes for a unit are in place.
2188 *
2189 * - If so, do nothing.
2190 * - If not, create paths, move processes over, and set attributes.
2191 *
2192 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
2193 * a depth-first way. As such the process looks like this:
2194 *
2195 * Suppose we have a cgroup hierarchy which looks like this:
2196 *
2197 * root
2198 * / \
2199 * / \
2200 * / \
2201 * a b
2202 * / \ / \
2203 * / \ / \
2204 * c d e f
2205 * / \ / \ / \ / \
2206 * h i j k l m n o
2207 *
2208 * 1. We want to realise cgroup "d" now.
2209 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
2210 * 3. cgroup "k" just started requesting the memory controller.
2211 *
2212 * To make this work we must do the following in order:
2213 *
2214 * 1. Disable CPU controller in k, j
2215 * 2. Disable CPU controller in d
2216 * 3. Enable memory controller in root
2217 * 4. Enable memory controller in a
2218 * 5. Enable memory controller in d
2219 * 6. Enable memory controller in k
2220 *
2221 * Notice that we need to touch j in one direction, but not the other. We also
2222 * don't go beyond d when disabling -- it's up to "a" to get realized if it
2223 * wants to disable further. The basic rules are therefore:
2224 *
2225 * - If you're disabling something, you need to realise all of the cgroups from
2226 * your recursive descendants to the root. This starts from the leaves.
2227 * - If you're enabling something, you need to realise from the root cgroup
2228 * downwards, but you don't need to iterate your recursive descendants.
2229 *
2230 * Returns 0 on success and < 0 on failure. */
2231 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
2232 CGroupMask target_mask, enable_mask;
2233 int r;
2234
2235 assert(u);
2236
2237 unit_remove_from_cgroup_realize_queue(u);
2238
2239 target_mask = unit_get_target_mask(u);
2240 enable_mask = unit_get_enable_mask(u);
2241
2242 if (unit_has_mask_realized(u, target_mask, enable_mask))
2243 return 0;
2244
2245 /* Disable controllers below us, if there are any */
2246 r = unit_realize_cgroup_now_disable(u, state);
2247 if (r < 0)
2248 return r;
2249
2250 /* Enable controllers above us, if there are any */
2251 if (UNIT_ISSET(u->slice)) {
2252 r = unit_realize_cgroup_now_enable(UNIT_DEREF(u->slice), state);
2253 if (r < 0)
2254 return r;
2255 }
2256
2257 /* Now actually deal with the cgroup we were trying to realise and set attributes */
2258 r = unit_create_cgroup(u, target_mask, enable_mask, state);
2259 if (r < 0)
2260 return r;
2261
2262 /* Now, reset the invalidation mask */
2263 u->cgroup_invalidated_mask = 0;
2264 return 0;
2265 }
2266
2267 unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
2268 ManagerState state;
2269 unsigned n = 0;
2270 Unit *i;
2271 int r;
2272
2273 assert(m);
2274
2275 state = manager_state(m);
2276
2277 while ((i = m->cgroup_realize_queue)) {
2278 assert(i->in_cgroup_realize_queue);
2279
2280 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
2281 /* Maybe things changed, and the unit is not actually active anymore? */
2282 unit_remove_from_cgroup_realize_queue(i);
2283 continue;
2284 }
2285
2286 r = unit_realize_cgroup_now(i, state);
2287 if (r < 0)
2288 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
2289
2290 n++;
2291 }
2292
2293 return n;
2294 }
2295
2296 static void unit_add_siblings_to_cgroup_realize_queue(Unit *u) {
2297 Unit *slice;
2298
2299 /* This adds the siblings of the specified unit and the
2300 * siblings of all parent units to the cgroup queue. (But
2301 * neither the specified unit itself nor the parents.) */
2302
2303 while ((slice = UNIT_DEREF(u->slice))) {
2304 Iterator i;
2305 Unit *m;
2306 void *v;
2307
2308 HASHMAP_FOREACH_KEY(v, m, u->dependencies[UNIT_BEFORE], i) {
2309 /* Skip units that have a dependency on the slice
2310 * but aren't actually in it. */
2311 if (UNIT_DEREF(m->slice) != slice)
2312 continue;
2313
2314 /* No point in doing cgroup application for units
2315 * without active processes. */
2316 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
2317 continue;
2318
2319 /* If the unit doesn't need any new controllers
2320 * and has current ones realized, it doesn't need
2321 * any changes. */
2322 if (unit_has_mask_realized(m,
2323 unit_get_target_mask(m),
2324 unit_get_enable_mask(m)))
2325 continue;
2326
2327 unit_add_to_cgroup_realize_queue(m);
2328 }
2329
2330 u = slice;
2331 }
2332 }
2333
2334 int unit_realize_cgroup(Unit *u) {
2335 assert(u);
2336
2337 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2338 return 0;
2339
2340 /* So, here's the deal: when realizing the cgroups for this
2341 * unit, we need to first create all parents, but there's more
2342 * actually: for the weight-based controllers we also need to
2343 * make sure that all our siblings (i.e. units that are in the
2344 * same slice as we are) have cgroups, too. Otherwise, things
2345 * would become very uneven as each of their processes would
2346 * get as much resources as all our group together. This call
2347 * will synchronously create the parent cgroups, but will
2348 * defer work on the siblings to the next event loop
2349 * iteration. */
2350
2351 /* Add all sibling slices to the cgroup queue. */
2352 unit_add_siblings_to_cgroup_realize_queue(u);
2353
2354 /* And realize this one now (and apply the values) */
2355 return unit_realize_cgroup_now(u, manager_state(u->manager));
2356 }
2357
2358 void unit_release_cgroup(Unit *u) {
2359 assert(u);
2360
2361 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
2362 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
2363
2364 if (u->cgroup_path) {
2365 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
2366 u->cgroup_path = mfree(u->cgroup_path);
2367 }
2368
2369 if (u->cgroup_control_inotify_wd >= 0) {
2370 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_control_inotify_wd) < 0)
2371 log_unit_debug_errno(u, errno, "Failed to remove cgroup control inotify watch %i for %s, ignoring: %m", u->cgroup_control_inotify_wd, u->id);
2372
2373 (void) hashmap_remove(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd));
2374 u->cgroup_control_inotify_wd = -1;
2375 }
2376
2377 if (u->cgroup_memory_inotify_wd >= 0) {
2378 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_memory_inotify_wd) < 0)
2379 log_unit_debug_errno(u, errno, "Failed to remove cgroup memory inotify watch %i for %s, ignoring: %m", u->cgroup_memory_inotify_wd, u->id);
2380
2381 (void) hashmap_remove(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd));
2382 u->cgroup_memory_inotify_wd = -1;
2383 }
2384 }
2385
2386 void unit_prune_cgroup(Unit *u) {
2387 int r;
2388 bool is_root_slice;
2389
2390 assert(u);
2391
2392 /* Removes the cgroup, if empty and possible, and stops watching it. */
2393
2394 if (!u->cgroup_path)
2395 return;
2396
2397 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
2398
2399 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
2400
2401 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
2402 if (r < 0)
2403 /* One reason we could have failed here is, that the cgroup still contains a process.
2404 * However, if the cgroup becomes removable at a later time, it might be removed when
2405 * the containing slice is stopped. So even if we failed now, this unit shouldn't assume
2406 * that the cgroup is still realized the next time it is started. Do not return early
2407 * on error, continue cleanup. */
2408 log_unit_full(u, r == -EBUSY ? LOG_DEBUG : LOG_WARNING, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
2409
2410 if (is_root_slice)
2411 return;
2412
2413 unit_release_cgroup(u);
2414
2415 u->cgroup_realized = false;
2416 u->cgroup_realized_mask = 0;
2417 u->cgroup_enabled_mask = 0;
2418
2419 u->bpf_device_control_installed = bpf_program_unref(u->bpf_device_control_installed);
2420 }
2421
2422 int unit_search_main_pid(Unit *u, pid_t *ret) {
2423 _cleanup_fclose_ FILE *f = NULL;
2424 pid_t pid = 0, npid;
2425 int r;
2426
2427 assert(u);
2428 assert(ret);
2429
2430 if (!u->cgroup_path)
2431 return -ENXIO;
2432
2433 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
2434 if (r < 0)
2435 return r;
2436
2437 while (cg_read_pid(f, &npid) > 0) {
2438
2439 if (npid == pid)
2440 continue;
2441
2442 if (pid_is_my_child(npid) == 0)
2443 continue;
2444
2445 if (pid != 0)
2446 /* Dang, there's more than one daemonized PID
2447 in this group, so we don't know what process
2448 is the main process. */
2449
2450 return -ENODATA;
2451
2452 pid = npid;
2453 }
2454
2455 *ret = pid;
2456 return 0;
2457 }
2458
2459 static int unit_watch_pids_in_path(Unit *u, const char *path) {
2460 _cleanup_closedir_ DIR *d = NULL;
2461 _cleanup_fclose_ FILE *f = NULL;
2462 int ret = 0, r;
2463
2464 assert(u);
2465 assert(path);
2466
2467 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
2468 if (r < 0)
2469 ret = r;
2470 else {
2471 pid_t pid;
2472
2473 while ((r = cg_read_pid(f, &pid)) > 0) {
2474 r = unit_watch_pid(u, pid, false);
2475 if (r < 0 && ret >= 0)
2476 ret = r;
2477 }
2478
2479 if (r < 0 && ret >= 0)
2480 ret = r;
2481 }
2482
2483 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
2484 if (r < 0) {
2485 if (ret >= 0)
2486 ret = r;
2487 } else {
2488 char *fn;
2489
2490 while ((r = cg_read_subgroup(d, &fn)) > 0) {
2491 _cleanup_free_ char *p = NULL;
2492
2493 p = path_join(empty_to_root(path), fn);
2494 free(fn);
2495
2496 if (!p)
2497 return -ENOMEM;
2498
2499 r = unit_watch_pids_in_path(u, p);
2500 if (r < 0 && ret >= 0)
2501 ret = r;
2502 }
2503
2504 if (r < 0 && ret >= 0)
2505 ret = r;
2506 }
2507
2508 return ret;
2509 }
2510
2511 int unit_synthesize_cgroup_empty_event(Unit *u) {
2512 int r;
2513
2514 assert(u);
2515
2516 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
2517 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
2518 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
2519
2520 if (!u->cgroup_path)
2521 return -ENOENT;
2522
2523 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2524 if (r < 0)
2525 return r;
2526 if (r > 0) /* On unified we have reliable notifications, and don't need this */
2527 return 0;
2528
2529 if (!set_isempty(u->pids))
2530 return 0;
2531
2532 unit_add_to_cgroup_empty_queue(u);
2533 return 0;
2534 }
2535
2536 int unit_watch_all_pids(Unit *u) {
2537 int r;
2538
2539 assert(u);
2540
2541 /* Adds all PIDs from our cgroup to the set of PIDs we
2542 * watch. This is a fallback logic for cases where we do not
2543 * get reliable cgroup empty notifications: we try to use
2544 * SIGCHLD as replacement. */
2545
2546 if (!u->cgroup_path)
2547 return -ENOENT;
2548
2549 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2550 if (r < 0)
2551 return r;
2552 if (r > 0) /* On unified we can use proper notifications */
2553 return 0;
2554
2555 return unit_watch_pids_in_path(u, u->cgroup_path);
2556 }
2557
2558 static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
2559 Manager *m = userdata;
2560 Unit *u;
2561 int r;
2562
2563 assert(s);
2564 assert(m);
2565
2566 u = m->cgroup_empty_queue;
2567 if (!u)
2568 return 0;
2569
2570 assert(u->in_cgroup_empty_queue);
2571 u->in_cgroup_empty_queue = false;
2572 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
2573
2574 if (m->cgroup_empty_queue) {
2575 /* More stuff queued, let's make sure we remain enabled */
2576 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
2577 if (r < 0)
2578 log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
2579 }
2580
2581 unit_add_to_gc_queue(u);
2582
2583 if (UNIT_VTABLE(u)->notify_cgroup_empty)
2584 UNIT_VTABLE(u)->notify_cgroup_empty(u);
2585
2586 return 0;
2587 }
2588
2589 void unit_add_to_cgroup_empty_queue(Unit *u) {
2590 int r;
2591
2592 assert(u);
2593
2594 /* Note that there are four different ways how cgroup empty events reach us:
2595 *
2596 * 1. On the unified hierarchy we get an inotify event on the cgroup
2597 *
2598 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2599 *
2600 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2601 *
2602 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2603 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2604 *
2605 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2606 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2607 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2608 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2609 * case for scope units). */
2610
2611 if (u->in_cgroup_empty_queue)
2612 return;
2613
2614 /* Let's verify that the cgroup is really empty */
2615 if (!u->cgroup_path)
2616 return;
2617 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
2618 if (r < 0) {
2619 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", u->cgroup_path);
2620 return;
2621 }
2622 if (r == 0)
2623 return;
2624
2625 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
2626 u->in_cgroup_empty_queue = true;
2627
2628 /* Trigger the defer event */
2629 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
2630 if (r < 0)
2631 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
2632 }
2633
2634 int unit_check_oom(Unit *u) {
2635 _cleanup_free_ char *oom_kill = NULL;
2636 bool increased;
2637 uint64_t c;
2638 int r;
2639
2640 if (!u->cgroup_path)
2641 return 0;
2642
2643 r = cg_get_keyed_attribute("memory", u->cgroup_path, "memory.events", STRV_MAKE("oom_kill"), &oom_kill);
2644 if (r < 0)
2645 return log_unit_debug_errno(u, r, "Failed to read oom_kill field of memory.events cgroup attribute: %m");
2646
2647 r = safe_atou64(oom_kill, &c);
2648 if (r < 0)
2649 return log_unit_debug_errno(u, r, "Failed to parse oom_kill field: %m");
2650
2651 increased = c > u->oom_kill_last;
2652 u->oom_kill_last = c;
2653
2654 if (!increased)
2655 return 0;
2656
2657 log_struct(LOG_NOTICE,
2658 "MESSAGE_ID=" SD_MESSAGE_UNIT_OUT_OF_MEMORY_STR,
2659 LOG_UNIT_ID(u),
2660 LOG_UNIT_INVOCATION_ID(u),
2661 LOG_UNIT_MESSAGE(u, "A process of this unit has been killed by the OOM killer."));
2662
2663 if (UNIT_VTABLE(u)->notify_cgroup_oom)
2664 UNIT_VTABLE(u)->notify_cgroup_oom(u);
2665
2666 return 1;
2667 }
2668
2669 static int on_cgroup_oom_event(sd_event_source *s, void *userdata) {
2670 Manager *m = userdata;
2671 Unit *u;
2672 int r;
2673
2674 assert(s);
2675 assert(m);
2676
2677 u = m->cgroup_oom_queue;
2678 if (!u)
2679 return 0;
2680
2681 assert(u->in_cgroup_oom_queue);
2682 u->in_cgroup_oom_queue = false;
2683 LIST_REMOVE(cgroup_oom_queue, m->cgroup_oom_queue, u);
2684
2685 if (m->cgroup_oom_queue) {
2686 /* More stuff queued, let's make sure we remain enabled */
2687 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
2688 if (r < 0)
2689 log_debug_errno(r, "Failed to reenable cgroup oom event source, ignoring: %m");
2690 }
2691
2692 (void) unit_check_oom(u);
2693 return 0;
2694 }
2695
2696 static void unit_add_to_cgroup_oom_queue(Unit *u) {
2697 int r;
2698
2699 assert(u);
2700
2701 if (u->in_cgroup_oom_queue)
2702 return;
2703 if (!u->cgroup_path)
2704 return;
2705
2706 LIST_PREPEND(cgroup_oom_queue, u->manager->cgroup_oom_queue, u);
2707 u->in_cgroup_oom_queue = true;
2708
2709 /* Trigger the defer event */
2710 if (!u->manager->cgroup_oom_event_source) {
2711 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
2712
2713 r = sd_event_add_defer(u->manager->event, &s, on_cgroup_oom_event, u->manager);
2714 if (r < 0) {
2715 log_error_errno(r, "Failed to create cgroup oom event source: %m");
2716 return;
2717 }
2718
2719 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_NORMAL-8);
2720 if (r < 0) {
2721 log_error_errno(r, "Failed to set priority of cgroup oom event source: %m");
2722 return;
2723 }
2724
2725 (void) sd_event_source_set_description(s, "cgroup-oom");
2726 u->manager->cgroup_oom_event_source = TAKE_PTR(s);
2727 }
2728
2729 r = sd_event_source_set_enabled(u->manager->cgroup_oom_event_source, SD_EVENT_ONESHOT);
2730 if (r < 0)
2731 log_error_errno(r, "Failed to enable cgroup oom event source: %m");
2732 }
2733
2734 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2735 Manager *m = userdata;
2736
2737 assert(s);
2738 assert(fd >= 0);
2739 assert(m);
2740
2741 for (;;) {
2742 union inotify_event_buffer buffer;
2743 struct inotify_event *e;
2744 ssize_t l;
2745
2746 l = read(fd, &buffer, sizeof(buffer));
2747 if (l < 0) {
2748 if (IN_SET(errno, EINTR, EAGAIN))
2749 return 0;
2750
2751 return log_error_errno(errno, "Failed to read control group inotify events: %m");
2752 }
2753
2754 FOREACH_INOTIFY_EVENT(e, buffer, l) {
2755 Unit *u;
2756
2757 if (e->wd < 0)
2758 /* Queue overflow has no watch descriptor */
2759 continue;
2760
2761 if (e->mask & IN_IGNORED)
2762 /* The watch was just removed */
2763 continue;
2764
2765 /* Note that inotify might deliver events for a watch even after it was removed,
2766 * because it was queued before the removal. Let's ignore this here safely. */
2767
2768 u = hashmap_get(m->cgroup_control_inotify_wd_unit, INT_TO_PTR(e->wd));
2769 if (u)
2770 unit_add_to_cgroup_empty_queue(u);
2771
2772 u = hashmap_get(m->cgroup_memory_inotify_wd_unit, INT_TO_PTR(e->wd));
2773 if (u)
2774 unit_add_to_cgroup_oom_queue(u);
2775 }
2776 }
2777 }
2778
2779 static int cg_bpf_mask_supported(CGroupMask *ret) {
2780 CGroupMask mask = 0;
2781 int r;
2782
2783 /* BPF-based firewall */
2784 r = bpf_firewall_supported();
2785 if (r > 0)
2786 mask |= CGROUP_MASK_BPF_FIREWALL;
2787
2788 /* BPF-based device access control */
2789 r = bpf_devices_supported();
2790 if (r > 0)
2791 mask |= CGROUP_MASK_BPF_DEVICES;
2792
2793 *ret = mask;
2794 return 0;
2795 }
2796
2797 int manager_setup_cgroup(Manager *m) {
2798 _cleanup_free_ char *path = NULL;
2799 const char *scope_path;
2800 CGroupController c;
2801 int r, all_unified;
2802 CGroupMask mask;
2803 char *e;
2804
2805 assert(m);
2806
2807 /* 1. Determine hierarchy */
2808 m->cgroup_root = mfree(m->cgroup_root);
2809 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
2810 if (r < 0)
2811 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
2812
2813 /* Chop off the init scope, if we are already located in it */
2814 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2815
2816 /* LEGACY: Also chop off the system slice if we are in
2817 * it. This is to support live upgrades from older systemd
2818 * versions where PID 1 was moved there. Also see
2819 * cg_get_root_path(). */
2820 if (!e && MANAGER_IS_SYSTEM(m)) {
2821 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
2822 if (!e)
2823 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
2824 }
2825 if (e)
2826 *e = 0;
2827
2828 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2829 * easily prepend it everywhere. */
2830 delete_trailing_chars(m->cgroup_root, "/");
2831
2832 /* 2. Show data */
2833 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
2834 if (r < 0)
2835 return log_error_errno(r, "Cannot find cgroup mount point: %m");
2836
2837 r = cg_unified_flush();
2838 if (r < 0)
2839 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
2840
2841 all_unified = cg_all_unified();
2842 if (all_unified < 0)
2843 return log_error_errno(all_unified, "Couldn't determine whether we are in all unified mode: %m");
2844 if (all_unified > 0)
2845 log_debug("Unified cgroup hierarchy is located at %s.", path);
2846 else {
2847 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2848 if (r < 0)
2849 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
2850 if (r > 0)
2851 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
2852 else
2853 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
2854 }
2855
2856 /* 3. Allocate cgroup empty defer event source */
2857 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2858 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
2859 if (r < 0)
2860 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
2861
2862 /* Schedule cgroup empty checks early, but after having processed service notification messages or
2863 * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of
2864 * notification, and we collected the metadata the notification and SIGCHLD stuff offers first. */
2865 r = sd_event_source_set_priority(m->cgroup_empty_event_source, SD_EVENT_PRIORITY_NORMAL-5);
2866 if (r < 0)
2867 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
2868
2869 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
2870 if (r < 0)
2871 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
2872
2873 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
2874
2875 /* 4. Install notifier inotify object, or agent */
2876 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
2877
2878 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2879
2880 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2881 safe_close(m->cgroup_inotify_fd);
2882
2883 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
2884 if (m->cgroup_inotify_fd < 0)
2885 return log_error_errno(errno, "Failed to create control group inotify object: %m");
2886
2887 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
2888 if (r < 0)
2889 return log_error_errno(r, "Failed to watch control group inotify object: %m");
2890
2891 /* Process cgroup empty notifications early. Note that when this event is dispatched it'll
2892 * just add the unit to a cgroup empty queue, hence let's run earlier than that. Also see
2893 * handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2894 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-9);
2895 if (r < 0)
2896 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
2897
2898 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
2899
2900 } else if (MANAGER_IS_SYSTEM(m) && manager_owns_host_root_cgroup(m) && !MANAGER_IS_TEST_RUN(m)) {
2901
2902 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2903 * since it does not generate events when control groups with children run empty. */
2904
2905 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
2906 if (r < 0)
2907 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
2908 else if (r > 0)
2909 log_debug("Installed release agent.");
2910 else if (r == 0)
2911 log_debug("Release agent already installed.");
2912 }
2913
2914 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2915 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2916 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2917 if (r >= 0) {
2918 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2919 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2920 if (r < 0)
2921 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
2922
2923 /* 6. And pin it, so that it cannot be unmounted */
2924 safe_close(m->pin_cgroupfs_fd);
2925 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
2926 if (m->pin_cgroupfs_fd < 0)
2927 return log_error_errno(errno, "Failed to open pin file: %m");
2928
2929 } else if (!MANAGER_IS_TEST_RUN(m))
2930 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
2931
2932 /* 7. Always enable hierarchical support if it exists... */
2933 if (!all_unified && !MANAGER_IS_TEST_RUN(m))
2934 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
2935
2936 /* 8. Figure out which controllers are supported */
2937 r = cg_mask_supported(&m->cgroup_supported);
2938 if (r < 0)
2939 return log_error_errno(r, "Failed to determine supported controllers: %m");
2940
2941 /* 9. Figure out which bpf-based pseudo-controllers are supported */
2942 r = cg_bpf_mask_supported(&mask);
2943 if (r < 0)
2944 return log_error_errno(r, "Failed to determine supported bpf-based pseudo-controllers: %m");
2945 m->cgroup_supported |= mask;
2946
2947 /* 10. Log which controllers are supported */
2948 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
2949 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
2950
2951 return 0;
2952 }
2953
2954 void manager_shutdown_cgroup(Manager *m, bool delete) {
2955 assert(m);
2956
2957 /* We can't really delete the group, since we are in it. But
2958 * let's trim it. */
2959 if (delete && m->cgroup_root && m->test_run_flags != MANAGER_TEST_RUN_MINIMAL)
2960 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
2961
2962 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2963
2964 m->cgroup_control_inotify_wd_unit = hashmap_free(m->cgroup_control_inotify_wd_unit);
2965 m->cgroup_memory_inotify_wd_unit = hashmap_free(m->cgroup_memory_inotify_wd_unit);
2966
2967 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2968 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
2969
2970 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
2971
2972 m->cgroup_root = mfree(m->cgroup_root);
2973 }
2974
2975 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
2976 char *p;
2977 Unit *u;
2978
2979 assert(m);
2980 assert(cgroup);
2981
2982 u = hashmap_get(m->cgroup_unit, cgroup);
2983 if (u)
2984 return u;
2985
2986 p = strdupa(cgroup);
2987 for (;;) {
2988 char *e;
2989
2990 e = strrchr(p, '/');
2991 if (!e || e == p)
2992 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
2993
2994 *e = 0;
2995
2996 u = hashmap_get(m->cgroup_unit, p);
2997 if (u)
2998 return u;
2999 }
3000 }
3001
3002 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
3003 _cleanup_free_ char *cgroup = NULL;
3004
3005 assert(m);
3006
3007 if (!pid_is_valid(pid))
3008 return NULL;
3009
3010 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup) < 0)
3011 return NULL;
3012
3013 return manager_get_unit_by_cgroup(m, cgroup);
3014 }
3015
3016 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
3017 Unit *u, **array;
3018
3019 assert(m);
3020
3021 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
3022 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
3023 * relevant one as children of the process will be assigned to that one, too, before all else. */
3024
3025 if (!pid_is_valid(pid))
3026 return NULL;
3027
3028 if (pid == getpid_cached())
3029 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
3030
3031 u = manager_get_unit_by_pid_cgroup(m, pid);
3032 if (u)
3033 return u;
3034
3035 u = hashmap_get(m->watch_pids, PID_TO_PTR(pid));
3036 if (u)
3037 return u;
3038
3039 array = hashmap_get(m->watch_pids, PID_TO_PTR(-pid));
3040 if (array)
3041 return array[0];
3042
3043 return NULL;
3044 }
3045
3046 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
3047 Unit *u;
3048
3049 assert(m);
3050 assert(cgroup);
3051
3052 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
3053 * or from the --system instance */
3054
3055 log_debug("Got cgroup empty notification for: %s", cgroup);
3056
3057 u = manager_get_unit_by_cgroup(m, cgroup);
3058 if (!u)
3059 return 0;
3060
3061 unit_add_to_cgroup_empty_queue(u);
3062 return 1;
3063 }
3064
3065 int unit_get_memory_current(Unit *u, uint64_t *ret) {
3066 _cleanup_free_ char *v = NULL;
3067 int r;
3068
3069 assert(u);
3070 assert(ret);
3071
3072 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
3073 return -ENODATA;
3074
3075 if (!u->cgroup_path)
3076 return -ENODATA;
3077
3078 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3079 if (unit_has_host_root_cgroup(u))
3080 return procfs_memory_get_used(ret);
3081
3082 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
3083 return -ENODATA;
3084
3085 r = cg_all_unified();
3086 if (r < 0)
3087 return r;
3088 if (r > 0)
3089 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
3090 else
3091 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
3092 if (r == -ENOENT)
3093 return -ENODATA;
3094 if (r < 0)
3095 return r;
3096
3097 return safe_atou64(v, ret);
3098 }
3099
3100 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
3101 _cleanup_free_ char *v = NULL;
3102 int r;
3103
3104 assert(u);
3105 assert(ret);
3106
3107 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
3108 return -ENODATA;
3109
3110 if (!u->cgroup_path)
3111 return -ENODATA;
3112
3113 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3114 if (unit_has_host_root_cgroup(u))
3115 return procfs_tasks_get_current(ret);
3116
3117 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
3118 return -ENODATA;
3119
3120 r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
3121 if (r == -ENOENT)
3122 return -ENODATA;
3123 if (r < 0)
3124 return r;
3125
3126 return safe_atou64(v, ret);
3127 }
3128
3129 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
3130 _cleanup_free_ char *v = NULL;
3131 uint64_t ns;
3132 int r;
3133
3134 assert(u);
3135 assert(ret);
3136
3137 if (!u->cgroup_path)
3138 return -ENODATA;
3139
3140 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3141 if (unit_has_host_root_cgroup(u))
3142 return procfs_cpu_get_usage(ret);
3143
3144 /* Requisite controllers for CPU accounting are not enabled */
3145 if ((get_cpu_accounting_mask() & ~u->cgroup_realized_mask) != 0)
3146 return -ENODATA;
3147
3148 r = cg_all_unified();
3149 if (r < 0)
3150 return r;
3151 if (r > 0) {
3152 _cleanup_free_ char *val = NULL;
3153 uint64_t us;
3154
3155 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
3156 if (IN_SET(r, -ENOENT, -ENXIO))
3157 return -ENODATA;
3158 if (r < 0)
3159 return r;
3160
3161 r = safe_atou64(val, &us);
3162 if (r < 0)
3163 return r;
3164
3165 ns = us * NSEC_PER_USEC;
3166 } else {
3167 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
3168 if (r == -ENOENT)
3169 return -ENODATA;
3170 if (r < 0)
3171 return r;
3172
3173 r = safe_atou64(v, &ns);
3174 if (r < 0)
3175 return r;
3176 }
3177
3178 *ret = ns;
3179 return 0;
3180 }
3181
3182 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
3183 nsec_t ns;
3184 int r;
3185
3186 assert(u);
3187
3188 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
3189 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
3190 * call this function with a NULL return value. */
3191
3192 if (!UNIT_CGROUP_BOOL(u, cpu_accounting))
3193 return -ENODATA;
3194
3195 r = unit_get_cpu_usage_raw(u, &ns);
3196 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
3197 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
3198 * cached value. */
3199
3200 if (ret)
3201 *ret = u->cpu_usage_last;
3202 return 0;
3203 }
3204 if (r < 0)
3205 return r;
3206
3207 if (ns > u->cpu_usage_base)
3208 ns -= u->cpu_usage_base;
3209 else
3210 ns = 0;
3211
3212 u->cpu_usage_last = ns;
3213 if (ret)
3214 *ret = ns;
3215
3216 return 0;
3217 }
3218
3219 int unit_get_ip_accounting(
3220 Unit *u,
3221 CGroupIPAccountingMetric metric,
3222 uint64_t *ret) {
3223
3224 uint64_t value;
3225 int fd, r;
3226
3227 assert(u);
3228 assert(metric >= 0);
3229 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
3230 assert(ret);
3231
3232 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
3233 return -ENODATA;
3234
3235 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
3236 u->ip_accounting_ingress_map_fd :
3237 u->ip_accounting_egress_map_fd;
3238 if (fd < 0)
3239 return -ENODATA;
3240
3241 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
3242 r = bpf_firewall_read_accounting(fd, &value, NULL);
3243 else
3244 r = bpf_firewall_read_accounting(fd, NULL, &value);
3245 if (r < 0)
3246 return r;
3247
3248 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
3249 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
3250 * ip_accounting_extra[] field, and add them in here transparently. */
3251
3252 *ret = value + u->ip_accounting_extra[metric];
3253
3254 return r;
3255 }
3256
3257 static int unit_get_io_accounting_raw(Unit *u, uint64_t ret[static _CGROUP_IO_ACCOUNTING_METRIC_MAX]) {
3258 static const char *const field_names[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3259 [CGROUP_IO_READ_BYTES] = "rbytes=",
3260 [CGROUP_IO_WRITE_BYTES] = "wbytes=",
3261 [CGROUP_IO_READ_OPERATIONS] = "rios=",
3262 [CGROUP_IO_WRITE_OPERATIONS] = "wios=",
3263 };
3264 uint64_t acc[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {};
3265 _cleanup_free_ char *path = NULL;
3266 _cleanup_fclose_ FILE *f = NULL;
3267 int r;
3268
3269 assert(u);
3270
3271 if (!u->cgroup_path)
3272 return -ENODATA;
3273
3274 if (unit_has_host_root_cgroup(u))
3275 return -ENODATA; /* TODO: return useful data for the top-level cgroup */
3276
3277 r = cg_all_unified();
3278 if (r < 0)
3279 return r;
3280 if (r == 0) /* TODO: support cgroupv1 */
3281 return -ENODATA;
3282
3283 if (!FLAGS_SET(u->cgroup_realized_mask, CGROUP_MASK_IO))
3284 return -ENODATA;
3285
3286 r = cg_get_path("io", u->cgroup_path, "io.stat", &path);
3287 if (r < 0)
3288 return r;
3289
3290 f = fopen(path, "re");
3291 if (!f)
3292 return -errno;
3293
3294 for (;;) {
3295 _cleanup_free_ char *line = NULL;
3296 const char *p;
3297
3298 r = read_line(f, LONG_LINE_MAX, &line);
3299 if (r < 0)
3300 return r;
3301 if (r == 0)
3302 break;
3303
3304 p = line;
3305 p += strcspn(p, WHITESPACE); /* Skip over device major/minor */
3306 p += strspn(p, WHITESPACE); /* Skip over following whitespace */
3307
3308 for (;;) {
3309 _cleanup_free_ char *word = NULL;
3310
3311 r = extract_first_word(&p, &word, NULL, EXTRACT_RETAIN_ESCAPE);
3312 if (r < 0)
3313 return r;
3314 if (r == 0)
3315 break;
3316
3317 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
3318 const char *x;
3319
3320 x = startswith(word, field_names[i]);
3321 if (x) {
3322 uint64_t w;
3323
3324 r = safe_atou64(x, &w);
3325 if (r < 0)
3326 return r;
3327
3328 /* Sum up the stats of all devices */
3329 acc[i] += w;
3330 break;
3331 }
3332 }
3333 }
3334 }
3335
3336 memcpy(ret, acc, sizeof(acc));
3337 return 0;
3338 }
3339
3340 int unit_get_io_accounting(
3341 Unit *u,
3342 CGroupIOAccountingMetric metric,
3343 bool allow_cache,
3344 uint64_t *ret) {
3345
3346 uint64_t raw[_CGROUP_IO_ACCOUNTING_METRIC_MAX];
3347 int r;
3348
3349 /* Retrieve an IO account parameter. This will subtract the counter when the unit was started. */
3350
3351 if (!UNIT_CGROUP_BOOL(u, io_accounting))
3352 return -ENODATA;
3353
3354 if (allow_cache && u->io_accounting_last[metric] != UINT64_MAX)
3355 goto done;
3356
3357 r = unit_get_io_accounting_raw(u, raw);
3358 if (r == -ENODATA && u->io_accounting_last[metric] != UINT64_MAX)
3359 goto done;
3360 if (r < 0)
3361 return r;
3362
3363 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
3364 /* Saturated subtraction */
3365 if (raw[i] > u->io_accounting_base[i])
3366 u->io_accounting_last[i] = raw[i] - u->io_accounting_base[i];
3367 else
3368 u->io_accounting_last[i] = 0;
3369 }
3370
3371 done:
3372 if (ret)
3373 *ret = u->io_accounting_last[metric];
3374
3375 return 0;
3376 }
3377
3378 int unit_reset_cpu_accounting(Unit *u) {
3379 int r;
3380
3381 assert(u);
3382
3383 u->cpu_usage_last = NSEC_INFINITY;
3384
3385 r = unit_get_cpu_usage_raw(u, &u->cpu_usage_base);
3386 if (r < 0) {
3387 u->cpu_usage_base = 0;
3388 return r;
3389 }
3390
3391 return 0;
3392 }
3393
3394 int unit_reset_ip_accounting(Unit *u) {
3395 int r = 0, q = 0;
3396
3397 assert(u);
3398
3399 if (u->ip_accounting_ingress_map_fd >= 0)
3400 r = bpf_firewall_reset_accounting(u->ip_accounting_ingress_map_fd);
3401
3402 if (u->ip_accounting_egress_map_fd >= 0)
3403 q = bpf_firewall_reset_accounting(u->ip_accounting_egress_map_fd);
3404
3405 zero(u->ip_accounting_extra);
3406
3407 return r < 0 ? r : q;
3408 }
3409
3410 int unit_reset_io_accounting(Unit *u) {
3411 int r;
3412
3413 assert(u);
3414
3415 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++)
3416 u->io_accounting_last[i] = UINT64_MAX;
3417
3418 r = unit_get_io_accounting_raw(u, u->io_accounting_base);
3419 if (r < 0) {
3420 zero(u->io_accounting_base);
3421 return r;
3422 }
3423
3424 return 0;
3425 }
3426
3427 int unit_reset_accounting(Unit *u) {
3428 int r, q, v;
3429
3430 assert(u);
3431
3432 r = unit_reset_cpu_accounting(u);
3433 q = unit_reset_io_accounting(u);
3434 v = unit_reset_ip_accounting(u);
3435
3436 return r < 0 ? r : q < 0 ? q : v;
3437 }
3438
3439 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
3440 assert(u);
3441
3442 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3443 return;
3444
3445 if (m == 0)
3446 return;
3447
3448 /* always invalidate compat pairs together */
3449 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
3450 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
3451
3452 if (m & (CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT))
3453 m |= CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT;
3454
3455 if (FLAGS_SET(u->cgroup_invalidated_mask, m)) /* NOP? */
3456 return;
3457
3458 u->cgroup_invalidated_mask |= m;
3459 unit_add_to_cgroup_realize_queue(u);
3460 }
3461
3462 void unit_invalidate_cgroup_bpf(Unit *u) {
3463 assert(u);
3464
3465 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3466 return;
3467
3468 if (u->cgroup_invalidated_mask & CGROUP_MASK_BPF_FIREWALL) /* NOP? */
3469 return;
3470
3471 u->cgroup_invalidated_mask |= CGROUP_MASK_BPF_FIREWALL;
3472 unit_add_to_cgroup_realize_queue(u);
3473
3474 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
3475 * list of our children includes our own. */
3476 if (u->type == UNIT_SLICE) {
3477 Unit *member;
3478 Iterator i;
3479 void *v;
3480
3481 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE], i) {
3482 if (UNIT_DEREF(member->slice) == u)
3483 unit_invalidate_cgroup_bpf(member);
3484 }
3485 }
3486 }
3487
3488 bool unit_cgroup_delegate(Unit *u) {
3489 CGroupContext *c;
3490
3491 assert(u);
3492
3493 if (!UNIT_VTABLE(u)->can_delegate)
3494 return false;
3495
3496 c = unit_get_cgroup_context(u);
3497 if (!c)
3498 return false;
3499
3500 return c->delegate;
3501 }
3502
3503 void manager_invalidate_startup_units(Manager *m) {
3504 Iterator i;
3505 Unit *u;
3506
3507 assert(m);
3508
3509 SET_FOREACH(u, m->startup_units, i)
3510 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
3511 }
3512
3513 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
3514 [CGROUP_AUTO] = "auto",
3515 [CGROUP_CLOSED] = "closed",
3516 [CGROUP_STRICT] = "strict",
3517 };
3518
3519 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);