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