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