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