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