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