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