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