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