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