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