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