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