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