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