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