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