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