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