]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/cgroup.c
Merge pull request #28797 from Werkov/eff_limits
[thirdparty/systemd.git] / src / core / cgroup.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4
5 #include "sd-messages.h"
6
7 #include "af-list.h"
8 #include "alloc-util.h"
9 #include "blockdev-util.h"
10 #include "bpf-devices.h"
11 #include "bpf-firewall.h"
12 #include "bpf-foreign.h"
13 #include "bpf-socket-bind.h"
14 #include "btrfs-util.h"
15 #include "bus-error.h"
16 #include "bus-locator.h"
17 #include "cgroup-setup.h"
18 #include "cgroup-util.h"
19 #include "cgroup.h"
20 #include "devnum-util.h"
21 #include "fd-util.h"
22 #include "fileio.h"
23 #include "firewall-util.h"
24 #include "in-addr-prefix-util.h"
25 #include "inotify-util.h"
26 #include "io-util.h"
27 #include "ip-protocol-list.h"
28 #include "limits-util.h"
29 #include "nulstr-util.h"
30 #include "parse-util.h"
31 #include "path-util.h"
32 #include "percent-util.h"
33 #include "process-util.h"
34 #include "procfs-util.h"
35 #include "restrict-ifaces.h"
36 #include "set.h"
37 #include "special.h"
38 #include "stdio-util.h"
39 #include "string-table.h"
40 #include "string-util.h"
41 #include "virt.h"
42
43 #if BPF_FRAMEWORK
44 #include "bpf-dlopen.h"
45 #include "bpf-link.h"
46 #include "bpf/restrict_fs/restrict-fs-skel.h"
47 #endif
48
49 #define CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
50
51 /* Returns the log level to use when cgroup attribute writes fail. When an attribute is missing or we have access
52 * problems we downgrade to LOG_DEBUG. This is supposed to be nice to container managers and kernels which want to mask
53 * out specific attributes from us. */
54 #define LOG_LEVEL_CGROUP_WRITE(r) (IN_SET(abs(r), ENOENT, EROFS, EACCES, EPERM) ? LOG_DEBUG : LOG_WARNING)
55
56 uint64_t cgroup_tasks_max_resolve(const CGroupTasksMax *tasks_max) {
57 if (tasks_max->scale == 0)
58 return tasks_max->value;
59
60 return system_tasks_max_scale(tasks_max->value, tasks_max->scale);
61 }
62
63 bool manager_owns_host_root_cgroup(Manager *m) {
64 assert(m);
65
66 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
67 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
68 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
69 * we run in any kind of container virtualization. */
70
71 if (MANAGER_IS_USER(m))
72 return false;
73
74 if (detect_container() > 0)
75 return false;
76
77 return empty_or_root(m->cgroup_root);
78 }
79
80 bool unit_has_startup_cgroup_constraints(Unit *u) {
81 assert(u);
82
83 /* Returns true if this unit has any directives which apply during
84 * startup/shutdown phases. */
85
86 CGroupContext *c;
87
88 c = unit_get_cgroup_context(u);
89 if (!c)
90 return false;
91
92 return c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID ||
93 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
94 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
95 c->startup_cpuset_cpus.set ||
96 c->startup_cpuset_mems.set ||
97 c->startup_memory_high_set ||
98 c->startup_memory_max_set ||
99 c->startup_memory_swap_max_set||
100 c->startup_memory_zswap_max_set ||
101 c->startup_memory_low_set;
102 }
103
104 bool unit_has_host_root_cgroup(Unit *u) {
105 assert(u);
106
107 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
108 * the manager manages the root cgroup. */
109
110 if (!manager_owns_host_root_cgroup(u->manager))
111 return false;
112
113 return unit_has_name(u, SPECIAL_ROOT_SLICE);
114 }
115
116 static int set_attribute_and_warn(Unit *u, const char *controller, const char *attribute, const char *value) {
117 int r;
118
119 r = cg_set_attribute(controller, u->cgroup_path, attribute, value);
120 if (r < 0)
121 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to set '%s' attribute on '%s' to '%.*s': %m",
122 strna(attribute), empty_to_root(u->cgroup_path), (int) strcspn(value, NEWLINE), value);
123
124 return r;
125 }
126
127 static void cgroup_compat_warn(void) {
128 static bool cgroup_compat_warned = false;
129
130 if (cgroup_compat_warned)
131 return;
132
133 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
134 "See cgroup-compat debug messages for details.");
135
136 cgroup_compat_warned = true;
137 }
138
139 #define log_cgroup_compat(unit, fmt, ...) do { \
140 cgroup_compat_warn(); \
141 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
142 } while (false)
143
144 void cgroup_context_init(CGroupContext *c) {
145 assert(c);
146
147 /* Initialize everything to the kernel defaults. When initializing a bool member to 'true', make
148 * sure to serialize in execute-serialize.c using serialize_bool() instead of
149 * serialize_bool_elide(), as sd-executor will initialize here to 'true', but serialize_bool_elide()
150 * skips serialization if the value is 'false' (as that's the common default), so if the value at
151 * runtime is zero it would be lost after deserialization. Same when initializing uint64_t and other
152 * values, update/add a conditional serialization check. This is to minimize the amount of
153 * serialized data that is sent to the sd-executor, so that there is less work to do on the default
154 * cases. */
155
156 *c = (CGroupContext) {
157 .cpu_weight = CGROUP_WEIGHT_INVALID,
158 .startup_cpu_weight = CGROUP_WEIGHT_INVALID,
159 .cpu_quota_per_sec_usec = USEC_INFINITY,
160 .cpu_quota_period_usec = USEC_INFINITY,
161
162 .cpu_shares = CGROUP_CPU_SHARES_INVALID,
163 .startup_cpu_shares = CGROUP_CPU_SHARES_INVALID,
164
165 .memory_high = CGROUP_LIMIT_MAX,
166 .startup_memory_high = CGROUP_LIMIT_MAX,
167 .memory_max = CGROUP_LIMIT_MAX,
168 .startup_memory_max = CGROUP_LIMIT_MAX,
169 .memory_swap_max = CGROUP_LIMIT_MAX,
170 .startup_memory_swap_max = CGROUP_LIMIT_MAX,
171 .memory_zswap_max = CGROUP_LIMIT_MAX,
172 .startup_memory_zswap_max = CGROUP_LIMIT_MAX,
173
174 .memory_limit = CGROUP_LIMIT_MAX,
175
176 .io_weight = CGROUP_WEIGHT_INVALID,
177 .startup_io_weight = CGROUP_WEIGHT_INVALID,
178
179 .blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
180 .startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
181
182 .tasks_max = CGROUP_TASKS_MAX_UNSET,
183
184 .moom_swap = MANAGED_OOM_AUTO,
185 .moom_mem_pressure = MANAGED_OOM_AUTO,
186 .moom_preference = MANAGED_OOM_PREFERENCE_NONE,
187
188 .memory_pressure_watch = _CGROUP_PRESSURE_WATCH_INVALID,
189 .memory_pressure_threshold_usec = USEC_INFINITY,
190 };
191 }
192
193 int cgroup_context_add_io_device_weight_dup(CGroupContext *c, CGroupIODeviceWeight *w) {
194 _cleanup_free_ CGroupIODeviceWeight *n = NULL;
195
196 assert(c);
197 assert(w);
198
199 n = new0(CGroupIODeviceWeight, 1);
200 if (!n)
201 return -ENOMEM;
202
203 n->path = strdup(w->path);
204 if (!n->path)
205 return -ENOMEM;
206 n->weight = w->weight;
207
208 LIST_PREPEND(device_weights, c->io_device_weights, TAKE_PTR(n));
209 return 0;
210 }
211
212 int cgroup_context_add_io_device_limit_dup(CGroupContext *c, CGroupIODeviceLimit *l) {
213 _cleanup_free_ CGroupIODeviceLimit *n = NULL;
214
215 assert(c);
216 assert(l);
217
218 n = new0(CGroupIODeviceLimit, 1);
219 if (!l)
220 return -ENOMEM;
221
222 n->path = strdup(l->path);
223 if (!n->path)
224 return -ENOMEM;
225
226 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
227 n->limits[type] = l->limits[type];
228
229 LIST_PREPEND(device_limits, c->io_device_limits, TAKE_PTR(n));
230 return 0;
231 }
232
233 int cgroup_context_add_io_device_latency_dup(CGroupContext *c, CGroupIODeviceLatency *l) {
234 _cleanup_free_ CGroupIODeviceLatency *n = NULL;
235
236 assert(c);
237 assert(l);
238
239 n = new0(CGroupIODeviceLatency, 1);
240 if (!n)
241 return -ENOMEM;
242
243 n->path = strdup(l->path);
244 if (!n->path)
245 return -ENOMEM;
246
247 n->target_usec = l->target_usec;
248
249 LIST_PREPEND(device_latencies, c->io_device_latencies, TAKE_PTR(n));
250 return 0;
251 }
252
253 int cgroup_context_add_block_io_device_weight_dup(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
254 _cleanup_free_ CGroupBlockIODeviceWeight *n = NULL;
255
256 assert(c);
257 assert(w);
258
259 n = new0(CGroupBlockIODeviceWeight, 1);
260 if (!n)
261 return -ENOMEM;
262
263 n->path = strdup(w->path);
264 if (!n->path)
265 return -ENOMEM;
266
267 n->weight = w->weight;
268
269 LIST_PREPEND(device_weights, c->blockio_device_weights, TAKE_PTR(n));
270 return 0;
271 }
272
273 int cgroup_context_add_block_io_device_bandwidth_dup(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
274 _cleanup_free_ CGroupBlockIODeviceBandwidth *n = NULL;
275
276 assert(c);
277 assert(b);
278
279 n = new0(CGroupBlockIODeviceBandwidth, 1);
280 if (!n)
281 return -ENOMEM;
282
283 *n = (CGroupBlockIODeviceBandwidth) {
284 .rbps = b->rbps,
285 .wbps = b->wbps,
286 };
287
288 LIST_PREPEND(device_bandwidths, c->blockio_device_bandwidths, TAKE_PTR(n));
289 return 0;
290 }
291
292 int cgroup_context_add_device_allow_dup(CGroupContext *c, CGroupDeviceAllow *a) {
293 _cleanup_free_ CGroupDeviceAllow *n = NULL;
294
295 assert(c);
296 assert(a);
297
298 n = new0(CGroupDeviceAllow, 1);
299 if (!n)
300 return -ENOMEM;
301
302 n->path = strdup(a->path);
303 if (!n->path)
304 return -ENOMEM;
305
306 n->permissions = a->permissions;
307
308 LIST_PREPEND(device_allow, c->device_allow, TAKE_PTR(n));
309 return 0;
310 }
311
312 static int cgroup_context_add_socket_bind_item_dup(CGroupContext *c, CGroupSocketBindItem *i, CGroupSocketBindItem *h) {
313 _cleanup_free_ CGroupSocketBindItem *n = NULL;
314
315 assert(c);
316 assert(i);
317
318 n = new0(CGroupSocketBindItem, 1);
319 if (!n)
320 return -ENOMEM;
321
322 *n = (CGroupSocketBindItem) {
323 .address_family = i->address_family,
324 .ip_protocol = i->ip_protocol,
325 .nr_ports = i->nr_ports,
326 .port_min = i->port_min,
327 };
328
329 LIST_PREPEND(socket_bind_items, h, TAKE_PTR(n));
330 return 0;
331 }
332
333 int cgroup_context_add_socket_bind_item_allow_dup(CGroupContext *c, CGroupSocketBindItem *i) {
334 return cgroup_context_add_socket_bind_item_dup(c, i, c->socket_bind_allow);
335 }
336
337 int cgroup_context_add_socket_bind_item_deny_dup(CGroupContext *c, CGroupSocketBindItem *i) {
338 return cgroup_context_add_socket_bind_item_dup(c, i, c->socket_bind_deny);
339 }
340
341 int cgroup_context_copy(CGroupContext *dst, const CGroupContext *src) {
342 struct in_addr_prefix *i;
343 char *iface;
344 int r;
345
346 assert(src);
347 assert(dst);
348
349 dst->cpu_accounting = src->cpu_accounting;
350 dst->io_accounting = src->io_accounting;
351 dst->blockio_accounting = src->blockio_accounting;
352 dst->memory_accounting = src->memory_accounting;
353 dst->tasks_accounting = src->tasks_accounting;
354 dst->ip_accounting = src->ip_accounting;
355
356 dst->memory_oom_group = dst->memory_oom_group;
357
358 dst->cpu_weight = src->cpu_weight;
359 dst->startup_cpu_weight = src->startup_cpu_weight;
360 dst->cpu_quota_per_sec_usec = src->cpu_quota_per_sec_usec;
361 dst->cpu_quota_period_usec = src->cpu_quota_period_usec;
362
363 dst->cpuset_cpus = src->cpuset_cpus;
364 dst->startup_cpuset_cpus = src->startup_cpuset_cpus;
365 dst->cpuset_mems = src->cpuset_mems;
366 dst->startup_cpuset_mems = src->startup_cpuset_mems;
367
368 dst->io_weight = src->io_weight;
369 dst->startup_io_weight = src->startup_io_weight;
370
371 LIST_FOREACH_BACKWARDS(device_weights, w, LIST_FIND_TAIL(device_weights, src->io_device_weights)) {
372 r = cgroup_context_add_io_device_weight_dup(dst, w);
373 if (r < 0)
374 return r;
375 }
376
377 LIST_FOREACH_BACKWARDS(device_limits, l, LIST_FIND_TAIL(device_limits, src->io_device_limits)) {
378 r = cgroup_context_add_io_device_limit_dup(dst, l);
379 if (r < 0)
380 return r;
381 }
382
383 LIST_FOREACH_BACKWARDS(device_latencies, l, LIST_FIND_TAIL(device_latencies, src->io_device_latencies)) {
384 r = cgroup_context_add_io_device_latency_dup(dst, l);
385 if (r < 0)
386 return r;
387 }
388
389 dst->default_memory_min = src->default_memory_min;
390 dst->default_memory_low = src->default_memory_low;
391 dst->default_startup_memory_low = src->default_startup_memory_low;
392 dst->memory_min = src->memory_min;
393 dst->memory_low = src->memory_low;
394 dst->startup_memory_low = src->startup_memory_low;
395 dst->memory_high = src->memory_high;
396 dst->startup_memory_high = src->startup_memory_high;
397 dst->memory_max = src->memory_max;
398 dst->startup_memory_max = src->startup_memory_max;
399 dst->memory_swap_max = src->memory_swap_max;
400 dst->startup_memory_swap_max = src->startup_memory_swap_max;
401 dst->memory_zswap_max = src->memory_zswap_max;
402 dst->startup_memory_zswap_max = src->startup_memory_zswap_max;
403
404 dst->default_memory_min_set = src->default_memory_min_set;
405 dst->default_memory_low_set = src->default_memory_low_set;
406 dst->default_startup_memory_low_set = src->default_startup_memory_low_set;
407 dst->memory_min_set = src->memory_min_set;
408 dst->memory_low_set = src->memory_low_set;
409 dst->startup_memory_low_set = src->startup_memory_low_set;
410 dst->startup_memory_high_set = src->startup_memory_high_set;
411 dst->startup_memory_max_set = src->startup_memory_max_set;
412 dst->startup_memory_swap_max_set = src->startup_memory_swap_max_set;
413 dst->startup_memory_zswap_max_set = src->startup_memory_zswap_max_set;
414
415 SET_FOREACH(i, src->ip_address_allow) {
416 r = in_addr_prefix_add(&dst->ip_address_allow, i);
417 if (r < 0)
418 return r;
419 }
420
421 SET_FOREACH(i, src->ip_address_deny) {
422 r = in_addr_prefix_add(&dst->ip_address_deny, i);
423 if (r < 0)
424 return r;
425 }
426
427 dst->ip_address_allow_reduced = src->ip_address_allow_reduced;
428 dst->ip_address_deny_reduced = src->ip_address_deny_reduced;
429
430 if (!strv_isempty(src->ip_filters_ingress)) {
431 dst->ip_filters_ingress = strv_copy(src->ip_filters_ingress);
432 if (!dst->ip_filters_ingress)
433 return -ENOMEM;
434 }
435
436 if (!strv_isempty(src->ip_filters_egress)) {
437 dst->ip_filters_egress = strv_copy(src->ip_filters_egress);
438 if (!dst->ip_filters_egress)
439 return -ENOMEM;
440 }
441
442 LIST_FOREACH_BACKWARDS(programs, l, LIST_FIND_TAIL(programs, src->bpf_foreign_programs)) {
443 r = cgroup_context_add_bpf_foreign_program_dup(dst, l);
444 if (r < 0)
445 return r;
446 }
447
448 SET_FOREACH(iface, src->restrict_network_interfaces) {
449 r = set_put_strdup(&dst->restrict_network_interfaces, iface);
450 if (r < 0)
451 return r;
452 }
453 dst->restrict_network_interfaces_is_allow_list = src->restrict_network_interfaces_is_allow_list;
454
455 dst->cpu_shares = src->cpu_shares;
456 dst->startup_cpu_shares = src->startup_cpu_shares;
457
458 dst->blockio_weight = src->blockio_weight;
459 dst->startup_blockio_weight = src->startup_blockio_weight;
460
461 LIST_FOREACH_BACKWARDS(device_weights, l, LIST_FIND_TAIL(device_weights, src->blockio_device_weights)) {
462 r = cgroup_context_add_block_io_device_weight_dup(dst, l);
463 if (r < 0)
464 return r;
465 }
466
467 LIST_FOREACH_BACKWARDS(device_bandwidths, l, LIST_FIND_TAIL(device_bandwidths, src->blockio_device_bandwidths)) {
468 r = cgroup_context_add_block_io_device_bandwidth_dup(dst, l);
469 if (r < 0)
470 return r;
471 }
472
473 dst->memory_limit = src->memory_limit;
474
475 dst->device_policy = src->device_policy;
476 LIST_FOREACH_BACKWARDS(device_allow, l, LIST_FIND_TAIL(device_allow, src->device_allow)) {
477 r = cgroup_context_add_device_allow_dup(dst, l);
478 if (r < 0)
479 return r;
480 }
481
482 LIST_FOREACH_BACKWARDS(socket_bind_items, l, LIST_FIND_TAIL(socket_bind_items, src->socket_bind_allow)) {
483 r = cgroup_context_add_socket_bind_item_allow_dup(dst, l);
484 if (r < 0)
485 return r;
486
487 }
488
489 LIST_FOREACH_BACKWARDS(socket_bind_items, l, LIST_FIND_TAIL(socket_bind_items, src->socket_bind_deny)) {
490 r = cgroup_context_add_socket_bind_item_deny_dup(dst, l);
491 if (r < 0)
492 return r;
493 }
494
495 dst->tasks_max = src->tasks_max;
496
497 return 0;
498 }
499
500 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
501 assert(c);
502 assert(a);
503
504 LIST_REMOVE(device_allow, c->device_allow, a);
505 free(a->path);
506 free(a);
507 }
508
509 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
510 assert(c);
511 assert(w);
512
513 LIST_REMOVE(device_weights, c->io_device_weights, w);
514 free(w->path);
515 free(w);
516 }
517
518 void cgroup_context_free_io_device_latency(CGroupContext *c, CGroupIODeviceLatency *l) {
519 assert(c);
520 assert(l);
521
522 LIST_REMOVE(device_latencies, c->io_device_latencies, l);
523 free(l->path);
524 free(l);
525 }
526
527 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
528 assert(c);
529 assert(l);
530
531 LIST_REMOVE(device_limits, c->io_device_limits, l);
532 free(l->path);
533 free(l);
534 }
535
536 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
537 assert(c);
538 assert(w);
539
540 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
541 free(w->path);
542 free(w);
543 }
544
545 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
546 assert(c);
547 assert(b);
548
549 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
550 free(b->path);
551 free(b);
552 }
553
554 void cgroup_context_remove_bpf_foreign_program(CGroupContext *c, CGroupBPFForeignProgram *p) {
555 assert(c);
556 assert(p);
557
558 LIST_REMOVE(programs, c->bpf_foreign_programs, p);
559 free(p->bpffs_path);
560 free(p);
561 }
562
563 void cgroup_context_remove_socket_bind(CGroupSocketBindItem **head) {
564 assert(head);
565
566 LIST_CLEAR(socket_bind_items, *head, free);
567 }
568
569 void cgroup_context_done(CGroupContext *c) {
570 assert(c);
571
572 while (c->io_device_weights)
573 cgroup_context_free_io_device_weight(c, c->io_device_weights);
574
575 while (c->io_device_latencies)
576 cgroup_context_free_io_device_latency(c, c->io_device_latencies);
577
578 while (c->io_device_limits)
579 cgroup_context_free_io_device_limit(c, c->io_device_limits);
580
581 while (c->blockio_device_weights)
582 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
583
584 while (c->blockio_device_bandwidths)
585 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
586
587 while (c->device_allow)
588 cgroup_context_free_device_allow(c, c->device_allow);
589
590 cgroup_context_remove_socket_bind(&c->socket_bind_allow);
591 cgroup_context_remove_socket_bind(&c->socket_bind_deny);
592
593 c->ip_address_allow = set_free(c->ip_address_allow);
594 c->ip_address_deny = set_free(c->ip_address_deny);
595
596 c->ip_filters_ingress = strv_free(c->ip_filters_ingress);
597 c->ip_filters_egress = strv_free(c->ip_filters_egress);
598
599 while (c->bpf_foreign_programs)
600 cgroup_context_remove_bpf_foreign_program(c, c->bpf_foreign_programs);
601
602 c->restrict_network_interfaces = set_free_free(c->restrict_network_interfaces);
603
604 cpu_set_reset(&c->cpuset_cpus);
605 cpu_set_reset(&c->startup_cpuset_cpus);
606 cpu_set_reset(&c->cpuset_mems);
607 cpu_set_reset(&c->startup_cpuset_mems);
608
609 c->delegate_subgroup = mfree(c->delegate_subgroup);
610
611 nft_set_context_clear(&c->nft_set_context);
612 }
613
614 static int unit_get_kernel_memory_limit(Unit *u, const char *file, uint64_t *ret) {
615 assert(u);
616
617 if (!u->cgroup_realized)
618 return -EOWNERDEAD;
619
620 return cg_get_attribute_as_uint64("memory", u->cgroup_path, file, ret);
621 }
622
623 static int unit_compare_memory_limit(Unit *u, const char *property_name, uint64_t *ret_unit_value, uint64_t *ret_kernel_value) {
624 CGroupContext *c;
625 CGroupMask m;
626 const char *file;
627 uint64_t unit_value;
628 int r;
629
630 /* Compare kernel memcg configuration against our internal systemd state. Unsupported (and will
631 * return -ENODATA) on cgroup v1.
632 *
633 * Returns:
634 *
635 * <0: On error.
636 * 0: If the kernel memory setting doesn't match our configuration.
637 * >0: If the kernel memory setting matches our configuration.
638 *
639 * The following values are only guaranteed to be populated on return >=0:
640 *
641 * - ret_unit_value will contain our internal expected value for the unit, page-aligned.
642 * - ret_kernel_value will contain the actual value presented by the kernel. */
643
644 assert(u);
645
646 r = cg_all_unified();
647 if (r < 0)
648 return log_debug_errno(r, "Failed to determine cgroup hierarchy version: %m");
649
650 /* Unsupported on v1.
651 *
652 * We don't return ENOENT, since that could actually mask a genuine problem where somebody else has
653 * silently masked the controller. */
654 if (r == 0)
655 return -ENODATA;
656
657 /* The root slice doesn't have any controller files, so we can't compare anything. */
658 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
659 return -ENODATA;
660
661 /* It's possible to have MemoryFoo set without systemd wanting to have the memory controller enabled,
662 * for example, in the case of DisableControllers= or cgroup_disable on the kernel command line. To
663 * avoid specious errors in these scenarios, check that we even expect the memory controller to be
664 * enabled at all. */
665 m = unit_get_target_mask(u);
666 if (!FLAGS_SET(m, CGROUP_MASK_MEMORY))
667 return -ENODATA;
668
669 assert_se(c = unit_get_cgroup_context(u));
670
671 bool startup = u->manager && IN_SET(manager_state(u->manager), MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING);
672
673 if (streq(property_name, "MemoryLow")) {
674 unit_value = unit_get_ancestor_memory_low(u);
675 file = "memory.low";
676 } else if (startup && streq(property_name, "StartupMemoryLow")) {
677 unit_value = unit_get_ancestor_startup_memory_low(u);
678 file = "memory.low";
679 } else if (streq(property_name, "MemoryMin")) {
680 unit_value = unit_get_ancestor_memory_min(u);
681 file = "memory.min";
682 } else if (streq(property_name, "MemoryHigh")) {
683 unit_value = c->memory_high;
684 file = "memory.high";
685 } else if (startup && streq(property_name, "StartupMemoryHigh")) {
686 unit_value = c->startup_memory_high;
687 file = "memory.high";
688 } else if (streq(property_name, "MemoryMax")) {
689 unit_value = c->memory_max;
690 file = "memory.max";
691 } else if (startup && streq(property_name, "StartupMemoryMax")) {
692 unit_value = c->startup_memory_max;
693 file = "memory.max";
694 } else if (streq(property_name, "MemorySwapMax")) {
695 unit_value = c->memory_swap_max;
696 file = "memory.swap.max";
697 } else if (startup && streq(property_name, "StartupMemorySwapMax")) {
698 unit_value = c->startup_memory_swap_max;
699 file = "memory.swap.max";
700 } else if (streq(property_name, "MemoryZSwapMax")) {
701 unit_value = c->memory_zswap_max;
702 file = "memory.zswap.max";
703 } else if (startup && streq(property_name, "StartupMemoryZSwapMax")) {
704 unit_value = c->startup_memory_zswap_max;
705 file = "memory.zswap.max";
706 } else
707 return -EINVAL;
708
709 r = unit_get_kernel_memory_limit(u, file, ret_kernel_value);
710 if (r < 0)
711 return log_unit_debug_errno(u, r, "Failed to parse %s: %m", file);
712
713 /* It's intended (soon) in a future kernel to not expose cgroup memory limits rounded to page
714 * boundaries, but instead separate the user-exposed limit, which is whatever userspace told us, from
715 * our internal page-counting. To support those future kernels, just check the value itself first
716 * without any page-alignment. */
717 if (*ret_kernel_value == unit_value) {
718 *ret_unit_value = unit_value;
719 return 1;
720 }
721
722 /* The current kernel behaviour, by comparison, is that even if you write a particular number of
723 * bytes into a cgroup memory file, it always returns that number page-aligned down (since the kernel
724 * internally stores cgroup limits in pages). As such, so long as it aligns properly, everything is
725 * cricket. */
726 if (unit_value != CGROUP_LIMIT_MAX)
727 unit_value = PAGE_ALIGN_DOWN(unit_value);
728
729 *ret_unit_value = unit_value;
730
731 return *ret_kernel_value == *ret_unit_value;
732 }
733
734 #define FORMAT_CGROUP_DIFF_MAX 128
735
736 static char *format_cgroup_memory_limit_comparison(char *buf, size_t l, Unit *u, const char *property_name) {
737 uint64_t kval, sval;
738 int r;
739
740 assert(u);
741 assert(buf);
742 assert(l > 0);
743
744 r = unit_compare_memory_limit(u, property_name, &sval, &kval);
745
746 /* memory.swap.max is special in that it relies on CONFIG_MEMCG_SWAP (and the default swapaccount=1).
747 * In the absence of reliably being able to detect whether memcg swap support is available or not,
748 * only complain if the error is not ENOENT. This is similarly the case for memory.zswap.max relying
749 * on CONFIG_ZSWAP. */
750 if (r > 0 || IN_SET(r, -ENODATA, -EOWNERDEAD) ||
751 (r == -ENOENT && STR_IN_SET(property_name,
752 "MemorySwapMax",
753 "StartupMemorySwapMax",
754 "MemoryZSwapMax",
755 "StartupMemoryZSwapMax")))
756 buf[0] = 0;
757 else if (r < 0) {
758 errno = -r;
759 (void) snprintf(buf, l, " (error getting kernel value: %m)");
760 } else
761 (void) snprintf(buf, l, " (different value in kernel: %" PRIu64 ")", kval);
762
763 return buf;
764 }
765
766 const char *cgroup_device_permissions_to_string(CGroupDevicePermissions p) {
767 static const char *table[_CGROUP_DEVICE_PERMISSIONS_MAX] = {
768 /* Lets simply define a table with every possible combination. As long as those are just 8 we
769 * can get away with it. If this ever grows to more we need to revisit this logic though. */
770 [0] = "",
771 [CGROUP_DEVICE_READ] = "r",
772 [CGROUP_DEVICE_WRITE] = "w",
773 [CGROUP_DEVICE_MKNOD] = "m",
774 [CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE] = "rw",
775 [CGROUP_DEVICE_READ|CGROUP_DEVICE_MKNOD] = "rm",
776 [CGROUP_DEVICE_WRITE|CGROUP_DEVICE_MKNOD] = "wm",
777 [CGROUP_DEVICE_READ|CGROUP_DEVICE_WRITE|CGROUP_DEVICE_MKNOD] = "rwm",
778 };
779
780 if (p < 0 || p >= _CGROUP_DEVICE_PERMISSIONS_MAX)
781 return NULL;
782
783 return table[p];
784 }
785
786 CGroupDevicePermissions cgroup_device_permissions_from_string(const char *s) {
787 CGroupDevicePermissions p = 0;
788
789 if (!s)
790 return _CGROUP_DEVICE_PERMISSIONS_INVALID;
791
792 for (const char *c = s; *c; c++) {
793 if (*c == 'r')
794 p |= CGROUP_DEVICE_READ;
795 else if (*c == 'w')
796 p |= CGROUP_DEVICE_WRITE;
797 else if (*c == 'm')
798 p |= CGROUP_DEVICE_MKNOD;
799 else
800 return _CGROUP_DEVICE_PERMISSIONS_INVALID;
801 }
802
803 return p;
804 }
805
806 void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
807 _cleanup_free_ char *disable_controllers_str = NULL, *delegate_controllers_str = NULL, *cpuset_cpus = NULL, *cpuset_mems = NULL, *startup_cpuset_cpus = NULL, *startup_cpuset_mems = NULL;
808 CGroupContext *c;
809 struct in_addr_prefix *iaai;
810
811 char cda[FORMAT_CGROUP_DIFF_MAX];
812 char cdb[FORMAT_CGROUP_DIFF_MAX];
813 char cdc[FORMAT_CGROUP_DIFF_MAX];
814 char cdd[FORMAT_CGROUP_DIFF_MAX];
815 char cde[FORMAT_CGROUP_DIFF_MAX];
816 char cdf[FORMAT_CGROUP_DIFF_MAX];
817 char cdg[FORMAT_CGROUP_DIFF_MAX];
818 char cdh[FORMAT_CGROUP_DIFF_MAX];
819 char cdi[FORMAT_CGROUP_DIFF_MAX];
820 char cdj[FORMAT_CGROUP_DIFF_MAX];
821 char cdk[FORMAT_CGROUP_DIFF_MAX];
822
823 assert(u);
824 assert(f);
825
826 assert_se(c = unit_get_cgroup_context(u));
827
828 prefix = strempty(prefix);
829
830 (void) cg_mask_to_string(c->disable_controllers, &disable_controllers_str);
831 (void) cg_mask_to_string(c->delegate_controllers, &delegate_controllers_str);
832
833 /* "Delegate=" means "yes, but no controllers". Show this as "(none)". */
834 const char *delegate_str = delegate_controllers_str ?: c->delegate ? "(none)" : "no";
835
836 cpuset_cpus = cpu_set_to_range_string(&c->cpuset_cpus);
837 startup_cpuset_cpus = cpu_set_to_range_string(&c->startup_cpuset_cpus);
838 cpuset_mems = cpu_set_to_range_string(&c->cpuset_mems);
839 startup_cpuset_mems = cpu_set_to_range_string(&c->startup_cpuset_mems);
840
841 fprintf(f,
842 "%sCPUAccounting: %s\n"
843 "%sIOAccounting: %s\n"
844 "%sBlockIOAccounting: %s\n"
845 "%sMemoryAccounting: %s\n"
846 "%sTasksAccounting: %s\n"
847 "%sIPAccounting: %s\n"
848 "%sCPUWeight: %" PRIu64 "\n"
849 "%sStartupCPUWeight: %" PRIu64 "\n"
850 "%sCPUShares: %" PRIu64 "\n"
851 "%sStartupCPUShares: %" PRIu64 "\n"
852 "%sCPUQuotaPerSecSec: %s\n"
853 "%sCPUQuotaPeriodSec: %s\n"
854 "%sAllowedCPUs: %s\n"
855 "%sStartupAllowedCPUs: %s\n"
856 "%sAllowedMemoryNodes: %s\n"
857 "%sStartupAllowedMemoryNodes: %s\n"
858 "%sIOWeight: %" PRIu64 "\n"
859 "%sStartupIOWeight: %" PRIu64 "\n"
860 "%sBlockIOWeight: %" PRIu64 "\n"
861 "%sStartupBlockIOWeight: %" PRIu64 "\n"
862 "%sDefaultMemoryMin: %" PRIu64 "\n"
863 "%sDefaultMemoryLow: %" PRIu64 "\n"
864 "%sMemoryMin: %" PRIu64 "%s\n"
865 "%sMemoryLow: %" PRIu64 "%s\n"
866 "%sStartupMemoryLow: %" PRIu64 "%s\n"
867 "%sMemoryHigh: %" PRIu64 "%s\n"
868 "%sStartupMemoryHigh: %" PRIu64 "%s\n"
869 "%sMemoryMax: %" PRIu64 "%s\n"
870 "%sStartupMemoryMax: %" PRIu64 "%s\n"
871 "%sMemorySwapMax: %" PRIu64 "%s\n"
872 "%sStartupMemorySwapMax: %" PRIu64 "%s\n"
873 "%sMemoryZSwapMax: %" PRIu64 "%s\n"
874 "%sStartupMemoryZSwapMax: %" PRIu64 "%s\n"
875 "%sMemoryLimit: %" PRIu64 "\n"
876 "%sTasksMax: %" PRIu64 "\n"
877 "%sDevicePolicy: %s\n"
878 "%sDisableControllers: %s\n"
879 "%sDelegate: %s\n"
880 "%sManagedOOMSwap: %s\n"
881 "%sManagedOOMMemoryPressure: %s\n"
882 "%sManagedOOMMemoryPressureLimit: " PERMYRIAD_AS_PERCENT_FORMAT_STR "\n"
883 "%sManagedOOMPreference: %s\n"
884 "%sMemoryPressureWatch: %s\n"
885 "%sCoredumpReceive: %s\n",
886 prefix, yes_no(c->cpu_accounting),
887 prefix, yes_no(c->io_accounting),
888 prefix, yes_no(c->blockio_accounting),
889 prefix, yes_no(c->memory_accounting),
890 prefix, yes_no(c->tasks_accounting),
891 prefix, yes_no(c->ip_accounting),
892 prefix, c->cpu_weight,
893 prefix, c->startup_cpu_weight,
894 prefix, c->cpu_shares,
895 prefix, c->startup_cpu_shares,
896 prefix, FORMAT_TIMESPAN(c->cpu_quota_per_sec_usec, 1),
897 prefix, FORMAT_TIMESPAN(c->cpu_quota_period_usec, 1),
898 prefix, strempty(cpuset_cpus),
899 prefix, strempty(startup_cpuset_cpus),
900 prefix, strempty(cpuset_mems),
901 prefix, strempty(startup_cpuset_mems),
902 prefix, c->io_weight,
903 prefix, c->startup_io_weight,
904 prefix, c->blockio_weight,
905 prefix, c->startup_blockio_weight,
906 prefix, c->default_memory_min,
907 prefix, c->default_memory_low,
908 prefix, c->memory_min, format_cgroup_memory_limit_comparison(cda, sizeof(cda), u, "MemoryMin"),
909 prefix, c->memory_low, format_cgroup_memory_limit_comparison(cdb, sizeof(cdb), u, "MemoryLow"),
910 prefix, c->startup_memory_low, format_cgroup_memory_limit_comparison(cdc, sizeof(cdc), u, "StartupMemoryLow"),
911 prefix, c->memory_high, format_cgroup_memory_limit_comparison(cdd, sizeof(cdd), u, "MemoryHigh"),
912 prefix, c->startup_memory_high, format_cgroup_memory_limit_comparison(cde, sizeof(cde), u, "StartupMemoryHigh"),
913 prefix, c->memory_max, format_cgroup_memory_limit_comparison(cdf, sizeof(cdf), u, "MemoryMax"),
914 prefix, c->startup_memory_max, format_cgroup_memory_limit_comparison(cdg, sizeof(cdg), u, "StartupMemoryMax"),
915 prefix, c->memory_swap_max, format_cgroup_memory_limit_comparison(cdh, sizeof(cdh), u, "MemorySwapMax"),
916 prefix, c->startup_memory_swap_max, format_cgroup_memory_limit_comparison(cdi, sizeof(cdi), u, "StartupMemorySwapMax"),
917 prefix, c->memory_zswap_max, format_cgroup_memory_limit_comparison(cdj, sizeof(cdj), u, "MemoryZSwapMax"),
918 prefix, c->startup_memory_zswap_max, format_cgroup_memory_limit_comparison(cdk, sizeof(cdk), u, "StartupMemoryZSwapMax"),
919 prefix, c->memory_limit,
920 prefix, cgroup_tasks_max_resolve(&c->tasks_max),
921 prefix, cgroup_device_policy_to_string(c->device_policy),
922 prefix, strempty(disable_controllers_str),
923 prefix, delegate_str,
924 prefix, managed_oom_mode_to_string(c->moom_swap),
925 prefix, managed_oom_mode_to_string(c->moom_mem_pressure),
926 prefix, PERMYRIAD_AS_PERCENT_FORMAT_VAL(UINT32_SCALE_TO_PERMYRIAD(c->moom_mem_pressure_limit)),
927 prefix, managed_oom_preference_to_string(c->moom_preference),
928 prefix, cgroup_pressure_watch_to_string(c->memory_pressure_watch),
929 prefix, yes_no(c->coredump_receive));
930
931 if (c->delegate_subgroup)
932 fprintf(f, "%sDelegateSubgroup: %s\n",
933 prefix, c->delegate_subgroup);
934
935 if (c->memory_pressure_threshold_usec != USEC_INFINITY)
936 fprintf(f, "%sMemoryPressureThresholdSec: %s\n",
937 prefix, FORMAT_TIMESPAN(c->memory_pressure_threshold_usec, 1));
938
939 LIST_FOREACH(device_allow, a, c->device_allow)
940 /* strna() below should be redundant, for avoiding -Werror=format-overflow= error. See #30223. */
941 fprintf(f,
942 "%sDeviceAllow: %s %s\n",
943 prefix,
944 a->path,
945 strna(cgroup_device_permissions_to_string(a->permissions)));
946
947 LIST_FOREACH(device_weights, iw, c->io_device_weights)
948 fprintf(f,
949 "%sIODeviceWeight: %s %" PRIu64 "\n",
950 prefix,
951 iw->path,
952 iw->weight);
953
954 LIST_FOREACH(device_latencies, l, c->io_device_latencies)
955 fprintf(f,
956 "%sIODeviceLatencyTargetSec: %s %s\n",
957 prefix,
958 l->path,
959 FORMAT_TIMESPAN(l->target_usec, 1));
960
961 LIST_FOREACH(device_limits, il, c->io_device_limits)
962 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
963 if (il->limits[type] != cgroup_io_limit_defaults[type])
964 fprintf(f,
965 "%s%s: %s %s\n",
966 prefix,
967 cgroup_io_limit_type_to_string(type),
968 il->path,
969 FORMAT_BYTES(il->limits[type]));
970
971 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
972 fprintf(f,
973 "%sBlockIODeviceWeight: %s %" PRIu64,
974 prefix,
975 w->path,
976 w->weight);
977
978 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
979 if (b->rbps != CGROUP_LIMIT_MAX)
980 fprintf(f,
981 "%sBlockIOReadBandwidth: %s %s\n",
982 prefix,
983 b->path,
984 FORMAT_BYTES(b->rbps));
985 if (b->wbps != CGROUP_LIMIT_MAX)
986 fprintf(f,
987 "%sBlockIOWriteBandwidth: %s %s\n",
988 prefix,
989 b->path,
990 FORMAT_BYTES(b->wbps));
991 }
992
993 SET_FOREACH(iaai, c->ip_address_allow)
994 fprintf(f, "%sIPAddressAllow: %s\n", prefix,
995 IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
996 SET_FOREACH(iaai, c->ip_address_deny)
997 fprintf(f, "%sIPAddressDeny: %s\n", prefix,
998 IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
999
1000 STRV_FOREACH(path, c->ip_filters_ingress)
1001 fprintf(f, "%sIPIngressFilterPath: %s\n", prefix, *path);
1002 STRV_FOREACH(path, c->ip_filters_egress)
1003 fprintf(f, "%sIPEgressFilterPath: %s\n", prefix, *path);
1004
1005 LIST_FOREACH(programs, p, c->bpf_foreign_programs)
1006 fprintf(f, "%sBPFProgram: %s:%s",
1007 prefix, bpf_cgroup_attach_type_to_string(p->attach_type), p->bpffs_path);
1008
1009 if (c->socket_bind_allow) {
1010 fprintf(f, "%sSocketBindAllow: ", prefix);
1011 cgroup_context_dump_socket_bind_items(c->socket_bind_allow, f);
1012 fputc('\n', f);
1013 }
1014
1015 if (c->socket_bind_deny) {
1016 fprintf(f, "%sSocketBindDeny: ", prefix);
1017 cgroup_context_dump_socket_bind_items(c->socket_bind_deny, f);
1018 fputc('\n', f);
1019 }
1020
1021 if (c->restrict_network_interfaces) {
1022 char *iface;
1023 SET_FOREACH(iface, c->restrict_network_interfaces)
1024 fprintf(f, "%sRestrictNetworkInterfaces: %s\n", prefix, iface);
1025 }
1026
1027 FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets)
1028 fprintf(f, "%sNFTSet: %s:%s:%s:%s\n", prefix, nft_set_source_to_string(nft_set->source),
1029 nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set);
1030 }
1031
1032 void cgroup_context_dump_socket_bind_item(const CGroupSocketBindItem *item, FILE *f) {
1033 const char *family, *colon1, *protocol = "", *colon2 = "";
1034
1035 family = strempty(af_to_ipv4_ipv6(item->address_family));
1036 colon1 = isempty(family) ? "" : ":";
1037
1038 if (item->ip_protocol != 0) {
1039 protocol = ip_protocol_to_tcp_udp(item->ip_protocol);
1040 colon2 = ":";
1041 }
1042
1043 if (item->nr_ports == 0)
1044 fprintf(f, "%s%s%s%sany", family, colon1, protocol, colon2);
1045 else if (item->nr_ports == 1)
1046 fprintf(f, "%s%s%s%s%" PRIu16, family, colon1, protocol, colon2, item->port_min);
1047 else {
1048 uint16_t port_max = item->port_min + item->nr_ports - 1;
1049 fprintf(f, "%s%s%s%s%" PRIu16 "-%" PRIu16, family, colon1, protocol, colon2,
1050 item->port_min, port_max);
1051 }
1052 }
1053
1054 void cgroup_context_dump_socket_bind_items(const CGroupSocketBindItem *items, FILE *f) {
1055 bool first = true;
1056
1057 LIST_FOREACH(socket_bind_items, bi, items) {
1058 if (first)
1059 first = false;
1060 else
1061 fputc(' ', f);
1062
1063 cgroup_context_dump_socket_bind_item(bi, f);
1064 }
1065 }
1066
1067 int cgroup_context_add_device_allow(CGroupContext *c, const char *dev, CGroupDevicePermissions p) {
1068 _cleanup_free_ CGroupDeviceAllow *a = NULL;
1069 _cleanup_free_ char *d = NULL;
1070
1071 assert(c);
1072 assert(dev);
1073 assert(p >= 0 && p < _CGROUP_DEVICE_PERMISSIONS_MAX);
1074
1075 if (p == 0)
1076 p = _CGROUP_DEVICE_PERMISSIONS_ALL;
1077
1078 a = new(CGroupDeviceAllow, 1);
1079 if (!a)
1080 return -ENOMEM;
1081
1082 d = strdup(dev);
1083 if (!d)
1084 return -ENOMEM;
1085
1086 *a = (CGroupDeviceAllow) {
1087 .path = TAKE_PTR(d),
1088 .permissions = p,
1089 };
1090
1091 LIST_PREPEND(device_allow, c->device_allow, a);
1092 TAKE_PTR(a);
1093
1094 return 0;
1095 }
1096
1097 int cgroup_context_add_or_update_device_allow(CGroupContext *c, const char *dev, CGroupDevicePermissions p) {
1098 assert(c);
1099 assert(dev);
1100 assert(p >= 0 && p < _CGROUP_DEVICE_PERMISSIONS_MAX);
1101
1102 if (p == 0)
1103 p = _CGROUP_DEVICE_PERMISSIONS_ALL;
1104
1105 LIST_FOREACH(device_allow, b, c->device_allow)
1106 if (path_equal(b->path, dev)) {
1107 b->permissions = p;
1108 return 0;
1109 }
1110
1111 return cgroup_context_add_device_allow(c, dev, p);
1112 }
1113
1114 int cgroup_context_add_bpf_foreign_program(CGroupContext *c, uint32_t attach_type, const char *bpffs_path) {
1115 CGroupBPFForeignProgram *p;
1116 _cleanup_free_ char *d = NULL;
1117
1118 assert(c);
1119 assert(bpffs_path);
1120
1121 if (!path_is_normalized(bpffs_path) || !path_is_absolute(bpffs_path))
1122 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not normalized: %m");
1123
1124 d = strdup(bpffs_path);
1125 if (!d)
1126 return log_oom();
1127
1128 p = new(CGroupBPFForeignProgram, 1);
1129 if (!p)
1130 return log_oom();
1131
1132 *p = (CGroupBPFForeignProgram) {
1133 .attach_type = attach_type,
1134 .bpffs_path = TAKE_PTR(d),
1135 };
1136
1137 LIST_PREPEND(programs, c->bpf_foreign_programs, TAKE_PTR(p));
1138
1139 return 0;
1140 }
1141
1142 #define UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(entry) \
1143 uint64_t unit_get_ancestor_##entry(Unit *u) { \
1144 CGroupContext *c; \
1145 \
1146 /* 1. Is entry set in this unit? If so, use that. \
1147 * 2. Is the default for this entry set in any \
1148 * ancestor? If so, use that. \
1149 * 3. Otherwise, return CGROUP_LIMIT_MIN. */ \
1150 \
1151 assert(u); \
1152 \
1153 c = unit_get_cgroup_context(u); \
1154 if (c && c->entry##_set) \
1155 return c->entry; \
1156 \
1157 while ((u = UNIT_GET_SLICE(u))) { \
1158 c = unit_get_cgroup_context(u); \
1159 if (c && c->default_##entry##_set) \
1160 return c->default_##entry; \
1161 } \
1162 \
1163 /* We've reached the root, but nobody had default for \
1164 * this entry set, so set it to the kernel default. */ \
1165 return CGROUP_LIMIT_MIN; \
1166 }
1167
1168 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_low);
1169 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(startup_memory_low);
1170 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_min);
1171
1172 static void unit_set_xattr_graceful(Unit *u, const char *name, const void *data, size_t size) {
1173 int r;
1174
1175 assert(u);
1176 assert(name);
1177
1178 if (!u->cgroup_path)
1179 return;
1180
1181 r = cg_set_xattr(u->cgroup_path, name, data, size, 0);
1182 if (r < 0)
1183 log_unit_debug_errno(u, r, "Failed to set '%s' xattr on control group %s, ignoring: %m", name, empty_to_root(u->cgroup_path));
1184 }
1185
1186 static void unit_remove_xattr_graceful(Unit *u, const char *name) {
1187 int r;
1188
1189 assert(u);
1190 assert(name);
1191
1192 if (!u->cgroup_path)
1193 return;
1194
1195 r = cg_remove_xattr(u->cgroup_path, name);
1196 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
1197 log_unit_debug_errno(u, r, "Failed to remove '%s' xattr flag on control group %s, ignoring: %m", name, empty_to_root(u->cgroup_path));
1198 }
1199
1200 static void cgroup_oomd_xattr_apply(Unit *u) {
1201 CGroupContext *c;
1202
1203 assert(u);
1204
1205 c = unit_get_cgroup_context(u);
1206 if (!c)
1207 return;
1208
1209 if (c->moom_preference == MANAGED_OOM_PREFERENCE_OMIT)
1210 unit_set_xattr_graceful(u, "user.oomd_omit", "1", 1);
1211
1212 if (c->moom_preference == MANAGED_OOM_PREFERENCE_AVOID)
1213 unit_set_xattr_graceful(u, "user.oomd_avoid", "1", 1);
1214
1215 if (c->moom_preference != MANAGED_OOM_PREFERENCE_AVOID)
1216 unit_remove_xattr_graceful(u, "user.oomd_avoid");
1217
1218 if (c->moom_preference != MANAGED_OOM_PREFERENCE_OMIT)
1219 unit_remove_xattr_graceful(u, "user.oomd_omit");
1220 }
1221
1222 static int cgroup_log_xattr_apply(Unit *u) {
1223 ExecContext *c;
1224 size_t len, allowed_patterns_len, denied_patterns_len;
1225 _cleanup_free_ char *patterns = NULL, *allowed_patterns = NULL, *denied_patterns = NULL;
1226 char *last;
1227 int r;
1228
1229 assert(u);
1230
1231 c = unit_get_exec_context(u);
1232 if (!c)
1233 /* Some unit types have a cgroup context but no exec context, so we do not log
1234 * any error here to avoid confusion. */
1235 return 0;
1236
1237 if (set_isempty(c->log_filter_allowed_patterns) && set_isempty(c->log_filter_denied_patterns)) {
1238 unit_remove_xattr_graceful(u, "user.journald_log_filter_patterns");
1239 return 0;
1240 }
1241
1242 r = set_make_nulstr(c->log_filter_allowed_patterns, &allowed_patterns, &allowed_patterns_len);
1243 if (r < 0)
1244 return log_debug_errno(r, "Failed to make nulstr from set: %m");
1245
1246 r = set_make_nulstr(c->log_filter_denied_patterns, &denied_patterns, &denied_patterns_len);
1247 if (r < 0)
1248 return log_debug_errno(r, "Failed to make nulstr from set: %m");
1249
1250 /* Use nul character separated strings without trailing nul */
1251 allowed_patterns_len = LESS_BY(allowed_patterns_len, 1u);
1252 denied_patterns_len = LESS_BY(denied_patterns_len, 1u);
1253
1254 len = allowed_patterns_len + 1 + denied_patterns_len;
1255 patterns = new(char, len);
1256 if (!patterns)
1257 return log_oom_debug();
1258
1259 last = mempcpy_safe(patterns, allowed_patterns, allowed_patterns_len);
1260 *(last++) = '\xff';
1261 memcpy_safe(last, denied_patterns, denied_patterns_len);
1262
1263 unit_set_xattr_graceful(u, "user.journald_log_filter_patterns", patterns, len);
1264
1265 return 0;
1266 }
1267
1268 static void cgroup_invocation_id_xattr_apply(Unit *u) {
1269 bool b;
1270
1271 assert(u);
1272
1273 b = !sd_id128_is_null(u->invocation_id);
1274 FOREACH_STRING(xn, "trusted.invocation_id", "user.invocation_id") {
1275 if (b)
1276 unit_set_xattr_graceful(u, xn, SD_ID128_TO_STRING(u->invocation_id), 32);
1277 else
1278 unit_remove_xattr_graceful(u, xn);
1279 }
1280 }
1281
1282 static void cgroup_coredump_xattr_apply(Unit *u) {
1283 CGroupContext *c;
1284
1285 assert(u);
1286
1287 c = unit_get_cgroup_context(u);
1288 if (!c)
1289 return;
1290
1291 if (unit_cgroup_delegate(u) && c->coredump_receive)
1292 unit_set_xattr_graceful(u, "user.coredump_receive", "1", 1);
1293 else
1294 unit_remove_xattr_graceful(u, "user.coredump_receive");
1295 }
1296
1297 static void cgroup_delegate_xattr_apply(Unit *u) {
1298 bool b;
1299
1300 assert(u);
1301
1302 /* Indicate on the cgroup whether delegation is on, via an xattr. This is best-effort, as old kernels
1303 * didn't support xattrs on cgroups at all. Later they got support for setting 'trusted.*' xattrs,
1304 * and even later 'user.*' xattrs. We started setting this field when 'trusted.*' was added, and
1305 * given this is now pretty much API, let's continue to support that. But also set 'user.*' as well,
1306 * since it is readable by any user, not just CAP_SYS_ADMIN. This hence comes with slightly weaker
1307 * security (as users who got delegated cgroups could turn it off if they like), but this shouldn't
1308 * be a big problem given this communicates delegation state to clients, but the manager never reads
1309 * it. */
1310 b = unit_cgroup_delegate(u);
1311 FOREACH_STRING(xn, "trusted.delegate", "user.delegate") {
1312 if (b)
1313 unit_set_xattr_graceful(u, xn, "1", 1);
1314 else
1315 unit_remove_xattr_graceful(u, xn);
1316 }
1317 }
1318
1319 static void cgroup_survive_xattr_apply(Unit *u) {
1320 int r;
1321
1322 assert(u);
1323
1324 if (u->survive_final_kill_signal) {
1325 r = cg_set_xattr(
1326 u->cgroup_path,
1327 "user.survive_final_kill_signal",
1328 "1",
1329 1,
1330 /* flags= */ 0);
1331 /* user xattr support was added in kernel v5.7 */
1332 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
1333 r = cg_set_xattr(
1334 u->cgroup_path,
1335 "trusted.survive_final_kill_signal",
1336 "1",
1337 1,
1338 /* flags= */ 0);
1339 if (r < 0)
1340 log_unit_debug_errno(u,
1341 r,
1342 "Failed to set 'survive_final_kill_signal' xattr on control "
1343 "group %s, ignoring: %m",
1344 empty_to_root(u->cgroup_path));
1345 } else {
1346 unit_remove_xattr_graceful(u, "user.survive_final_kill_signal");
1347 unit_remove_xattr_graceful(u, "trusted.survive_final_kill_signal");
1348 }
1349 }
1350
1351 static void cgroup_xattr_apply(Unit *u) {
1352 assert(u);
1353
1354 /* The 'user.*' xattrs can be set from a user manager. */
1355 cgroup_oomd_xattr_apply(u);
1356 cgroup_log_xattr_apply(u);
1357 cgroup_coredump_xattr_apply(u);
1358
1359 if (!MANAGER_IS_SYSTEM(u->manager))
1360 return;
1361
1362 cgroup_invocation_id_xattr_apply(u);
1363 cgroup_delegate_xattr_apply(u);
1364 cgroup_survive_xattr_apply(u);
1365 }
1366
1367 static int lookup_block_device(const char *p, dev_t *ret) {
1368 dev_t rdev, dev = 0;
1369 mode_t mode;
1370 int r;
1371
1372 assert(p);
1373 assert(ret);
1374
1375 r = device_path_parse_major_minor(p, &mode, &rdev);
1376 if (r == -ENODEV) { /* not a parsable device node, need to go to disk */
1377 struct stat st;
1378
1379 if (stat(p, &st) < 0)
1380 return log_warning_errno(errno, "Couldn't stat device '%s': %m", p);
1381
1382 mode = st.st_mode;
1383 rdev = st.st_rdev;
1384 dev = st.st_dev;
1385 } else if (r < 0)
1386 return log_warning_errno(r, "Failed to parse major/minor from path '%s': %m", p);
1387
1388 if (S_ISCHR(mode))
1389 return log_warning_errno(SYNTHETIC_ERRNO(ENOTBLK),
1390 "Device node '%s' is a character device, but block device needed.", p);
1391 if (S_ISBLK(mode))
1392 *ret = rdev;
1393 else if (major(dev) != 0)
1394 *ret = dev; /* If this is not a device node then use the block device this file is stored on */
1395 else {
1396 /* If this is btrfs, getting the backing block device is a bit harder */
1397 r = btrfs_get_block_device(p, ret);
1398 if (r == -ENOTTY)
1399 return log_warning_errno(SYNTHETIC_ERRNO(ENODEV),
1400 "'%s' is not a block device node, and file system block device cannot be determined or is not local.", p);
1401 if (r < 0)
1402 return log_warning_errno(r, "Failed to determine block device backing btrfs file system '%s': %m", p);
1403 }
1404
1405 /* If this is a LUKS/DM device, recursively try to get the originating block device */
1406 while (block_get_originating(*ret, ret) > 0);
1407
1408 /* If this is a partition, try to get the originating block device */
1409 (void) block_get_whole_disk(*ret, ret);
1410 return 0;
1411 }
1412
1413 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
1414 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
1415 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
1416 }
1417
1418 static bool cgroup_context_has_cpu_shares(CGroupContext *c) {
1419 return c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
1420 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID;
1421 }
1422
1423 static bool cgroup_context_has_allowed_cpus(CGroupContext *c) {
1424 return c->cpuset_cpus.set || c->startup_cpuset_cpus.set;
1425 }
1426
1427 static bool cgroup_context_has_allowed_mems(CGroupContext *c) {
1428 return c->cpuset_mems.set || c->startup_cpuset_mems.set;
1429 }
1430
1431 uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
1432 assert(c);
1433
1434 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1435 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
1436 return c->startup_cpu_weight;
1437 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
1438 return c->cpu_weight;
1439 else
1440 return CGROUP_WEIGHT_DEFAULT;
1441 }
1442
1443 static uint64_t cgroup_context_cpu_shares(CGroupContext *c, ManagerState state) {
1444 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1445 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID)
1446 return c->startup_cpu_shares;
1447 else if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID)
1448 return c->cpu_shares;
1449 else
1450 return CGROUP_CPU_SHARES_DEFAULT;
1451 }
1452
1453 static CPUSet *cgroup_context_allowed_cpus(CGroupContext *c, ManagerState state) {
1454 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1455 c->startup_cpuset_cpus.set)
1456 return &c->startup_cpuset_cpus;
1457 else
1458 return &c->cpuset_cpus;
1459 }
1460
1461 static CPUSet *cgroup_context_allowed_mems(CGroupContext *c, ManagerState state) {
1462 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1463 c->startup_cpuset_mems.set)
1464 return &c->startup_cpuset_mems;
1465 else
1466 return &c->cpuset_mems;
1467 }
1468
1469 usec_t cgroup_cpu_adjust_period(usec_t period, usec_t quota, usec_t resolution, usec_t max_period) {
1470 /* kernel uses a minimum resolution of 1ms, so both period and (quota * period)
1471 * need to be higher than that boundary. quota is specified in USecPerSec.
1472 * Additionally, period must be at most max_period. */
1473 assert(quota > 0);
1474
1475 return MIN(MAX3(period, resolution, resolution * USEC_PER_SEC / quota), max_period);
1476 }
1477
1478 static usec_t cgroup_cpu_adjust_period_and_log(Unit *u, usec_t period, usec_t quota) {
1479 usec_t new_period;
1480
1481 if (quota == USEC_INFINITY)
1482 /* Always use default period for infinity quota. */
1483 return CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
1484
1485 if (period == USEC_INFINITY)
1486 /* Default period was requested. */
1487 period = CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC;
1488
1489 /* Clamp to interval [1ms, 1s] */
1490 new_period = cgroup_cpu_adjust_period(period, quota, USEC_PER_MSEC, USEC_PER_SEC);
1491
1492 if (new_period != period) {
1493 log_unit_full(u, u->warned_clamping_cpu_quota_period ? LOG_DEBUG : LOG_WARNING,
1494 "Clamping CPU interval for cpu.max: period is now %s",
1495 FORMAT_TIMESPAN(new_period, 1));
1496 u->warned_clamping_cpu_quota_period = true;
1497 }
1498
1499 return new_period;
1500 }
1501
1502 static void cgroup_apply_unified_cpu_weight(Unit *u, uint64_t weight) {
1503 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1504
1505 if (weight == CGROUP_WEIGHT_IDLE)
1506 return;
1507 xsprintf(buf, "%" PRIu64 "\n", weight);
1508 (void) set_attribute_and_warn(u, "cpu", "cpu.weight", buf);
1509 }
1510
1511 static void cgroup_apply_unified_cpu_idle(Unit *u, uint64_t weight) {
1512 int r;
1513 bool is_idle;
1514 const char *idle_val;
1515
1516 is_idle = weight == CGROUP_WEIGHT_IDLE;
1517 idle_val = one_zero(is_idle);
1518 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.idle", idle_val);
1519 if (r < 0 && (r != -ENOENT || is_idle))
1520 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r, "Failed to set '%s' attribute on '%s' to '%s': %m",
1521 "cpu.idle", empty_to_root(u->cgroup_path), idle_val);
1522 }
1523
1524 static void cgroup_apply_unified_cpu_quota(Unit *u, usec_t quota, usec_t period) {
1525 char buf[(DECIMAL_STR_MAX(usec_t) + 1) * 2 + 1];
1526
1527 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
1528 if (quota != USEC_INFINITY)
1529 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
1530 MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC), period);
1531 else
1532 xsprintf(buf, "max " USEC_FMT "\n", period);
1533 (void) set_attribute_and_warn(u, "cpu", "cpu.max", buf);
1534 }
1535
1536 static void cgroup_apply_legacy_cpu_shares(Unit *u, uint64_t shares) {
1537 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1538
1539 xsprintf(buf, "%" PRIu64 "\n", shares);
1540 (void) set_attribute_and_warn(u, "cpu", "cpu.shares", buf);
1541 }
1542
1543 static void cgroup_apply_legacy_cpu_quota(Unit *u, usec_t quota, usec_t period) {
1544 char buf[DECIMAL_STR_MAX(usec_t) + 2];
1545
1546 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
1547
1548 xsprintf(buf, USEC_FMT "\n", period);
1549 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_period_us", buf);
1550
1551 if (quota != USEC_INFINITY) {
1552 xsprintf(buf, USEC_FMT "\n", MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC));
1553 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", buf);
1554 } else
1555 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", "-1\n");
1556 }
1557
1558 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares) {
1559 return CLAMP(shares * CGROUP_WEIGHT_DEFAULT / CGROUP_CPU_SHARES_DEFAULT,
1560 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
1561 }
1562
1563 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight) {
1564 /* we don't support idle in cgroupv1 */
1565 if (weight == CGROUP_WEIGHT_IDLE)
1566 return CGROUP_CPU_SHARES_MIN;
1567
1568 return CLAMP(weight * CGROUP_CPU_SHARES_DEFAULT / CGROUP_WEIGHT_DEFAULT,
1569 CGROUP_CPU_SHARES_MIN, CGROUP_CPU_SHARES_MAX);
1570 }
1571
1572 static void cgroup_apply_unified_cpuset(Unit *u, const CPUSet *cpus, const char *name) {
1573 _cleanup_free_ char *buf = NULL;
1574
1575 buf = cpu_set_to_range_string(cpus);
1576 if (!buf) {
1577 log_oom();
1578 return;
1579 }
1580
1581 (void) set_attribute_and_warn(u, "cpuset", name, buf);
1582 }
1583
1584 static bool cgroup_context_has_io_config(CGroupContext *c) {
1585 return c->io_accounting ||
1586 c->io_weight != CGROUP_WEIGHT_INVALID ||
1587 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
1588 c->io_device_weights ||
1589 c->io_device_latencies ||
1590 c->io_device_limits;
1591 }
1592
1593 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
1594 return c->blockio_accounting ||
1595 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
1596 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
1597 c->blockio_device_weights ||
1598 c->blockio_device_bandwidths;
1599 }
1600
1601 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
1602 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1603 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
1604 return c->startup_io_weight;
1605 if (c->io_weight != CGROUP_WEIGHT_INVALID)
1606 return c->io_weight;
1607 return CGROUP_WEIGHT_DEFAULT;
1608 }
1609
1610 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
1611 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING) &&
1612 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
1613 return c->startup_blockio_weight;
1614 if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
1615 return c->blockio_weight;
1616 return CGROUP_BLKIO_WEIGHT_DEFAULT;
1617 }
1618
1619 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
1620 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
1621 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
1622 }
1623
1624 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
1625 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
1626 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
1627 }
1628
1629 static int set_bfq_weight(Unit *u, const char *controller, dev_t dev, uint64_t io_weight) {
1630 static const char * const prop_names[] = {
1631 "IOWeight",
1632 "BlockIOWeight",
1633 "IODeviceWeight",
1634 "BlockIODeviceWeight",
1635 };
1636 static bool warned = false;
1637 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+STRLEN("\n")];
1638 const char *p;
1639 uint64_t bfq_weight;
1640 int r;
1641
1642 /* FIXME: drop this function when distro kernels properly support BFQ through "io.weight"
1643 * See also: https://github.com/systemd/systemd/pull/13335 and
1644 * https://github.com/torvalds/linux/commit/65752aef0a407e1ef17ec78a7fc31ba4e0b360f9. */
1645 p = strjoina(controller, ".bfq.weight");
1646 /* Adjust to kernel range is 1..1000, the default is 100. */
1647 bfq_weight = BFQ_WEIGHT(io_weight);
1648
1649 if (major(dev) > 0)
1650 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), bfq_weight);
1651 else
1652 xsprintf(buf, "%" PRIu64 "\n", bfq_weight);
1653
1654 r = cg_set_attribute(controller, u->cgroup_path, p, buf);
1655
1656 /* FIXME: drop this when kernels prior
1657 * 795fe54c2a82 ("bfq: Add per-device weight") v5.4
1658 * are not interesting anymore. Old kernels will fail with EINVAL, while new kernels won't return
1659 * EINVAL on properly formatted input by us. Treat EINVAL accordingly. */
1660 if (r == -EINVAL && major(dev) > 0) {
1661 if (!warned) {
1662 log_unit_warning(u, "Kernel version does not accept per-device setting in %s.", p);
1663 warned = true;
1664 }
1665 r = -EOPNOTSUPP; /* mask as unconfigured device */
1666 } else if (r >= 0 && io_weight != bfq_weight)
1667 log_unit_debug(u, "%s=%" PRIu64 " scaled to %s=%" PRIu64,
1668 prop_names[2*(major(dev) > 0) + streq(controller, "blkio")],
1669 io_weight, p, bfq_weight);
1670 return r;
1671 }
1672
1673 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
1674 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1675 dev_t dev;
1676 int r, r1, r2;
1677
1678 if (lookup_block_device(dev_path, &dev) < 0)
1679 return;
1680
1681 r1 = set_bfq_weight(u, "io", dev, io_weight);
1682
1683 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), io_weight);
1684 r2 = cg_set_attribute("io", u->cgroup_path, "io.weight", buf);
1685
1686 /* Look at the configured device, when both fail, prefer io.weight errno. */
1687 r = r2 == -EOPNOTSUPP ? r1 : r2;
1688
1689 if (r < 0)
1690 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r),
1691 r, "Failed to set 'io[.bfq].weight' attribute on '%s' to '%.*s': %m",
1692 empty_to_root(u->cgroup_path), (int) strcspn(buf, NEWLINE), buf);
1693 }
1694
1695 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
1696 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1697 dev_t dev;
1698 int r;
1699
1700 r = lookup_block_device(dev_path, &dev);
1701 if (r < 0)
1702 return;
1703
1704 xsprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), blkio_weight);
1705 (void) set_attribute_and_warn(u, "blkio", "blkio.weight_device", buf);
1706 }
1707
1708 static void cgroup_apply_io_device_latency(Unit *u, const char *dev_path, usec_t target) {
1709 char buf[DECIMAL_STR_MAX(dev_t)*2+2+7+DECIMAL_STR_MAX(uint64_t)+1];
1710 dev_t dev;
1711 int r;
1712
1713 r = lookup_block_device(dev_path, &dev);
1714 if (r < 0)
1715 return;
1716
1717 if (target != USEC_INFINITY)
1718 xsprintf(buf, DEVNUM_FORMAT_STR " target=%" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), target);
1719 else
1720 xsprintf(buf, DEVNUM_FORMAT_STR " target=max\n", DEVNUM_FORMAT_VAL(dev));
1721
1722 (void) set_attribute_and_warn(u, "io", "io.latency", buf);
1723 }
1724
1725 static void cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
1726 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)],
1727 buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
1728 dev_t dev;
1729
1730 if (lookup_block_device(dev_path, &dev) < 0)
1731 return;
1732
1733 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
1734 if (limits[type] != cgroup_io_limit_defaults[type])
1735 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
1736 else
1737 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
1738
1739 xsprintf(buf, DEVNUM_FORMAT_STR " rbps=%s wbps=%s riops=%s wiops=%s\n", DEVNUM_FORMAT_VAL(dev),
1740 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
1741 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
1742 (void) set_attribute_and_warn(u, "io", "io.max", buf);
1743 }
1744
1745 static void cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
1746 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
1747 dev_t dev;
1748
1749 if (lookup_block_device(dev_path, &dev) < 0)
1750 return;
1751
1752 sprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), rbps);
1753 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.read_bps_device", buf);
1754
1755 sprintf(buf, DEVNUM_FORMAT_STR " %" PRIu64 "\n", DEVNUM_FORMAT_VAL(dev), wbps);
1756 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.write_bps_device", buf);
1757 }
1758
1759 static bool unit_has_unified_memory_config(Unit *u) {
1760 CGroupContext *c;
1761
1762 assert(u);
1763
1764 assert_se(c = unit_get_cgroup_context(u));
1765
1766 return unit_get_ancestor_memory_min(u) > 0 ||
1767 unit_get_ancestor_memory_low(u) > 0 || unit_get_ancestor_startup_memory_low(u) > 0 ||
1768 c->memory_high != CGROUP_LIMIT_MAX || c->startup_memory_high_set ||
1769 c->memory_max != CGROUP_LIMIT_MAX || c->startup_memory_max_set ||
1770 c->memory_swap_max != CGROUP_LIMIT_MAX || c->startup_memory_swap_max_set ||
1771 c->memory_zswap_max != CGROUP_LIMIT_MAX || c->startup_memory_zswap_max_set;
1772 }
1773
1774 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
1775 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max\n";
1776
1777 if (v != CGROUP_LIMIT_MAX)
1778 xsprintf(buf, "%" PRIu64 "\n", v);
1779
1780 (void) set_attribute_and_warn(u, "memory", file, buf);
1781 }
1782
1783 static void cgroup_apply_firewall(Unit *u) {
1784 assert(u);
1785
1786 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
1787
1788 if (bpf_firewall_compile(u) < 0)
1789 return;
1790
1791 (void) bpf_firewall_load_custom(u);
1792 (void) bpf_firewall_install(u);
1793 }
1794
1795 void unit_modify_nft_set(Unit *u, bool add) {
1796 int r;
1797
1798 assert(u);
1799
1800 if (!MANAGER_IS_SYSTEM(u->manager))
1801 return;
1802
1803 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1804 return;
1805
1806 if (cg_all_unified() <= 0)
1807 return;
1808
1809 if (u->cgroup_id == 0)
1810 return;
1811
1812 if (!u->manager->fw_ctx) {
1813 r = fw_ctx_new_full(&u->manager->fw_ctx, /* init_tables= */ false);
1814 if (r < 0)
1815 return;
1816
1817 assert(u->manager->fw_ctx);
1818 }
1819
1820 CGroupContext *c = ASSERT_PTR(unit_get_cgroup_context(u));
1821
1822 FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets) {
1823 if (nft_set->source != NFT_SET_SOURCE_CGROUP)
1824 continue;
1825
1826 uint64_t element = u->cgroup_id;
1827
1828 r = nft_set_element_modify_any(u->manager->fw_ctx, add, nft_set->nfproto, nft_set->table, nft_set->set, &element, sizeof(element));
1829 if (r < 0)
1830 log_warning_errno(r, "Failed to %s NFT set: family %s, table %s, set %s, cgroup %" PRIu64 ", ignoring: %m",
1831 add? "add" : "delete", nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set, u->cgroup_id);
1832 else
1833 log_debug("%s NFT set: family %s, table %s, set %s, cgroup %" PRIu64,
1834 add? "Added" : "Deleted", nfproto_to_string(nft_set->nfproto), nft_set->table, nft_set->set, u->cgroup_id);
1835 }
1836 }
1837
1838 static void cgroup_apply_socket_bind(Unit *u) {
1839 assert(u);
1840
1841 (void) bpf_socket_bind_install(u);
1842 }
1843
1844 static void cgroup_apply_restrict_network_interfaces(Unit *u) {
1845 assert(u);
1846
1847 (void) restrict_network_interfaces_install(u);
1848 }
1849
1850 static int cgroup_apply_devices(Unit *u) {
1851 _cleanup_(bpf_program_freep) BPFProgram *prog = NULL;
1852 const char *path;
1853 CGroupContext *c;
1854 CGroupDevicePolicy policy;
1855 int r;
1856
1857 assert_se(c = unit_get_cgroup_context(u));
1858 assert_se(path = u->cgroup_path);
1859
1860 policy = c->device_policy;
1861
1862 if (cg_all_unified() > 0) {
1863 r = bpf_devices_cgroup_init(&prog, policy, c->device_allow);
1864 if (r < 0)
1865 return log_unit_warning_errno(u, r, "Failed to initialize device control bpf program: %m");
1866
1867 } else {
1868 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore
1869 * EINVAL here. */
1870
1871 if (c->device_allow || policy != CGROUP_DEVICE_POLICY_AUTO)
1872 r = cg_set_attribute("devices", path, "devices.deny", "a");
1873 else
1874 r = cg_set_attribute("devices", path, "devices.allow", "a");
1875 if (r < 0)
1876 log_unit_full_errno(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING, r,
1877 "Failed to reset devices.allow/devices.deny: %m");
1878 }
1879
1880 bool allow_list_static = policy == CGROUP_DEVICE_POLICY_CLOSED ||
1881 (policy == CGROUP_DEVICE_POLICY_AUTO && c->device_allow);
1882 if (allow_list_static)
1883 (void) bpf_devices_allow_list_static(prog, path);
1884
1885 bool any = allow_list_static;
1886 LIST_FOREACH(device_allow, a, c->device_allow) {
1887 const char *val;
1888
1889 if (a->permissions == 0)
1890 continue;
1891
1892 if (path_startswith(a->path, "/dev/"))
1893 r = bpf_devices_allow_list_device(prog, path, a->path, a->permissions);
1894 else if ((val = startswith(a->path, "block-")))
1895 r = bpf_devices_allow_list_major(prog, path, val, 'b', a->permissions);
1896 else if ((val = startswith(a->path, "char-")))
1897 r = bpf_devices_allow_list_major(prog, path, val, 'c', a->permissions);
1898 else {
1899 log_unit_debug(u, "Ignoring device '%s' while writing cgroup attribute.", a->path);
1900 continue;
1901 }
1902
1903 if (r >= 0)
1904 any = true;
1905 }
1906
1907 if (prog && !any) {
1908 log_unit_warning_errno(u, SYNTHETIC_ERRNO(ENODEV), "No devices matched by device filter.");
1909
1910 /* The kernel verifier would reject a program we would build with the normal intro and outro
1911 but no allow-listing rules (outro would contain an unreachable instruction for successful
1912 return). */
1913 policy = CGROUP_DEVICE_POLICY_STRICT;
1914 }
1915
1916 r = bpf_devices_apply_policy(&prog, policy, any, path, &u->bpf_device_control_installed);
1917 if (r < 0) {
1918 static bool warned = false;
1919
1920 log_full_errno(warned ? LOG_DEBUG : LOG_WARNING, r,
1921 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1922 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1923 "(This warning is only shown for the first loaded unit using device ACL.)", u->id);
1924
1925 warned = true;
1926 }
1927 return r;
1928 }
1929
1930 static void set_io_weight(Unit *u, uint64_t weight) {
1931 char buf[STRLEN("default \n")+DECIMAL_STR_MAX(uint64_t)];
1932
1933 assert(u);
1934
1935 (void) set_bfq_weight(u, "io", makedev(0, 0), weight);
1936
1937 xsprintf(buf, "default %" PRIu64 "\n", weight);
1938 (void) set_attribute_and_warn(u, "io", "io.weight", buf);
1939 }
1940
1941 static void set_blkio_weight(Unit *u, uint64_t weight) {
1942 char buf[STRLEN("\n")+DECIMAL_STR_MAX(uint64_t)];
1943
1944 assert(u);
1945
1946 (void) set_bfq_weight(u, "blkio", makedev(0, 0), weight);
1947
1948 xsprintf(buf, "%" PRIu64 "\n", weight);
1949 (void) set_attribute_and_warn(u, "blkio", "blkio.weight", buf);
1950 }
1951
1952 static void cgroup_apply_bpf_foreign_program(Unit *u) {
1953 assert(u);
1954
1955 (void) bpf_foreign_install(u);
1956 }
1957
1958 static void cgroup_context_apply(
1959 Unit *u,
1960 CGroupMask apply_mask,
1961 ManagerState state) {
1962
1963 const char *path;
1964 CGroupContext *c;
1965 bool is_host_root, is_local_root;
1966 int r;
1967
1968 assert(u);
1969
1970 /* Nothing to do? Exit early! */
1971 if (apply_mask == 0)
1972 return;
1973
1974 /* Some cgroup attributes are not supported on the host root cgroup, hence silently ignore them here. And other
1975 * attributes should only be managed for cgroups further down the tree. */
1976 is_local_root = unit_has_name(u, SPECIAL_ROOT_SLICE);
1977 is_host_root = unit_has_host_root_cgroup(u);
1978
1979 assert_se(c = unit_get_cgroup_context(u));
1980 assert_se(path = u->cgroup_path);
1981
1982 if (is_local_root) /* Make sure we don't try to display messages with an empty path. */
1983 path = "/";
1984
1985 /* We generally ignore errors caused by read-only mounted cgroup trees (assuming we are running in a container
1986 * then), and missing cgroups, i.e. EROFS and ENOENT. */
1987
1988 /* In fully unified mode these attributes don't exist on the host cgroup root. On legacy the weights exist, but
1989 * setting the weight makes very little sense on the host root cgroup, as there are no other cgroups at this
1990 * level. The quota exists there too, but any attempt to write to it is refused with EINVAL. Inside of
1991 * containers we want to leave control of these to the container manager (and if cgroup v2 delegation is used
1992 * we couldn't even write to them if we wanted to). */
1993 if ((apply_mask & CGROUP_MASK_CPU) && !is_local_root) {
1994
1995 if (cg_all_unified() > 0) {
1996 uint64_t weight;
1997
1998 if (cgroup_context_has_cpu_weight(c))
1999 weight = cgroup_context_cpu_weight(c, state);
2000 else if (cgroup_context_has_cpu_shares(c)) {
2001 uint64_t shares;
2002
2003 shares = cgroup_context_cpu_shares(c, state);
2004 weight = cgroup_cpu_shares_to_weight(shares);
2005
2006 log_cgroup_compat(u, "Applying [Startup]CPUShares=%" PRIu64 " as [Startup]CPUWeight=%" PRIu64 " on %s",
2007 shares, weight, path);
2008 } else
2009 weight = CGROUP_WEIGHT_DEFAULT;
2010
2011 cgroup_apply_unified_cpu_idle(u, weight);
2012 cgroup_apply_unified_cpu_weight(u, weight);
2013 cgroup_apply_unified_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
2014
2015 } else {
2016 uint64_t shares;
2017
2018 if (cgroup_context_has_cpu_weight(c)) {
2019 uint64_t weight;
2020
2021 weight = cgroup_context_cpu_weight(c, state);
2022 shares = cgroup_cpu_weight_to_shares(weight);
2023
2024 log_cgroup_compat(u, "Applying [Startup]CPUWeight=%" PRIu64 " as [Startup]CPUShares=%" PRIu64 " on %s",
2025 weight, shares, path);
2026 } else if (cgroup_context_has_cpu_shares(c))
2027 shares = cgroup_context_cpu_shares(c, state);
2028 else
2029 shares = CGROUP_CPU_SHARES_DEFAULT;
2030
2031 cgroup_apply_legacy_cpu_shares(u, shares);
2032 cgroup_apply_legacy_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
2033 }
2034 }
2035
2036 if ((apply_mask & CGROUP_MASK_CPUSET) && !is_local_root) {
2037 cgroup_apply_unified_cpuset(u, cgroup_context_allowed_cpus(c, state), "cpuset.cpus");
2038 cgroup_apply_unified_cpuset(u, cgroup_context_allowed_mems(c, state), "cpuset.mems");
2039 }
2040
2041 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroup v2
2042 * controller), and in case of containers we want to leave control of these attributes to the container manager
2043 * (and we couldn't access that stuff anyway, even if we tried if proper delegation is used). */
2044 if ((apply_mask & CGROUP_MASK_IO) && !is_local_root) {
2045 bool has_io, has_blockio;
2046 uint64_t weight;
2047
2048 has_io = cgroup_context_has_io_config(c);
2049 has_blockio = cgroup_context_has_blockio_config(c);
2050
2051 if (has_io)
2052 weight = cgroup_context_io_weight(c, state);
2053 else if (has_blockio) {
2054 uint64_t blkio_weight;
2055
2056 blkio_weight = cgroup_context_blkio_weight(c, state);
2057 weight = cgroup_weight_blkio_to_io(blkio_weight);
2058
2059 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight=%" PRIu64 " as [Startup]IOWeight=%" PRIu64,
2060 blkio_weight, weight);
2061 } else
2062 weight = CGROUP_WEIGHT_DEFAULT;
2063
2064 set_io_weight(u, weight);
2065
2066 if (has_io) {
2067 LIST_FOREACH(device_weights, w, c->io_device_weights)
2068 cgroup_apply_io_device_weight(u, w->path, w->weight);
2069
2070 LIST_FOREACH(device_limits, limit, c->io_device_limits)
2071 cgroup_apply_io_device_limit(u, limit->path, limit->limits);
2072
2073 LIST_FOREACH(device_latencies, latency, c->io_device_latencies)
2074 cgroup_apply_io_device_latency(u, latency->path, latency->target_usec);
2075
2076 } else if (has_blockio) {
2077 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
2078 weight = cgroup_weight_blkio_to_io(w->weight);
2079
2080 log_cgroup_compat(u, "Applying BlockIODeviceWeight=%" PRIu64 " as IODeviceWeight=%" PRIu64 " for %s",
2081 w->weight, weight, w->path);
2082
2083 cgroup_apply_io_device_weight(u, w->path, weight);
2084 }
2085
2086 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
2087 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
2088
2089 for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
2090 limits[type] = cgroup_io_limit_defaults[type];
2091
2092 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
2093 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
2094
2095 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax= for %s",
2096 b->rbps, b->wbps, b->path);
2097
2098 cgroup_apply_io_device_limit(u, b->path, limits);
2099 }
2100 }
2101 }
2102
2103 if (apply_mask & CGROUP_MASK_BLKIO) {
2104 bool has_io, has_blockio;
2105
2106 has_io = cgroup_context_has_io_config(c);
2107 has_blockio = cgroup_context_has_blockio_config(c);
2108
2109 /* Applying a 'weight' never makes sense for the host root cgroup, and for containers this should be
2110 * left to our container manager, too. */
2111 if (!is_local_root) {
2112 uint64_t weight;
2113
2114 if (has_io) {
2115 uint64_t io_weight;
2116
2117 io_weight = cgroup_context_io_weight(c, state);
2118 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
2119
2120 log_cgroup_compat(u, "Applying [Startup]IOWeight=%" PRIu64 " as [Startup]BlockIOWeight=%" PRIu64,
2121 io_weight, weight);
2122 } else if (has_blockio)
2123 weight = cgroup_context_blkio_weight(c, state);
2124 else
2125 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
2126
2127 set_blkio_weight(u, weight);
2128
2129 if (has_io)
2130 LIST_FOREACH(device_weights, w, c->io_device_weights) {
2131 weight = cgroup_weight_io_to_blkio(w->weight);
2132
2133 log_cgroup_compat(u, "Applying IODeviceWeight=%" PRIu64 " as BlockIODeviceWeight=%" PRIu64 " for %s",
2134 w->weight, weight, w->path);
2135
2136 cgroup_apply_blkio_device_weight(u, w->path, weight);
2137 }
2138 else if (has_blockio)
2139 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
2140 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
2141 }
2142
2143 /* The bandwidth limits are something that make sense to be applied to the host's root but not container
2144 * roots, as there we want the container manager to handle it */
2145 if (is_host_root || !is_local_root) {
2146 if (has_io)
2147 LIST_FOREACH(device_limits, l, c->io_device_limits) {
2148 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax= for %s",
2149 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
2150
2151 cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]);
2152 }
2153 else if (has_blockio)
2154 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
2155 cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps);
2156 }
2157 }
2158
2159 /* In unified mode 'memory' attributes do not exist on the root cgroup. In legacy mode 'memory.limit_in_bytes'
2160 * exists on the root cgroup, but any writes to it are refused with EINVAL. And if we run in a container we
2161 * want to leave control to the container manager (and if proper cgroup v2 delegation is used we couldn't even
2162 * write to this if we wanted to.) */
2163 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_local_root) {
2164
2165 if (cg_all_unified() > 0) {
2166 uint64_t max, swap_max = CGROUP_LIMIT_MAX, zswap_max = CGROUP_LIMIT_MAX, high = CGROUP_LIMIT_MAX;
2167
2168 if (unit_has_unified_memory_config(u)) {
2169 bool startup = IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING, MANAGER_STOPPING);
2170
2171 high = startup && c->startup_memory_high_set ? c->startup_memory_high : c->memory_high;
2172 max = startup && c->startup_memory_max_set ? c->startup_memory_max : c->memory_max;
2173 swap_max = startup && c->startup_memory_swap_max_set ? c->startup_memory_swap_max : c->memory_swap_max;
2174 zswap_max = startup && c->startup_memory_zswap_max_set ? c->startup_memory_zswap_max : c->memory_zswap_max;
2175 } else {
2176 max = c->memory_limit;
2177
2178 if (max != CGROUP_LIMIT_MAX)
2179 log_cgroup_compat(u, "Applying MemoryLimit=%" PRIu64 " as MemoryMax=", max);
2180 }
2181
2182 cgroup_apply_unified_memory_limit(u, "memory.min", unit_get_ancestor_memory_min(u));
2183 cgroup_apply_unified_memory_limit(u, "memory.low", unit_get_ancestor_memory_low(u));
2184 cgroup_apply_unified_memory_limit(u, "memory.high", high);
2185 cgroup_apply_unified_memory_limit(u, "memory.max", max);
2186 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
2187 cgroup_apply_unified_memory_limit(u, "memory.zswap.max", zswap_max);
2188
2189 (void) set_attribute_and_warn(u, "memory", "memory.oom.group", one_zero(c->memory_oom_group));
2190
2191 } else {
2192 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
2193 uint64_t val;
2194
2195 if (unit_has_unified_memory_config(u)) {
2196 val = c->memory_max;
2197 if (val != CGROUP_LIMIT_MAX)
2198 log_cgroup_compat(u, "Applying MemoryMax=%" PRIu64 " as MemoryLimit=", val);
2199 } else
2200 val = c->memory_limit;
2201
2202 if (val == CGROUP_LIMIT_MAX)
2203 strncpy(buf, "-1\n", sizeof(buf));
2204 else
2205 xsprintf(buf, "%" PRIu64 "\n", val);
2206
2207 (void) set_attribute_and_warn(u, "memory", "memory.limit_in_bytes", buf);
2208 }
2209 }
2210
2211 /* On cgroup v2 we can apply BPF everywhere. On cgroup v1 we apply it everywhere except for the root of
2212 * containers, where we leave this to the manager */
2213 if ((apply_mask & (CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES)) &&
2214 (is_host_root || cg_all_unified() > 0 || !is_local_root))
2215 (void) cgroup_apply_devices(u);
2216
2217 if (apply_mask & CGROUP_MASK_PIDS) {
2218
2219 if (is_host_root) {
2220 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
2221 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
2222 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
2223 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
2224 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
2225 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
2226 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
2227 * it also counts. But if the user never set a limit through us (i.e. we are the default of
2228 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
2229 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
2230 * which is desirable so that there's an official way to release control of the sysctl from
2231 * systemd: set the limit to unbounded and reload. */
2232
2233 if (cgroup_tasks_max_isset(&c->tasks_max)) {
2234 u->manager->sysctl_pid_max_changed = true;
2235 r = procfs_tasks_set_limit(cgroup_tasks_max_resolve(&c->tasks_max));
2236 } else if (u->manager->sysctl_pid_max_changed)
2237 r = procfs_tasks_set_limit(TASKS_MAX);
2238 else
2239 r = 0;
2240 if (r < 0)
2241 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r,
2242 "Failed to write to tasks limit sysctls: %m");
2243 }
2244
2245 /* The attribute itself is not available on the host root cgroup, and in the container case we want to
2246 * leave it for the container manager. */
2247 if (!is_local_root) {
2248 if (cgroup_tasks_max_isset(&c->tasks_max)) {
2249 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
2250
2251 xsprintf(buf, "%" PRIu64 "\n", cgroup_tasks_max_resolve(&c->tasks_max));
2252 (void) set_attribute_and_warn(u, "pids", "pids.max", buf);
2253 } else
2254 (void) set_attribute_and_warn(u, "pids", "pids.max", "max\n");
2255 }
2256 }
2257
2258 if (apply_mask & CGROUP_MASK_BPF_FIREWALL)
2259 cgroup_apply_firewall(u);
2260
2261 if (apply_mask & CGROUP_MASK_BPF_FOREIGN)
2262 cgroup_apply_bpf_foreign_program(u);
2263
2264 if (apply_mask & CGROUP_MASK_BPF_SOCKET_BIND)
2265 cgroup_apply_socket_bind(u);
2266
2267 if (apply_mask & CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES)
2268 cgroup_apply_restrict_network_interfaces(u);
2269
2270 unit_modify_nft_set(u, /* add = */ true);
2271 }
2272
2273 static bool unit_get_needs_bpf_firewall(Unit *u) {
2274 CGroupContext *c;
2275 assert(u);
2276
2277 c = unit_get_cgroup_context(u);
2278 if (!c)
2279 return false;
2280
2281 if (c->ip_accounting ||
2282 !set_isempty(c->ip_address_allow) ||
2283 !set_isempty(c->ip_address_deny) ||
2284 c->ip_filters_ingress ||
2285 c->ip_filters_egress)
2286 return true;
2287
2288 /* If any parent slice has an IP access list defined, it applies too */
2289 for (Unit *p = UNIT_GET_SLICE(u); p; p = UNIT_GET_SLICE(p)) {
2290 c = unit_get_cgroup_context(p);
2291 if (!c)
2292 return false;
2293
2294 if (!set_isempty(c->ip_address_allow) ||
2295 !set_isempty(c->ip_address_deny))
2296 return true;
2297 }
2298
2299 return false;
2300 }
2301
2302 static bool unit_get_needs_bpf_foreign_program(Unit *u) {
2303 CGroupContext *c;
2304 assert(u);
2305
2306 c = unit_get_cgroup_context(u);
2307 if (!c)
2308 return false;
2309
2310 return !!c->bpf_foreign_programs;
2311 }
2312
2313 static bool unit_get_needs_socket_bind(Unit *u) {
2314 CGroupContext *c;
2315 assert(u);
2316
2317 c = unit_get_cgroup_context(u);
2318 if (!c)
2319 return false;
2320
2321 return c->socket_bind_allow || c->socket_bind_deny;
2322 }
2323
2324 static bool unit_get_needs_restrict_network_interfaces(Unit *u) {
2325 CGroupContext *c;
2326 assert(u);
2327
2328 c = unit_get_cgroup_context(u);
2329 if (!c)
2330 return false;
2331
2332 return !set_isempty(c->restrict_network_interfaces);
2333 }
2334
2335 static CGroupMask unit_get_cgroup_mask(Unit *u) {
2336 CGroupMask mask = 0;
2337 CGroupContext *c;
2338
2339 assert(u);
2340
2341 assert_se(c = unit_get_cgroup_context(u));
2342
2343 /* Figure out which controllers we need, based on the cgroup context object */
2344
2345 if (c->cpu_accounting)
2346 mask |= get_cpu_accounting_mask();
2347
2348 if (cgroup_context_has_cpu_weight(c) ||
2349 cgroup_context_has_cpu_shares(c) ||
2350 c->cpu_quota_per_sec_usec != USEC_INFINITY)
2351 mask |= CGROUP_MASK_CPU;
2352
2353 if (cgroup_context_has_allowed_cpus(c) || cgroup_context_has_allowed_mems(c))
2354 mask |= CGROUP_MASK_CPUSET;
2355
2356 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
2357 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
2358
2359 if (c->memory_accounting ||
2360 c->memory_limit != CGROUP_LIMIT_MAX ||
2361 unit_has_unified_memory_config(u))
2362 mask |= CGROUP_MASK_MEMORY;
2363
2364 if (c->device_allow ||
2365 c->device_policy != CGROUP_DEVICE_POLICY_AUTO)
2366 mask |= CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES;
2367
2368 if (c->tasks_accounting ||
2369 cgroup_tasks_max_isset(&c->tasks_max))
2370 mask |= CGROUP_MASK_PIDS;
2371
2372 return CGROUP_MASK_EXTEND_JOINED(mask);
2373 }
2374
2375 static CGroupMask unit_get_bpf_mask(Unit *u) {
2376 CGroupMask mask = 0;
2377
2378 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
2379 * too. */
2380
2381 if (unit_get_needs_bpf_firewall(u))
2382 mask |= CGROUP_MASK_BPF_FIREWALL;
2383
2384 if (unit_get_needs_bpf_foreign_program(u))
2385 mask |= CGROUP_MASK_BPF_FOREIGN;
2386
2387 if (unit_get_needs_socket_bind(u))
2388 mask |= CGROUP_MASK_BPF_SOCKET_BIND;
2389
2390 if (unit_get_needs_restrict_network_interfaces(u))
2391 mask |= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES;
2392
2393 return mask;
2394 }
2395
2396 CGroupMask unit_get_own_mask(Unit *u) {
2397 CGroupContext *c;
2398
2399 /* Returns the mask of controllers the unit needs for itself. If a unit is not properly loaded, return an empty
2400 * mask, as we shouldn't reflect it in the cgroup hierarchy then. */
2401
2402 if (u->load_state != UNIT_LOADED)
2403 return 0;
2404
2405 c = unit_get_cgroup_context(u);
2406 if (!c)
2407 return 0;
2408
2409 return unit_get_cgroup_mask(u) | unit_get_bpf_mask(u) | unit_get_delegate_mask(u);
2410 }
2411
2412 CGroupMask unit_get_delegate_mask(Unit *u) {
2413 CGroupContext *c;
2414
2415 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
2416 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
2417 *
2418 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
2419
2420 if (!unit_cgroup_delegate(u))
2421 return 0;
2422
2423 if (cg_all_unified() <= 0) {
2424 ExecContext *e;
2425
2426 e = unit_get_exec_context(u);
2427 if (e && !exec_context_maintains_privileges(e))
2428 return 0;
2429 }
2430
2431 assert_se(c = unit_get_cgroup_context(u));
2432 return CGROUP_MASK_EXTEND_JOINED(c->delegate_controllers);
2433 }
2434
2435 static CGroupMask unit_get_subtree_mask(Unit *u) {
2436
2437 /* Returns the mask of this subtree, meaning of the group
2438 * itself and its children. */
2439
2440 return unit_get_own_mask(u) | unit_get_members_mask(u);
2441 }
2442
2443 CGroupMask unit_get_members_mask(Unit *u) {
2444 assert(u);
2445
2446 /* Returns the mask of controllers all of the unit's children require, merged */
2447
2448 if (u->cgroup_members_mask_valid)
2449 return u->cgroup_members_mask; /* Use cached value if possible */
2450
2451 u->cgroup_members_mask = 0;
2452
2453 if (u->type == UNIT_SLICE) {
2454 Unit *member;
2455
2456 UNIT_FOREACH_DEPENDENCY(member, u, UNIT_ATOM_SLICE_OF)
2457 u->cgroup_members_mask |= unit_get_subtree_mask(member); /* note that this calls ourselves again, for the children */
2458 }
2459
2460 u->cgroup_members_mask_valid = true;
2461 return u->cgroup_members_mask;
2462 }
2463
2464 CGroupMask unit_get_siblings_mask(Unit *u) {
2465 Unit *slice;
2466 assert(u);
2467
2468 /* Returns the mask of controllers all of the unit's siblings
2469 * require, i.e. the members mask of the unit's parent slice
2470 * if there is one. */
2471
2472 slice = UNIT_GET_SLICE(u);
2473 if (slice)
2474 return unit_get_members_mask(slice);
2475
2476 return unit_get_subtree_mask(u); /* we are the top-level slice */
2477 }
2478
2479 static CGroupMask unit_get_disable_mask(Unit *u) {
2480 CGroupContext *c;
2481
2482 c = unit_get_cgroup_context(u);
2483 if (!c)
2484 return 0;
2485
2486 return c->disable_controllers;
2487 }
2488
2489 CGroupMask unit_get_ancestor_disable_mask(Unit *u) {
2490 CGroupMask mask;
2491 Unit *slice;
2492
2493 assert(u);
2494 mask = unit_get_disable_mask(u);
2495
2496 /* Returns the mask of controllers which are marked as forcibly
2497 * disabled in any ancestor unit or the unit in question. */
2498
2499 slice = UNIT_GET_SLICE(u);
2500 if (slice)
2501 mask |= unit_get_ancestor_disable_mask(slice);
2502
2503 return mask;
2504 }
2505
2506 CGroupMask unit_get_target_mask(Unit *u) {
2507 CGroupMask own_mask, mask;
2508
2509 /* This returns the cgroup mask of all controllers to enable for a specific cgroup, i.e. everything
2510 * it needs itself, plus all that its children need, plus all that its siblings need. This is
2511 * primarily useful on the legacy cgroup hierarchy, where we need to duplicate each cgroup in each
2512 * hierarchy that shall be enabled for it. */
2513
2514 own_mask = unit_get_own_mask(u);
2515
2516 if (own_mask & CGROUP_MASK_BPF_FIREWALL & ~u->manager->cgroup_supported)
2517 emit_bpf_firewall_warning(u);
2518
2519 mask = own_mask | unit_get_members_mask(u) | unit_get_siblings_mask(u);
2520
2521 mask &= u->manager->cgroup_supported;
2522 mask &= ~unit_get_ancestor_disable_mask(u);
2523
2524 return mask;
2525 }
2526
2527 CGroupMask unit_get_enable_mask(Unit *u) {
2528 CGroupMask mask;
2529
2530 /* This returns the cgroup mask of all controllers to enable
2531 * for the children of a specific cgroup. This is primarily
2532 * useful for the unified cgroup hierarchy, where each cgroup
2533 * controls which controllers are enabled for its children. */
2534
2535 mask = unit_get_members_mask(u);
2536 mask &= u->manager->cgroup_supported;
2537 mask &= ~unit_get_ancestor_disable_mask(u);
2538
2539 return mask;
2540 }
2541
2542 void unit_invalidate_cgroup_members_masks(Unit *u) {
2543 Unit *slice;
2544
2545 assert(u);
2546
2547 /* Recurse invalidate the member masks cache all the way up the tree */
2548 u->cgroup_members_mask_valid = false;
2549
2550 slice = UNIT_GET_SLICE(u);
2551 if (slice)
2552 unit_invalidate_cgroup_members_masks(slice);
2553 }
2554
2555 const char *unit_get_realized_cgroup_path(Unit *u, CGroupMask mask) {
2556
2557 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
2558
2559 while (u) {
2560
2561 if (u->cgroup_path &&
2562 u->cgroup_realized &&
2563 FLAGS_SET(u->cgroup_realized_mask, mask))
2564 return u->cgroup_path;
2565
2566 u = UNIT_GET_SLICE(u);
2567 }
2568
2569 return NULL;
2570 }
2571
2572 static const char *migrate_callback(CGroupMask mask, void *userdata) {
2573 /* If not realized at all, migrate to root ("").
2574 * It may happen if we're upgrading from older version that didn't clean up.
2575 */
2576 return strempty(unit_get_realized_cgroup_path(userdata, mask));
2577 }
2578
2579 int unit_default_cgroup_path(const Unit *u, char **ret) {
2580 _cleanup_free_ char *p = NULL;
2581 int r;
2582
2583 assert(u);
2584 assert(ret);
2585
2586 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
2587 p = strdup(u->manager->cgroup_root);
2588 else {
2589 _cleanup_free_ char *escaped = NULL, *slice_path = NULL;
2590 Unit *slice;
2591
2592 slice = UNIT_GET_SLICE(u);
2593 if (slice && !unit_has_name(slice, SPECIAL_ROOT_SLICE)) {
2594 r = cg_slice_to_path(slice->id, &slice_path);
2595 if (r < 0)
2596 return r;
2597 }
2598
2599 r = cg_escape(u->id, &escaped);
2600 if (r < 0)
2601 return r;
2602
2603 p = path_join(empty_to_root(u->manager->cgroup_root), slice_path, escaped);
2604 }
2605 if (!p)
2606 return -ENOMEM;
2607
2608 *ret = TAKE_PTR(p);
2609 return 0;
2610 }
2611
2612 int unit_set_cgroup_path(Unit *u, const char *path) {
2613 _cleanup_free_ char *p = NULL;
2614 int r;
2615
2616 assert(u);
2617
2618 if (streq_ptr(u->cgroup_path, path))
2619 return 0;
2620
2621 if (path) {
2622 p = strdup(path);
2623 if (!p)
2624 return -ENOMEM;
2625 }
2626
2627 if (p) {
2628 r = hashmap_put(u->manager->cgroup_unit, p, u);
2629 if (r < 0)
2630 return r;
2631 }
2632
2633 unit_release_cgroup(u);
2634 u->cgroup_path = TAKE_PTR(p);
2635
2636 return 1;
2637 }
2638
2639 int unit_watch_cgroup(Unit *u) {
2640 _cleanup_free_ char *events = NULL;
2641 int r;
2642
2643 assert(u);
2644
2645 /* Watches the "cgroups.events" attribute of this unit's cgroup for "empty" events, but only if
2646 * cgroupv2 is available. */
2647
2648 if (!u->cgroup_path)
2649 return 0;
2650
2651 if (u->cgroup_control_inotify_wd >= 0)
2652 return 0;
2653
2654 /* Only applies to the unified hierarchy */
2655 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2656 if (r < 0)
2657 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
2658 if (r == 0)
2659 return 0;
2660
2661 /* No point in watch the top-level slice, it's never going to run empty. */
2662 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
2663 return 0;
2664
2665 r = hashmap_ensure_allocated(&u->manager->cgroup_control_inotify_wd_unit, &trivial_hash_ops);
2666 if (r < 0)
2667 return log_oom();
2668
2669 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
2670 if (r < 0)
2671 return log_oom();
2672
2673 u->cgroup_control_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
2674 if (u->cgroup_control_inotify_wd < 0) {
2675
2676 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
2677 * is not an error */
2678 return 0;
2679
2680 return log_unit_error_errno(u, errno, "Failed to add control inotify watch descriptor for control group %s: %m", empty_to_root(u->cgroup_path));
2681 }
2682
2683 r = hashmap_put(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd), u);
2684 if (r < 0)
2685 return log_unit_error_errno(u, r, "Failed to add control inotify watch descriptor for control group %s to hash map: %m", empty_to_root(u->cgroup_path));
2686
2687 return 0;
2688 }
2689
2690 int unit_watch_cgroup_memory(Unit *u) {
2691 _cleanup_free_ char *events = NULL;
2692 CGroupContext *c;
2693 int r;
2694
2695 assert(u);
2696
2697 /* Watches the "memory.events" attribute of this unit's cgroup for "oom_kill" events, but only if
2698 * cgroupv2 is available. */
2699
2700 if (!u->cgroup_path)
2701 return 0;
2702
2703 c = unit_get_cgroup_context(u);
2704 if (!c)
2705 return 0;
2706
2707 /* The "memory.events" attribute is only available if the memory controller is on. Let's hence tie
2708 * this to memory accounting, in a way watching for OOM kills is a form of memory accounting after
2709 * all. */
2710 if (!c->memory_accounting)
2711 return 0;
2712
2713 /* Don't watch inner nodes, as the kernel doesn't report oom_kill events recursively currently, and
2714 * we also don't want to generate a log message for each parent cgroup of a process. */
2715 if (u->type == UNIT_SLICE)
2716 return 0;
2717
2718 if (u->cgroup_memory_inotify_wd >= 0)
2719 return 0;
2720
2721 /* Only applies to the unified hierarchy */
2722 r = cg_all_unified();
2723 if (r < 0)
2724 return log_error_errno(r, "Failed to determine whether the memory controller is unified: %m");
2725 if (r == 0)
2726 return 0;
2727
2728 r = hashmap_ensure_allocated(&u->manager->cgroup_memory_inotify_wd_unit, &trivial_hash_ops);
2729 if (r < 0)
2730 return log_oom();
2731
2732 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "memory.events", &events);
2733 if (r < 0)
2734 return log_oom();
2735
2736 u->cgroup_memory_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
2737 if (u->cgroup_memory_inotify_wd < 0) {
2738
2739 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
2740 * is not an error */
2741 return 0;
2742
2743 return log_unit_error_errno(u, errno, "Failed to add memory inotify watch descriptor for control group %s: %m", empty_to_root(u->cgroup_path));
2744 }
2745
2746 r = hashmap_put(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd), u);
2747 if (r < 0)
2748 return log_unit_error_errno(u, r, "Failed to add memory inotify watch descriptor for control group %s to hash map: %m", empty_to_root(u->cgroup_path));
2749
2750 return 0;
2751 }
2752
2753 int unit_pick_cgroup_path(Unit *u) {
2754 _cleanup_free_ char *path = NULL;
2755 int r;
2756
2757 assert(u);
2758
2759 if (u->cgroup_path)
2760 return 0;
2761
2762 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2763 return -EINVAL;
2764
2765 r = unit_default_cgroup_path(u, &path);
2766 if (r < 0)
2767 return log_unit_error_errno(u, r, "Failed to generate default cgroup path: %m");
2768
2769 r = unit_set_cgroup_path(u, path);
2770 if (r == -EEXIST)
2771 return log_unit_error_errno(u, r, "Control group %s exists already.", empty_to_root(path));
2772 if (r < 0)
2773 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", empty_to_root(path));
2774
2775 return 0;
2776 }
2777
2778 static int unit_update_cgroup(
2779 Unit *u,
2780 CGroupMask target_mask,
2781 CGroupMask enable_mask,
2782 ManagerState state) {
2783
2784 bool created, is_root_slice;
2785 CGroupMask migrate_mask = 0;
2786 _cleanup_free_ char *cgroup_full_path = NULL;
2787 int r;
2788
2789 assert(u);
2790
2791 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2792 return 0;
2793
2794 /* Figure out our cgroup path */
2795 r = unit_pick_cgroup_path(u);
2796 if (r < 0)
2797 return r;
2798
2799 /* First, create our own group */
2800 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
2801 if (r < 0)
2802 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", empty_to_root(u->cgroup_path));
2803 created = r;
2804
2805 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
2806 uint64_t cgroup_id = 0;
2807
2808 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, NULL, &cgroup_full_path);
2809 if (r == 0) {
2810 r = cg_path_get_cgroupid(cgroup_full_path, &cgroup_id);
2811 if (r < 0)
2812 log_unit_full_errno(u, ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
2813 "Failed to get cgroup ID of cgroup %s, ignoring: %m", cgroup_full_path);
2814 } else
2815 log_unit_warning_errno(u, r, "Failed to get full cgroup path on cgroup %s, ignoring: %m", empty_to_root(u->cgroup_path));
2816
2817 u->cgroup_id = cgroup_id;
2818 }
2819
2820 /* Start watching it */
2821 (void) unit_watch_cgroup(u);
2822 (void) unit_watch_cgroup_memory(u);
2823
2824 /* For v2 we preserve enabled controllers in delegated units, adjust others,
2825 * for v1 we figure out which controller hierarchies need migration. */
2826 if (created || !u->cgroup_realized || !unit_cgroup_delegate(u)) {
2827 CGroupMask result_mask = 0;
2828
2829 /* Enable all controllers we need */
2830 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path, &result_mask);
2831 if (r < 0)
2832 log_unit_warning_errno(u, r, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", empty_to_root(u->cgroup_path));
2833
2834 /* Remember what's actually enabled now */
2835 u->cgroup_enabled_mask = result_mask;
2836
2837 migrate_mask = u->cgroup_realized_mask ^ target_mask;
2838 }
2839
2840 /* Keep track that this is now realized */
2841 u->cgroup_realized = true;
2842 u->cgroup_realized_mask = target_mask;
2843
2844 /* Migrate processes in controller hierarchies both downwards (enabling) and upwards (disabling).
2845 *
2846 * Unnecessary controller cgroups are trimmed (after emptied by upward migration).
2847 * We perform migration also with whole slices for cases when users don't care about leave
2848 * granularity. Since delegated_mask is subset of target mask, we won't trim slice subtree containing
2849 * delegated units.
2850 */
2851 if (cg_all_unified() == 0) {
2852 r = cg_migrate_v1_controllers(u->manager->cgroup_supported, migrate_mask, u->cgroup_path, migrate_callback, u);
2853 if (r < 0)
2854 log_unit_warning_errno(u, r, "Failed to migrate controller cgroups from %s, ignoring: %m", empty_to_root(u->cgroup_path));
2855
2856 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
2857 r = cg_trim_v1_controllers(u->manager->cgroup_supported, ~target_mask, u->cgroup_path, !is_root_slice);
2858 if (r < 0)
2859 log_unit_warning_errno(u, r, "Failed to delete controller cgroups %s, ignoring: %m", empty_to_root(u->cgroup_path));
2860 }
2861
2862 /* Set attributes */
2863 cgroup_context_apply(u, target_mask, state);
2864 cgroup_xattr_apply(u);
2865
2866 /* For most units we expect that memory monitoring is set up before the unit is started and we won't
2867 * touch it after. For PID 1 this is different though, because we couldn't possibly do that given
2868 * that PID 1 runs before init.scope is even set up. Hence, whenever init.scope is realized, let's
2869 * try to open the memory pressure interface anew. */
2870 if (unit_has_name(u, SPECIAL_INIT_SCOPE))
2871 (void) manager_setup_memory_pressure_event_source(u->manager);
2872
2873 return 0;
2874 }
2875
2876 static int unit_attach_pid_to_cgroup_via_bus(Unit *u, pid_t pid, const char *suffix_path) {
2877 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2878 char *pp;
2879 int r;
2880
2881 assert(u);
2882
2883 if (MANAGER_IS_SYSTEM(u->manager))
2884 return -EINVAL;
2885
2886 if (!u->manager->system_bus)
2887 return -EIO;
2888
2889 if (!u->cgroup_path)
2890 return -EINVAL;
2891
2892 /* Determine this unit's cgroup path relative to our cgroup root */
2893 pp = path_startswith(u->cgroup_path, u->manager->cgroup_root);
2894 if (!pp)
2895 return -EINVAL;
2896
2897 pp = strjoina("/", pp, suffix_path);
2898 path_simplify(pp);
2899
2900 r = bus_call_method(u->manager->system_bus,
2901 bus_systemd_mgr,
2902 "AttachProcessesToUnit",
2903 &error, NULL,
2904 "ssau",
2905 NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
2906 if (r < 0)
2907 return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
2908
2909 return 0;
2910 }
2911
2912 int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
2913 _cleanup_free_ char *joined = NULL;
2914 CGroupMask delegated_mask;
2915 const char *p;
2916 PidRef *pid;
2917 int ret, r;
2918
2919 assert(u);
2920
2921 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2922 return -EINVAL;
2923
2924 if (set_isempty(pids))
2925 return 0;
2926
2927 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
2928 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
2929 r = bpf_firewall_load_custom(u);
2930 if (r < 0)
2931 return r;
2932
2933 r = unit_realize_cgroup(u);
2934 if (r < 0)
2935 return r;
2936
2937 if (isempty(suffix_path))
2938 p = u->cgroup_path;
2939 else {
2940 joined = path_join(u->cgroup_path, suffix_path);
2941 if (!joined)
2942 return -ENOMEM;
2943
2944 p = joined;
2945 }
2946
2947 delegated_mask = unit_get_delegate_mask(u);
2948
2949 ret = 0;
2950 SET_FOREACH(pid, pids) {
2951
2952 /* Unfortunately we cannot add pids by pidfd to a cgroup. Hence we have to use PIDs instead,
2953 * which of course is racy. Let's shorten the race a bit though, and re-validate the PID
2954 * before we use it */
2955 r = pidref_verify(pid);
2956 if (r < 0) {
2957 log_unit_info_errno(u, r, "PID " PID_FMT " vanished before we could move it to target cgroup '%s', skipping: %m", pid->pid, empty_to_root(p));
2958 continue;
2959 }
2960
2961 /* First, attach the PID to the main cgroup hierarchy */
2962 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, p, pid->pid);
2963 if (r < 0) {
2964 bool again = MANAGER_IS_USER(u->manager) && ERRNO_IS_PRIVILEGE(r);
2965
2966 log_unit_full_errno(u, again ? LOG_DEBUG : LOG_INFO, r,
2967 "Couldn't move process "PID_FMT" to%s requested cgroup '%s': %m",
2968 pid->pid, again ? " directly" : "", empty_to_root(p));
2969
2970 if (again) {
2971 int z;
2972
2973 /* If we are in a user instance, and we can't move the process ourselves due
2974 * to permission problems, let's ask the system instance about it instead.
2975 * Since it's more privileged it might be able to move the process across the
2976 * leaves of a subtree whose top node is not owned by us. */
2977
2978 z = unit_attach_pid_to_cgroup_via_bus(u, pid->pid, suffix_path);
2979 if (z < 0)
2980 log_unit_info_errno(u, z, "Couldn't move process "PID_FMT" to requested cgroup '%s' (directly or via the system bus): %m", pid->pid, empty_to_root(p));
2981 else {
2982 if (ret >= 0)
2983 ret++; /* Count successful additions */
2984 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
2985 }
2986 }
2987
2988 if (ret >= 0)
2989 ret = r; /* Remember first error */
2990
2991 continue;
2992 } else if (ret >= 0)
2993 ret++; /* Count successful additions */
2994
2995 r = cg_all_unified();
2996 if (r < 0)
2997 return r;
2998 if (r > 0)
2999 continue;
3000
3001 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
3002 * innermost realized one */
3003
3004 for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
3005 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
3006 const char *realized;
3007
3008 if (!(u->manager->cgroup_supported & bit))
3009 continue;
3010
3011 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
3012 if (delegated_mask & u->cgroup_realized_mask & bit) {
3013 r = cg_attach(cgroup_controller_to_string(c), p, pid->pid);
3014 if (r >= 0)
3015 continue; /* Success! */
3016
3017 log_unit_debug_errno(u, r, "Failed to attach PID " PID_FMT " to requested cgroup %s in controller %s, falling back to unit's cgroup: %m",
3018 pid->pid, empty_to_root(p), cgroup_controller_to_string(c));
3019 }
3020
3021 /* So this controller is either not delegate or realized, or something else weird happened. In
3022 * that case let's attach the PID at least to the closest cgroup up the tree that is
3023 * realized. */
3024 realized = unit_get_realized_cgroup_path(u, bit);
3025 if (!realized)
3026 continue; /* Not even realized in the root slice? Then let's not bother */
3027
3028 r = cg_attach(cgroup_controller_to_string(c), realized, pid->pid);
3029 if (r < 0)
3030 log_unit_debug_errno(u, r, "Failed to attach PID " PID_FMT " to realized cgroup %s in controller %s, ignoring: %m",
3031 pid->pid, realized, cgroup_controller_to_string(c));
3032 }
3033 }
3034
3035 return ret;
3036 }
3037
3038 static bool unit_has_mask_realized(
3039 Unit *u,
3040 CGroupMask target_mask,
3041 CGroupMask enable_mask) {
3042
3043 assert(u);
3044
3045 /* Returns true if this unit is fully realized. We check four things:
3046 *
3047 * 1. Whether the cgroup was created at all
3048 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
3049 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
3050 * 4. Whether the invalidation mask is currently zero
3051 *
3052 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
3053 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
3054 * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
3055 * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
3056 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
3057 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
3058 * simply don't matter. */
3059
3060 return u->cgroup_realized &&
3061 ((u->cgroup_realized_mask ^ target_mask) & CGROUP_MASK_V1) == 0 &&
3062 ((u->cgroup_enabled_mask ^ enable_mask) & CGROUP_MASK_V2) == 0 &&
3063 u->cgroup_invalidated_mask == 0;
3064 }
3065
3066 static bool unit_has_mask_disables_realized(
3067 Unit *u,
3068 CGroupMask target_mask,
3069 CGroupMask enable_mask) {
3070
3071 assert(u);
3072
3073 /* Returns true if all controllers which should be disabled are indeed disabled.
3074 *
3075 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
3076 * already removed. */
3077
3078 return !u->cgroup_realized ||
3079 (FLAGS_SET(u->cgroup_realized_mask, target_mask & CGROUP_MASK_V1) &&
3080 FLAGS_SET(u->cgroup_enabled_mask, enable_mask & CGROUP_MASK_V2));
3081 }
3082
3083 static bool unit_has_mask_enables_realized(
3084 Unit *u,
3085 CGroupMask target_mask,
3086 CGroupMask enable_mask) {
3087
3088 assert(u);
3089
3090 /* Returns true if all controllers which should be enabled are indeed enabled.
3091 *
3092 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
3093 * we want to add is already added. */
3094
3095 return u->cgroup_realized &&
3096 ((u->cgroup_realized_mask | target_mask) & CGROUP_MASK_V1) == (u->cgroup_realized_mask & CGROUP_MASK_V1) &&
3097 ((u->cgroup_enabled_mask | enable_mask) & CGROUP_MASK_V2) == (u->cgroup_enabled_mask & CGROUP_MASK_V2);
3098 }
3099
3100 void unit_add_to_cgroup_realize_queue(Unit *u) {
3101 assert(u);
3102
3103 if (u->in_cgroup_realize_queue)
3104 return;
3105
3106 LIST_APPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
3107 u->in_cgroup_realize_queue = true;
3108 }
3109
3110 static void unit_remove_from_cgroup_realize_queue(Unit *u) {
3111 assert(u);
3112
3113 if (!u->in_cgroup_realize_queue)
3114 return;
3115
3116 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
3117 u->in_cgroup_realize_queue = false;
3118 }
3119
3120 /* Controllers can only be enabled breadth-first, from the root of the
3121 * hierarchy downwards to the unit in question. */
3122 static int unit_realize_cgroup_now_enable(Unit *u, ManagerState state) {
3123 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
3124 Unit *slice;
3125 int r;
3126
3127 assert(u);
3128
3129 /* First go deal with this unit's parent, or we won't be able to enable
3130 * any new controllers at this layer. */
3131 slice = UNIT_GET_SLICE(u);
3132 if (slice) {
3133 r = unit_realize_cgroup_now_enable(slice, state);
3134 if (r < 0)
3135 return r;
3136 }
3137
3138 target_mask = unit_get_target_mask(u);
3139 enable_mask = unit_get_enable_mask(u);
3140
3141 /* We can only enable in this direction, don't try to disable anything.
3142 */
3143 if (unit_has_mask_enables_realized(u, target_mask, enable_mask))
3144 return 0;
3145
3146 new_target_mask = u->cgroup_realized_mask | target_mask;
3147 new_enable_mask = u->cgroup_enabled_mask | enable_mask;
3148
3149 return unit_update_cgroup(u, new_target_mask, new_enable_mask, state);
3150 }
3151
3152 /* Controllers can only be disabled depth-first, from the leaves of the
3153 * hierarchy upwards to the unit in question. */
3154 static int unit_realize_cgroup_now_disable(Unit *u, ManagerState state) {
3155 Unit *m;
3156
3157 assert(u);
3158
3159 if (u->type != UNIT_SLICE)
3160 return 0;
3161
3162 UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
3163 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
3164 int r;
3165
3166 /* The cgroup for this unit might not actually be fully realised yet, in which case it isn't
3167 * holding any controllers open anyway. */
3168 if (!m->cgroup_realized)
3169 continue;
3170
3171 /* We must disable those below us first in order to release the controller. */
3172 if (m->type == UNIT_SLICE)
3173 (void) unit_realize_cgroup_now_disable(m, state);
3174
3175 target_mask = unit_get_target_mask(m);
3176 enable_mask = unit_get_enable_mask(m);
3177
3178 /* We can only disable in this direction, don't try to enable anything. */
3179 if (unit_has_mask_disables_realized(m, target_mask, enable_mask))
3180 continue;
3181
3182 new_target_mask = m->cgroup_realized_mask & target_mask;
3183 new_enable_mask = m->cgroup_enabled_mask & enable_mask;
3184
3185 r = unit_update_cgroup(m, new_target_mask, new_enable_mask, state);
3186 if (r < 0)
3187 return r;
3188 }
3189
3190 return 0;
3191 }
3192
3193 /* Check if necessary controllers and attributes for a unit are in place.
3194 *
3195 * - If so, do nothing.
3196 * - If not, create paths, move processes over, and set attributes.
3197 *
3198 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
3199 * a depth-first way. As such the process looks like this:
3200 *
3201 * Suppose we have a cgroup hierarchy which looks like this:
3202 *
3203 * root
3204 * / \
3205 * / \
3206 * / \
3207 * a b
3208 * / \ / \
3209 * / \ / \
3210 * c d e f
3211 * / \ / \ / \ / \
3212 * h i j k l m n o
3213 *
3214 * 1. We want to realise cgroup "d" now.
3215 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
3216 * 3. cgroup "k" just started requesting the memory controller.
3217 *
3218 * To make this work we must do the following in order:
3219 *
3220 * 1. Disable CPU controller in k, j
3221 * 2. Disable CPU controller in d
3222 * 3. Enable memory controller in root
3223 * 4. Enable memory controller in a
3224 * 5. Enable memory controller in d
3225 * 6. Enable memory controller in k
3226 *
3227 * Notice that we need to touch j in one direction, but not the other. We also
3228 * don't go beyond d when disabling -- it's up to "a" to get realized if it
3229 * wants to disable further. The basic rules are therefore:
3230 *
3231 * - If you're disabling something, you need to realise all of the cgroups from
3232 * your recursive descendants to the root. This starts from the leaves.
3233 * - If you're enabling something, you need to realise from the root cgroup
3234 * downwards, but you don't need to iterate your recursive descendants.
3235 *
3236 * Returns 0 on success and < 0 on failure. */
3237 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
3238 CGroupMask target_mask, enable_mask;
3239 Unit *slice;
3240 int r;
3241
3242 assert(u);
3243
3244 unit_remove_from_cgroup_realize_queue(u);
3245
3246 target_mask = unit_get_target_mask(u);
3247 enable_mask = unit_get_enable_mask(u);
3248
3249 if (unit_has_mask_realized(u, target_mask, enable_mask))
3250 return 0;
3251
3252 /* Disable controllers below us, if there are any */
3253 r = unit_realize_cgroup_now_disable(u, state);
3254 if (r < 0)
3255 return r;
3256
3257 /* Enable controllers above us, if there are any */
3258 slice = UNIT_GET_SLICE(u);
3259 if (slice) {
3260 r = unit_realize_cgroup_now_enable(slice, state);
3261 if (r < 0)
3262 return r;
3263 }
3264
3265 /* Now actually deal with the cgroup we were trying to realise and set attributes */
3266 r = unit_update_cgroup(u, target_mask, enable_mask, state);
3267 if (r < 0)
3268 return r;
3269
3270 /* Now, reset the invalidation mask */
3271 u->cgroup_invalidated_mask = 0;
3272 return 0;
3273 }
3274
3275 unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
3276 ManagerState state;
3277 unsigned n = 0;
3278 Unit *i;
3279 int r;
3280
3281 assert(m);
3282
3283 state = manager_state(m);
3284
3285 while ((i = m->cgroup_realize_queue)) {
3286 assert(i->in_cgroup_realize_queue);
3287
3288 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
3289 /* Maybe things changed, and the unit is not actually active anymore? */
3290 unit_remove_from_cgroup_realize_queue(i);
3291 continue;
3292 }
3293
3294 r = unit_realize_cgroup_now(i, state);
3295 if (r < 0)
3296 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
3297
3298 n++;
3299 }
3300
3301 return n;
3302 }
3303
3304 void unit_add_family_to_cgroup_realize_queue(Unit *u) {
3305 assert(u);
3306 assert(u->type == UNIT_SLICE);
3307
3308 /* Family of a unit for is defined as (immediate) children of the unit and immediate children of all
3309 * its ancestors.
3310 *
3311 * Ideally we would enqueue ancestor path only (bottom up). However, on cgroup-v1 scheduling becomes
3312 * very weird if two units that own processes reside in the same slice, but one is realized in the
3313 * "cpu" hierarchy and one is not (for example because one has CPUWeight= set and the other does
3314 * not), because that means individual processes need to be scheduled against whole cgroups. Let's
3315 * avoid this asymmetry by always ensuring that siblings of a unit are always realized in their v1
3316 * controller hierarchies too (if unit requires the controller to be realized).
3317 *
3318 * The function must invalidate cgroup_members_mask of all ancestors in order to calculate up to date
3319 * masks. */
3320
3321 do {
3322 Unit *m;
3323
3324 /* Children of u likely changed when we're called */
3325 u->cgroup_members_mask_valid = false;
3326
3327 UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
3328
3329 /* No point in doing cgroup application for units without active processes. */
3330 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
3331 continue;
3332
3333 /* We only enqueue siblings if they were realized once at least, in the main
3334 * hierarchy. */
3335 if (!m->cgroup_realized)
3336 continue;
3337
3338 /* If the unit doesn't need any new controllers and has current ones
3339 * realized, it doesn't need any changes. */
3340 if (unit_has_mask_realized(m,
3341 unit_get_target_mask(m),
3342 unit_get_enable_mask(m)))
3343 continue;
3344
3345 unit_add_to_cgroup_realize_queue(m);
3346 }
3347
3348 /* Parent comes after children */
3349 unit_add_to_cgroup_realize_queue(u);
3350
3351 u = UNIT_GET_SLICE(u);
3352 } while (u);
3353 }
3354
3355 int unit_realize_cgroup(Unit *u) {
3356 Unit *slice;
3357
3358 assert(u);
3359
3360 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3361 return 0;
3362
3363 /* So, here's the deal: when realizing the cgroups for this unit, we need to first create all
3364 * parents, but there's more actually: for the weight-based controllers we also need to make sure
3365 * that all our siblings (i.e. units that are in the same slice as we are) have cgroups, too. On the
3366 * other hand, when a controller is removed from realized set, it may become unnecessary in siblings
3367 * and ancestors and they should be (de)realized too.
3368 *
3369 * This call will defer work on the siblings and derealized ancestors to the next event loop
3370 * iteration and synchronously creates the parent cgroups (unit_realize_cgroup_now). */
3371
3372 slice = UNIT_GET_SLICE(u);
3373 if (slice)
3374 unit_add_family_to_cgroup_realize_queue(slice);
3375
3376 /* And realize this one now (and apply the values) */
3377 return unit_realize_cgroup_now(u, manager_state(u->manager));
3378 }
3379
3380 void unit_release_cgroup(Unit *u) {
3381 assert(u);
3382
3383 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
3384 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
3385
3386 if (u->cgroup_path) {
3387 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
3388 u->cgroup_path = mfree(u->cgroup_path);
3389 }
3390
3391 if (u->cgroup_control_inotify_wd >= 0) {
3392 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_control_inotify_wd) < 0)
3393 log_unit_debug_errno(u, errno, "Failed to remove cgroup control inotify watch %i for %s, ignoring: %m", u->cgroup_control_inotify_wd, u->id);
3394
3395 (void) hashmap_remove(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd));
3396 u->cgroup_control_inotify_wd = -1;
3397 }
3398
3399 if (u->cgroup_memory_inotify_wd >= 0) {
3400 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_memory_inotify_wd) < 0)
3401 log_unit_debug_errno(u, errno, "Failed to remove cgroup memory inotify watch %i for %s, ignoring: %m", u->cgroup_memory_inotify_wd, u->id);
3402
3403 (void) hashmap_remove(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd));
3404 u->cgroup_memory_inotify_wd = -1;
3405 }
3406 }
3407
3408 bool unit_maybe_release_cgroup(Unit *u) {
3409 int r;
3410
3411 assert(u);
3412
3413 if (!u->cgroup_path)
3414 return true;
3415
3416 /* Don't release the cgroup if there are still processes under it. If we get notified later when all the
3417 * processes exit (e.g. the processes were in D-state and exited after the unit was marked as failed)
3418 * we need the cgroup paths to continue to be tracked by the manager so they can be looked up and cleaned
3419 * up later. */
3420 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
3421 if (r < 0)
3422 log_unit_debug_errno(u, r, "Error checking if the cgroup is recursively empty, ignoring: %m");
3423 else if (r == 1) {
3424 unit_release_cgroup(u);
3425 return true;
3426 }
3427
3428 return false;
3429 }
3430
3431 void unit_prune_cgroup(Unit *u) {
3432 int r;
3433 bool is_root_slice;
3434
3435 assert(u);
3436
3437 /* Removes the cgroup, if empty and possible, and stops watching it. */
3438
3439 if (!u->cgroup_path)
3440 return;
3441
3442 /* Cache the last CPU and memory usage values before we destroy the cgroup */
3443 (void) unit_get_cpu_usage(u, /* ret = */ NULL);
3444
3445 for (CGroupMemoryAccountingMetric metric = 0; metric <= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST; metric++)
3446 (void) unit_get_memory_accounting(u, metric, /* ret = */ NULL);
3447
3448 #if BPF_FRAMEWORK
3449 (void) lsm_bpf_cleanup(u); /* Remove cgroup from the global LSM BPF map */
3450 #endif
3451
3452 unit_modify_nft_set(u, /* add = */ false);
3453
3454 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
3455
3456 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
3457 if (r < 0)
3458 /* One reason we could have failed here is, that the cgroup still contains a process.
3459 * However, if the cgroup becomes removable at a later time, it might be removed when
3460 * the containing slice is stopped. So even if we failed now, this unit shouldn't assume
3461 * that the cgroup is still realized the next time it is started. Do not return early
3462 * on error, continue cleanup. */
3463 log_unit_full_errno(u, r == -EBUSY ? LOG_DEBUG : LOG_WARNING, r, "Failed to destroy cgroup %s, ignoring: %m", empty_to_root(u->cgroup_path));
3464
3465 if (is_root_slice)
3466 return;
3467
3468 if (!unit_maybe_release_cgroup(u)) /* Returns true if the cgroup was released */
3469 return;
3470
3471 u->cgroup_realized = false;
3472 u->cgroup_realized_mask = 0;
3473 u->cgroup_enabled_mask = 0;
3474
3475 u->bpf_device_control_installed = bpf_program_free(u->bpf_device_control_installed);
3476 }
3477
3478 int unit_search_main_pid(Unit *u, PidRef *ret) {
3479 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
3480 _cleanup_fclose_ FILE *f = NULL;
3481 int r;
3482
3483 assert(u);
3484 assert(ret);
3485
3486 if (!u->cgroup_path)
3487 return -ENXIO;
3488
3489 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
3490 if (r < 0)
3491 return r;
3492
3493 for (;;) {
3494 _cleanup_(pidref_done) PidRef npidref = PIDREF_NULL;
3495
3496 r = cg_read_pidref(f, &npidref);
3497 if (r < 0)
3498 return r;
3499 if (r == 0)
3500 break;
3501
3502 if (pidref_equal(&pidref, &npidref)) /* seen already, cgroupfs reports duplicates! */
3503 continue;
3504
3505 if (pidref_is_my_child(&npidref) <= 0) /* ignore processes further down the tree */
3506 continue;
3507
3508 if (pidref_is_set(&pidref) != 0)
3509 /* Dang, there's more than one daemonized PID in this group, so we don't know what
3510 * process is the main process. */
3511 return -ENODATA;
3512
3513 pidref = TAKE_PIDREF(npidref);
3514 }
3515
3516 if (!pidref_is_set(&pidref))
3517 return -ENODATA;
3518
3519 *ret = TAKE_PIDREF(pidref);
3520 return 0;
3521 }
3522
3523 static int unit_watch_pids_in_path(Unit *u, const char *path) {
3524 _cleanup_closedir_ DIR *d = NULL;
3525 _cleanup_fclose_ FILE *f = NULL;
3526 int ret = 0, r;
3527
3528 assert(u);
3529 assert(path);
3530
3531 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
3532 if (r < 0)
3533 RET_GATHER(ret, r);
3534 else {
3535 for (;;) {
3536 _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
3537
3538 r = cg_read_pidref(f, &pid);
3539 if (r == 0)
3540 break;
3541 if (r < 0) {
3542 RET_GATHER(ret, r);
3543 break;
3544 }
3545
3546 RET_GATHER(ret, unit_watch_pidref(u, &pid, /* exclusive= */ false));
3547 }
3548 }
3549
3550 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
3551 if (r < 0)
3552 RET_GATHER(ret, r);
3553 else {
3554 for (;;) {
3555 _cleanup_free_ char *fn = NULL, *p = NULL;
3556
3557 r = cg_read_subgroup(d, &fn);
3558 if (r == 0)
3559 break;
3560 if (r < 0) {
3561 RET_GATHER(ret, r);
3562 break;
3563 }
3564
3565 p = path_join(empty_to_root(path), fn);
3566 if (!p)
3567 return -ENOMEM;
3568
3569 RET_GATHER(ret, unit_watch_pids_in_path(u, p));
3570 }
3571 }
3572
3573 return ret;
3574 }
3575
3576 int unit_synthesize_cgroup_empty_event(Unit *u) {
3577 int r;
3578
3579 assert(u);
3580
3581 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
3582 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
3583 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
3584
3585 if (!u->cgroup_path)
3586 return -ENOENT;
3587
3588 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
3589 if (r < 0)
3590 return r;
3591 if (r > 0) /* On unified we have reliable notifications, and don't need this */
3592 return 0;
3593
3594 if (!set_isempty(u->pids))
3595 return 0;
3596
3597 unit_add_to_cgroup_empty_queue(u);
3598 return 0;
3599 }
3600
3601 int unit_watch_all_pids(Unit *u) {
3602 int r;
3603
3604 assert(u);
3605
3606 /* Adds all PIDs from our cgroup to the set of PIDs we
3607 * watch. This is a fallback logic for cases where we do not
3608 * get reliable cgroup empty notifications: we try to use
3609 * SIGCHLD as replacement. */
3610
3611 if (!u->cgroup_path)
3612 return -ENOENT;
3613
3614 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
3615 if (r < 0)
3616 return r;
3617 if (r > 0) /* On unified we can use proper notifications */
3618 return 0;
3619
3620 return unit_watch_pids_in_path(u, u->cgroup_path);
3621 }
3622
3623 static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
3624 Manager *m = ASSERT_PTR(userdata);
3625 Unit *u;
3626 int r;
3627
3628 assert(s);
3629
3630 u = m->cgroup_empty_queue;
3631 if (!u)
3632 return 0;
3633
3634 assert(u->in_cgroup_empty_queue);
3635 u->in_cgroup_empty_queue = false;
3636 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
3637
3638 if (m->cgroup_empty_queue) {
3639 /* More stuff queued, let's make sure we remain enabled */
3640 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
3641 if (r < 0)
3642 log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
3643 }
3644
3645 /* Update state based on OOM kills before we notify about cgroup empty event */
3646 (void) unit_check_oom(u);
3647 (void) unit_check_oomd_kill(u);
3648
3649 unit_add_to_gc_queue(u);
3650
3651 if (IN_SET(unit_active_state(u), UNIT_INACTIVE, UNIT_FAILED))
3652 unit_prune_cgroup(u);
3653 else if (UNIT_VTABLE(u)->notify_cgroup_empty)
3654 UNIT_VTABLE(u)->notify_cgroup_empty(u);
3655
3656 return 0;
3657 }
3658
3659 void unit_add_to_cgroup_empty_queue(Unit *u) {
3660 int r;
3661
3662 assert(u);
3663
3664 /* Note that there are four different ways how cgroup empty events reach us:
3665 *
3666 * 1. On the unified hierarchy we get an inotify event on the cgroup
3667 *
3668 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
3669 *
3670 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
3671 *
3672 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
3673 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
3674 *
3675 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
3676 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
3677 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
3678 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
3679 * case for scope units). */
3680
3681 if (u->in_cgroup_empty_queue)
3682 return;
3683
3684 /* Let's verify that the cgroup is really empty */
3685 if (!u->cgroup_path)
3686 return;
3687
3688 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
3689 if (r < 0) {
3690 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", empty_to_root(u->cgroup_path));
3691 return;
3692 }
3693 if (r == 0)
3694 return;
3695
3696 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
3697 u->in_cgroup_empty_queue = true;
3698
3699 /* Trigger the defer event */
3700 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
3701 if (r < 0)
3702 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
3703 }
3704
3705 static void unit_remove_from_cgroup_empty_queue(Unit *u) {
3706 assert(u);
3707
3708 if (!u->in_cgroup_empty_queue)
3709 return;
3710
3711 LIST_REMOVE(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
3712 u->in_cgroup_empty_queue = false;
3713 }
3714
3715 int unit_check_oomd_kill(Unit *u) {
3716 _cleanup_free_ char *value = NULL;
3717 bool increased;
3718 uint64_t n = 0;
3719 int r;
3720
3721 if (!u->cgroup_path)
3722 return 0;
3723
3724 r = cg_all_unified();
3725 if (r < 0)
3726 return log_unit_debug_errno(u, r, "Couldn't determine whether we are in all unified mode: %m");
3727 else if (r == 0)
3728 return 0;
3729
3730 r = cg_get_xattr_malloc(u->cgroup_path, "user.oomd_ooms", &value);
3731 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
3732 return r;
3733
3734 if (!isempty(value)) {
3735 r = safe_atou64(value, &n);
3736 if (r < 0)
3737 return r;
3738 }
3739
3740 increased = n > u->managed_oom_kill_last;
3741 u->managed_oom_kill_last = n;
3742
3743 if (!increased)
3744 return 0;
3745
3746 n = 0;
3747 value = mfree(value);
3748 r = cg_get_xattr_malloc(u->cgroup_path, "user.oomd_kill", &value);
3749 if (r >= 0 && !isempty(value))
3750 (void) safe_atou64(value, &n);
3751
3752 if (n > 0)
3753 log_unit_struct(u, LOG_NOTICE,
3754 "MESSAGE_ID=" SD_MESSAGE_UNIT_OOMD_KILL_STR,
3755 LOG_UNIT_INVOCATION_ID(u),
3756 LOG_UNIT_MESSAGE(u, "systemd-oomd killed %"PRIu64" process(es) in this unit.", n),
3757 "N_PROCESSES=%" PRIu64, n);
3758 else
3759 log_unit_struct(u, LOG_NOTICE,
3760 "MESSAGE_ID=" SD_MESSAGE_UNIT_OOMD_KILL_STR,
3761 LOG_UNIT_INVOCATION_ID(u),
3762 LOG_UNIT_MESSAGE(u, "systemd-oomd killed some process(es) in this unit."));
3763
3764 unit_notify_cgroup_oom(u, /* ManagedOOM= */ true);
3765
3766 return 1;
3767 }
3768
3769 int unit_check_oom(Unit *u) {
3770 _cleanup_free_ char *oom_kill = NULL;
3771 bool increased;
3772 uint64_t c;
3773 int r;
3774
3775 if (!u->cgroup_path)
3776 return 0;
3777
3778 r = cg_get_keyed_attribute("memory", u->cgroup_path, "memory.events", STRV_MAKE("oom_kill"), &oom_kill);
3779 if (IN_SET(r, -ENOENT, -ENXIO)) /* Handle gracefully if cgroup or oom_kill attribute don't exist */
3780 c = 0;
3781 else if (r < 0)
3782 return log_unit_debug_errno(u, r, "Failed to read oom_kill field of memory.events cgroup attribute: %m");
3783 else {
3784 r = safe_atou64(oom_kill, &c);
3785 if (r < 0)
3786 return log_unit_debug_errno(u, r, "Failed to parse oom_kill field: %m");
3787 }
3788
3789 increased = c > u->oom_kill_last;
3790 u->oom_kill_last = c;
3791
3792 if (!increased)
3793 return 0;
3794
3795 log_unit_struct(u, LOG_NOTICE,
3796 "MESSAGE_ID=" SD_MESSAGE_UNIT_OUT_OF_MEMORY_STR,
3797 LOG_UNIT_INVOCATION_ID(u),
3798 LOG_UNIT_MESSAGE(u, "A process of this unit has been killed by the OOM killer."));
3799
3800 unit_notify_cgroup_oom(u, /* ManagedOOM= */ false);
3801
3802 return 1;
3803 }
3804
3805 static int on_cgroup_oom_event(sd_event_source *s, void *userdata) {
3806 Manager *m = ASSERT_PTR(userdata);
3807 Unit *u;
3808 int r;
3809
3810 assert(s);
3811
3812 u = m->cgroup_oom_queue;
3813 if (!u)
3814 return 0;
3815
3816 assert(u->in_cgroup_oom_queue);
3817 u->in_cgroup_oom_queue = false;
3818 LIST_REMOVE(cgroup_oom_queue, m->cgroup_oom_queue, u);
3819
3820 if (m->cgroup_oom_queue) {
3821 /* More stuff queued, let's make sure we remain enabled */
3822 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
3823 if (r < 0)
3824 log_debug_errno(r, "Failed to reenable cgroup oom event source, ignoring: %m");
3825 }
3826
3827 (void) unit_check_oom(u);
3828 unit_add_to_gc_queue(u);
3829
3830 return 0;
3831 }
3832
3833 static void unit_add_to_cgroup_oom_queue(Unit *u) {
3834 int r;
3835
3836 assert(u);
3837
3838 if (u->in_cgroup_oom_queue)
3839 return;
3840 if (!u->cgroup_path)
3841 return;
3842
3843 LIST_PREPEND(cgroup_oom_queue, u->manager->cgroup_oom_queue, u);
3844 u->in_cgroup_oom_queue = true;
3845
3846 /* Trigger the defer event */
3847 if (!u->manager->cgroup_oom_event_source) {
3848 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
3849
3850 r = sd_event_add_defer(u->manager->event, &s, on_cgroup_oom_event, u->manager);
3851 if (r < 0) {
3852 log_error_errno(r, "Failed to create cgroup oom event source: %m");
3853 return;
3854 }
3855
3856 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_NORMAL-8);
3857 if (r < 0) {
3858 log_error_errno(r, "Failed to set priority of cgroup oom event source: %m");
3859 return;
3860 }
3861
3862 (void) sd_event_source_set_description(s, "cgroup-oom");
3863 u->manager->cgroup_oom_event_source = TAKE_PTR(s);
3864 }
3865
3866 r = sd_event_source_set_enabled(u->manager->cgroup_oom_event_source, SD_EVENT_ONESHOT);
3867 if (r < 0)
3868 log_error_errno(r, "Failed to enable cgroup oom event source: %m");
3869 }
3870
3871 static int unit_check_cgroup_events(Unit *u) {
3872 char *values[2] = {};
3873 int r;
3874
3875 assert(u);
3876
3877 if (!u->cgroup_path)
3878 return 0;
3879
3880 r = cg_get_keyed_attribute_graceful(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events",
3881 STRV_MAKE("populated", "frozen"), values);
3882 if (r < 0)
3883 return r;
3884
3885 /* The cgroup.events notifications can be merged together so act as we saw the given state for the
3886 * first time. The functions we call to handle given state are idempotent, which makes them
3887 * effectively remember the previous state. */
3888 if (values[0]) {
3889 if (streq(values[0], "1"))
3890 unit_remove_from_cgroup_empty_queue(u);
3891 else
3892 unit_add_to_cgroup_empty_queue(u);
3893 }
3894
3895 /* Disregard freezer state changes due to operations not initiated by us */
3896 if (values[1] && IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_THAWING)) {
3897 if (streq(values[1], "0"))
3898 unit_thawed(u);
3899 else
3900 unit_frozen(u);
3901 }
3902
3903 free(values[0]);
3904 free(values[1]);
3905
3906 return 0;
3907 }
3908
3909 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
3910 Manager *m = ASSERT_PTR(userdata);
3911
3912 assert(s);
3913 assert(fd >= 0);
3914
3915 for (;;) {
3916 union inotify_event_buffer buffer;
3917 ssize_t l;
3918
3919 l = read(fd, &buffer, sizeof(buffer));
3920 if (l < 0) {
3921 if (ERRNO_IS_TRANSIENT(errno))
3922 return 0;
3923
3924 return log_error_errno(errno, "Failed to read control group inotify events: %m");
3925 }
3926
3927 FOREACH_INOTIFY_EVENT_WARN(e, buffer, l) {
3928 Unit *u;
3929
3930 if (e->wd < 0)
3931 /* Queue overflow has no watch descriptor */
3932 continue;
3933
3934 if (e->mask & IN_IGNORED)
3935 /* The watch was just removed */
3936 continue;
3937
3938 /* Note that inotify might deliver events for a watch even after it was removed,
3939 * because it was queued before the removal. Let's ignore this here safely. */
3940
3941 u = hashmap_get(m->cgroup_control_inotify_wd_unit, INT_TO_PTR(e->wd));
3942 if (u)
3943 unit_check_cgroup_events(u);
3944
3945 u = hashmap_get(m->cgroup_memory_inotify_wd_unit, INT_TO_PTR(e->wd));
3946 if (u)
3947 unit_add_to_cgroup_oom_queue(u);
3948 }
3949 }
3950 }
3951
3952 static int cg_bpf_mask_supported(CGroupMask *ret) {
3953 CGroupMask mask = 0;
3954 int r;
3955
3956 /* BPF-based firewall */
3957 r = bpf_firewall_supported();
3958 if (r < 0)
3959 return r;
3960 if (r > 0)
3961 mask |= CGROUP_MASK_BPF_FIREWALL;
3962
3963 /* BPF-based device access control */
3964 r = bpf_devices_supported();
3965 if (r < 0)
3966 return r;
3967 if (r > 0)
3968 mask |= CGROUP_MASK_BPF_DEVICES;
3969
3970 /* BPF pinned prog */
3971 r = bpf_foreign_supported();
3972 if (r < 0)
3973 return r;
3974 if (r > 0)
3975 mask |= CGROUP_MASK_BPF_FOREIGN;
3976
3977 /* BPF-based bind{4|6} hooks */
3978 r = bpf_socket_bind_supported();
3979 if (r < 0)
3980 return r;
3981 if (r > 0)
3982 mask |= CGROUP_MASK_BPF_SOCKET_BIND;
3983
3984 /* BPF-based cgroup_skb/{egress|ingress} hooks */
3985 r = restrict_network_interfaces_supported();
3986 if (r < 0)
3987 return r;
3988 if (r > 0)
3989 mask |= CGROUP_MASK_BPF_RESTRICT_NETWORK_INTERFACES;
3990
3991 *ret = mask;
3992 return 0;
3993 }
3994
3995 int manager_setup_cgroup(Manager *m) {
3996 _cleanup_free_ char *path = NULL;
3997 const char *scope_path;
3998 int r, all_unified;
3999 CGroupMask mask;
4000 char *e;
4001
4002 assert(m);
4003
4004 /* 1. Determine hierarchy */
4005 m->cgroup_root = mfree(m->cgroup_root);
4006 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
4007 if (r < 0)
4008 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
4009
4010 /* Chop off the init scope, if we are already located in it */
4011 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
4012
4013 /* LEGACY: Also chop off the system slice if we are in
4014 * it. This is to support live upgrades from older systemd
4015 * versions where PID 1 was moved there. Also see
4016 * cg_get_root_path(). */
4017 if (!e && MANAGER_IS_SYSTEM(m)) {
4018 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
4019 if (!e)
4020 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
4021 }
4022 if (e)
4023 *e = 0;
4024
4025 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
4026 * easily prepend it everywhere. */
4027 delete_trailing_chars(m->cgroup_root, "/");
4028
4029 /* 2. Show data */
4030 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
4031 if (r < 0)
4032 return log_error_errno(r, "Cannot find cgroup mount point: %m");
4033
4034 r = cg_unified();
4035 if (r < 0)
4036 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
4037
4038 all_unified = cg_all_unified();
4039 if (all_unified < 0)
4040 return log_error_errno(all_unified, "Couldn't determine whether we are in all unified mode: %m");
4041 if (all_unified > 0)
4042 log_debug("Unified cgroup hierarchy is located at %s.", path);
4043 else {
4044 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
4045 if (r < 0)
4046 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
4047 if (r > 0)
4048 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
4049 else
4050 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
4051 }
4052
4053 /* 3. Allocate cgroup empty defer event source */
4054 m->cgroup_empty_event_source = sd_event_source_disable_unref(m->cgroup_empty_event_source);
4055 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
4056 if (r < 0)
4057 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
4058
4059 /* Schedule cgroup empty checks early, but after having processed service notification messages or
4060 * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of
4061 * notification, and we collected the metadata the notification and SIGCHLD stuff offers first. */
4062 r = sd_event_source_set_priority(m->cgroup_empty_event_source, SD_EVENT_PRIORITY_NORMAL-5);
4063 if (r < 0)
4064 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
4065
4066 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
4067 if (r < 0)
4068 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
4069
4070 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
4071
4072 /* 4. Install notifier inotify object, or agent */
4073 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
4074
4075 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
4076
4077 m->cgroup_inotify_event_source = sd_event_source_disable_unref(m->cgroup_inotify_event_source);
4078 safe_close(m->cgroup_inotify_fd);
4079
4080 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
4081 if (m->cgroup_inotify_fd < 0)
4082 return log_error_errno(errno, "Failed to create control group inotify object: %m");
4083
4084 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
4085 if (r < 0)
4086 return log_error_errno(r, "Failed to watch control group inotify object: %m");
4087
4088 /* Process cgroup empty notifications early. Note that when this event is dispatched it'll
4089 * just add the unit to a cgroup empty queue, hence let's run earlier than that. Also see
4090 * handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
4091 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-9);
4092 if (r < 0)
4093 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
4094
4095 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
4096
4097 } else if (MANAGER_IS_SYSTEM(m) && manager_owns_host_root_cgroup(m) && !MANAGER_IS_TEST_RUN(m)) {
4098
4099 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
4100 * since it does not generate events when control groups with children run empty. */
4101
4102 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUPS_AGENT_PATH);
4103 if (r < 0)
4104 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
4105 else if (r > 0)
4106 log_debug("Installed release agent.");
4107 else if (r == 0)
4108 log_debug("Release agent already installed.");
4109 }
4110
4111 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
4112 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
4113 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
4114 if (r >= 0) {
4115 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
4116 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
4117 if (r < 0)
4118 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
4119
4120 /* 6. And pin it, so that it cannot be unmounted */
4121 safe_close(m->pin_cgroupfs_fd);
4122 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
4123 if (m->pin_cgroupfs_fd < 0)
4124 return log_error_errno(errno, "Failed to open pin file: %m");
4125
4126 } else if (!MANAGER_IS_TEST_RUN(m))
4127 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
4128
4129 /* 7. Always enable hierarchical support if it exists... */
4130 if (!all_unified && !MANAGER_IS_TEST_RUN(m))
4131 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
4132
4133 /* 8. Figure out which controllers are supported */
4134 r = cg_mask_supported_subtree(m->cgroup_root, &m->cgroup_supported);
4135 if (r < 0)
4136 return log_error_errno(r, "Failed to determine supported controllers: %m");
4137
4138 /* 9. Figure out which bpf-based pseudo-controllers are supported */
4139 r = cg_bpf_mask_supported(&mask);
4140 if (r < 0)
4141 return log_error_errno(r, "Failed to determine supported bpf-based pseudo-controllers: %m");
4142 m->cgroup_supported |= mask;
4143
4144 /* 10. Log which controllers are supported */
4145 for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
4146 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c),
4147 yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
4148
4149 return 0;
4150 }
4151
4152 void manager_shutdown_cgroup(Manager *m, bool delete) {
4153 assert(m);
4154
4155 /* We can't really delete the group, since we are in it. But
4156 * let's trim it. */
4157 if (delete && m->cgroup_root && !FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
4158 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
4159
4160 m->cgroup_empty_event_source = sd_event_source_disable_unref(m->cgroup_empty_event_source);
4161
4162 m->cgroup_control_inotify_wd_unit = hashmap_free(m->cgroup_control_inotify_wd_unit);
4163 m->cgroup_memory_inotify_wd_unit = hashmap_free(m->cgroup_memory_inotify_wd_unit);
4164
4165 m->cgroup_inotify_event_source = sd_event_source_disable_unref(m->cgroup_inotify_event_source);
4166 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
4167
4168 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
4169
4170 m->cgroup_root = mfree(m->cgroup_root);
4171 }
4172
4173 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
4174 char *p;
4175 Unit *u;
4176
4177 assert(m);
4178 assert(cgroup);
4179
4180 u = hashmap_get(m->cgroup_unit, cgroup);
4181 if (u)
4182 return u;
4183
4184 p = strdupa_safe(cgroup);
4185 for (;;) {
4186 char *e;
4187
4188 e = strrchr(p, '/');
4189 if (!e || e == p)
4190 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
4191
4192 *e = 0;
4193
4194 u = hashmap_get(m->cgroup_unit, p);
4195 if (u)
4196 return u;
4197 }
4198 }
4199
4200 Unit *manager_get_unit_by_pidref_cgroup(Manager *m, PidRef *pid) {
4201 _cleanup_free_ char *cgroup = NULL;
4202
4203 assert(m);
4204
4205 if (cg_pidref_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup) < 0)
4206 return NULL;
4207
4208 return manager_get_unit_by_cgroup(m, cgroup);
4209 }
4210
4211 Unit *manager_get_unit_by_pidref_watching(Manager *m, PidRef *pid) {
4212 Unit *u, **array;
4213
4214 assert(m);
4215
4216 if (!pidref_is_set(pid))
4217 return NULL;
4218
4219 u = hashmap_get(m->watch_pids, pid);
4220 if (u)
4221 return u;
4222
4223 array = hashmap_get(m->watch_pids_more, pid);
4224 if (array)
4225 return array[0];
4226
4227 return NULL;
4228 }
4229
4230 Unit *manager_get_unit_by_pidref(Manager *m, PidRef *pid) {
4231 Unit *u;
4232
4233 assert(m);
4234
4235 /* Note that a process might be owned by multiple units, we return only one here, which is good
4236 * enough for most cases, though not strictly correct. We prefer the one reported by cgroup
4237 * membership, as that's the most relevant one as children of the process will be assigned to that
4238 * one, too, before all else. */
4239
4240 if (!pidref_is_set(pid))
4241 return NULL;
4242
4243 if (pidref_is_self(pid))
4244 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
4245 if (pid->pid == 1)
4246 return NULL;
4247
4248 u = manager_get_unit_by_pidref_cgroup(m, pid);
4249 if (u)
4250 return u;
4251
4252 u = manager_get_unit_by_pidref_watching(m, pid);
4253 if (u)
4254 return u;
4255
4256 return NULL;
4257 }
4258
4259 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
4260 assert(m);
4261
4262 if (!pid_is_valid(pid))
4263 return NULL;
4264
4265 return manager_get_unit_by_pidref(m, &PIDREF_MAKE_FROM_PID(pid));
4266 }
4267
4268 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
4269 Unit *u;
4270
4271 assert(m);
4272 assert(cgroup);
4273
4274 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
4275 * or from the --system instance */
4276
4277 log_debug("Got cgroup empty notification for: %s", cgroup);
4278
4279 u = manager_get_unit_by_cgroup(m, cgroup);
4280 if (!u)
4281 return 0;
4282
4283 unit_add_to_cgroup_empty_queue(u);
4284 return 1;
4285 }
4286
4287 int unit_get_memory_available(Unit *u, uint64_t *ret) {
4288 uint64_t available = UINT64_MAX, current = 0;
4289
4290 assert(u);
4291 assert(ret);
4292
4293 /* If data from cgroups can be accessed, try to find out how much more memory a unit can
4294 * claim before hitting the configured cgroup limits (if any). Consider both MemoryHigh
4295 * and MemoryMax, and also any slice the unit might be nested below. */
4296
4297 do {
4298 uint64_t unit_available, unit_limit = UINT64_MAX;
4299 CGroupContext *unit_context;
4300
4301 /* No point in continuing if we can't go any lower */
4302 if (available == 0)
4303 break;
4304
4305 unit_context = unit_get_cgroup_context(u);
4306 if (!unit_context)
4307 return -ENODATA;
4308
4309 if (!u->cgroup_path)
4310 continue;
4311
4312 (void) unit_get_memory_current(u, &current);
4313 /* in case of error, previous current propagates as lower bound */
4314
4315 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
4316 unit_limit = physical_memory();
4317 else if (unit_context->memory_max == UINT64_MAX && unit_context->memory_high == UINT64_MAX)
4318 continue;
4319 unit_limit = MIN3(unit_limit, unit_context->memory_max, unit_context->memory_high);
4320
4321 unit_available = LESS_BY(unit_limit, current);
4322 available = MIN(unit_available, available);
4323 } while ((u = UNIT_GET_SLICE(u)));
4324
4325 *ret = available;
4326
4327 return 0;
4328 }
4329
4330 int unit_get_memory_current(Unit *u, uint64_t *ret) {
4331 int r;
4332
4333 // FIXME: Merge this into unit_get_memory_accounting after support for cgroup v1 is dropped
4334
4335 assert(u);
4336 assert(ret);
4337
4338 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
4339 return -ENODATA;
4340
4341 if (!u->cgroup_path)
4342 return -ENODATA;
4343
4344 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
4345 if (unit_has_host_root_cgroup(u))
4346 return procfs_memory_get_used(ret);
4347
4348 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
4349 return -ENODATA;
4350
4351 r = cg_all_unified();
4352 if (r < 0)
4353 return r;
4354
4355 return cg_get_attribute_as_uint64("memory", u->cgroup_path, r > 0 ? "memory.current" : "memory.usage_in_bytes", ret);
4356 }
4357
4358 int unit_get_memory_accounting(Unit *u, CGroupMemoryAccountingMetric metric, uint64_t *ret) {
4359
4360 static const char* const attributes_table[_CGROUP_MEMORY_ACCOUNTING_METRIC_MAX] = {
4361 [CGROUP_MEMORY_PEAK] = "memory.peak",
4362 [CGROUP_MEMORY_SWAP_CURRENT] = "memory.swap.current",
4363 [CGROUP_MEMORY_SWAP_PEAK] = "memory.swap.peak",
4364 [CGROUP_MEMORY_ZSWAP_CURRENT] = "memory.zswap.current",
4365 };
4366
4367 uint64_t bytes;
4368 bool updated = false;
4369 int r;
4370
4371 assert(u);
4372 assert(metric >= 0);
4373 assert(metric < _CGROUP_MEMORY_ACCOUNTING_METRIC_MAX);
4374
4375 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
4376 return -ENODATA;
4377
4378 if (!u->cgroup_path)
4379 /* If the cgroup is already gone, we try to find the last cached value. */
4380 goto finish;
4381
4382 /* The root cgroup doesn't expose this information. */
4383 if (unit_has_host_root_cgroup(u))
4384 return -ENODATA;
4385
4386 if (!FLAGS_SET(u->cgroup_realized_mask, CGROUP_MASK_MEMORY))
4387 return -ENODATA;
4388
4389 r = cg_all_unified();
4390 if (r < 0)
4391 return r;
4392 if (r == 0)
4393 return -ENODATA;
4394
4395 r = cg_get_attribute_as_uint64("memory", u->cgroup_path, attributes_table[metric], &bytes);
4396 if (r < 0 && r != -ENODATA)
4397 return r;
4398 updated = r >= 0;
4399
4400 finish:
4401 if (metric <= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST) {
4402 uint64_t *last = &u->memory_accounting_last[metric];
4403
4404 if (updated)
4405 *last = bytes;
4406 else if (*last != UINT64_MAX)
4407 bytes = *last;
4408 else
4409 return -ENODATA;
4410
4411 } else if (!updated)
4412 return -ENODATA;
4413
4414 if (ret)
4415 *ret = bytes;
4416
4417 return 0;
4418 }
4419
4420 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
4421 assert(u);
4422 assert(ret);
4423
4424 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
4425 return -ENODATA;
4426
4427 if (!u->cgroup_path)
4428 return -ENODATA;
4429
4430 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
4431 if (unit_has_host_root_cgroup(u))
4432 return procfs_tasks_get_current(ret);
4433
4434 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
4435 return -ENODATA;
4436
4437 return cg_get_attribute_as_uint64("pids", u->cgroup_path, "pids.current", ret);
4438 }
4439
4440 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
4441 uint64_t ns;
4442 int r;
4443
4444 assert(u);
4445 assert(ret);
4446
4447 if (!u->cgroup_path)
4448 return -ENODATA;
4449
4450 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
4451 if (unit_has_host_root_cgroup(u))
4452 return procfs_cpu_get_usage(ret);
4453
4454 /* Requisite controllers for CPU accounting are not enabled */
4455 if ((get_cpu_accounting_mask() & ~u->cgroup_realized_mask) != 0)
4456 return -ENODATA;
4457
4458 r = cg_all_unified();
4459 if (r < 0)
4460 return r;
4461 if (r > 0) {
4462 _cleanup_free_ char *val = NULL;
4463 uint64_t us;
4464
4465 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
4466 if (IN_SET(r, -ENOENT, -ENXIO))
4467 return -ENODATA;
4468 if (r < 0)
4469 return r;
4470
4471 r = safe_atou64(val, &us);
4472 if (r < 0)
4473 return r;
4474
4475 ns = us * NSEC_PER_USEC;
4476 } else
4477 return cg_get_attribute_as_uint64("cpuacct", u->cgroup_path, "cpuacct.usage", ret);
4478
4479 *ret = ns;
4480 return 0;
4481 }
4482
4483 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
4484 nsec_t ns;
4485 int r;
4486
4487 assert(u);
4488
4489 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
4490 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
4491 * call this function with a NULL return value. */
4492
4493 if (!UNIT_CGROUP_BOOL(u, cpu_accounting))
4494 return -ENODATA;
4495
4496 r = unit_get_cpu_usage_raw(u, &ns);
4497 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
4498 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
4499 * cached value. */
4500
4501 if (ret)
4502 *ret = u->cpu_usage_last;
4503 return 0;
4504 }
4505 if (r < 0)
4506 return r;
4507
4508 if (ns > u->cpu_usage_base)
4509 ns -= u->cpu_usage_base;
4510 else
4511 ns = 0;
4512
4513 u->cpu_usage_last = ns;
4514 if (ret)
4515 *ret = ns;
4516
4517 return 0;
4518 }
4519
4520 int unit_get_ip_accounting(
4521 Unit *u,
4522 CGroupIPAccountingMetric metric,
4523 uint64_t *ret) {
4524
4525 uint64_t value;
4526 int fd, r;
4527
4528 assert(u);
4529 assert(metric >= 0);
4530 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
4531 assert(ret);
4532
4533 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
4534 return -ENODATA;
4535
4536 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
4537 u->ip_accounting_ingress_map_fd :
4538 u->ip_accounting_egress_map_fd;
4539 if (fd < 0)
4540 return -ENODATA;
4541
4542 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
4543 r = bpf_firewall_read_accounting(fd, &value, NULL);
4544 else
4545 r = bpf_firewall_read_accounting(fd, NULL, &value);
4546 if (r < 0)
4547 return r;
4548
4549 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
4550 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
4551 * ip_accounting_extra[] field, and add them in here transparently. */
4552
4553 *ret = value + u->ip_accounting_extra[metric];
4554
4555 return r;
4556 }
4557
4558 static uint64_t unit_get_effective_limit_one(Unit *u, CGroupLimitType type) {
4559 CGroupContext *cc;
4560
4561 assert(u);
4562 assert(UNIT_HAS_CGROUP_CONTEXT(u));
4563
4564 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
4565 switch (type) {
4566 case CGROUP_LIMIT_MEMORY_MAX:
4567 case CGROUP_LIMIT_MEMORY_HIGH:
4568 return physical_memory();
4569 case CGROUP_LIMIT_TASKS_MAX:
4570 return system_tasks_max();
4571 default:
4572 assert_not_reached();
4573 }
4574
4575 cc = unit_get_cgroup_context(u);
4576 switch (type) {
4577 /* Note: on legacy/hybrid hierarchies memory_max stays CGROUP_LIMIT_MAX unless configured
4578 * explicitly. Effective value of MemoryLimit= (cgroup v1) is not implemented. */
4579 case CGROUP_LIMIT_MEMORY_MAX:
4580 return cc->memory_max;
4581 case CGROUP_LIMIT_MEMORY_HIGH:
4582 return cc->memory_high;
4583 case CGROUP_LIMIT_TASKS_MAX:
4584 return cgroup_tasks_max_resolve(&cc->tasks_max);
4585 default:
4586 assert_not_reached();
4587 }
4588 }
4589
4590 int unit_get_effective_limit(Unit *u, CGroupLimitType type, uint64_t *ret) {
4591 uint64_t infimum;
4592
4593 assert(u);
4594 assert(ret);
4595 assert(type >= 0);
4596 assert(type < _CGROUP_LIMIT_TYPE_MAX);
4597
4598 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4599 return -EINVAL;
4600
4601 infimum = unit_get_effective_limit_one(u, type);
4602 for (Unit *slice = UNIT_GET_SLICE(u); slice; slice = UNIT_GET_SLICE(slice))
4603 infimum = MIN(infimum, unit_get_effective_limit_one(slice, type));
4604
4605 *ret = infimum;
4606 return 0;
4607 }
4608
4609 static int unit_get_io_accounting_raw(Unit *u, uint64_t ret[static _CGROUP_IO_ACCOUNTING_METRIC_MAX]) {
4610 static const char *const field_names[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
4611 [CGROUP_IO_READ_BYTES] = "rbytes=",
4612 [CGROUP_IO_WRITE_BYTES] = "wbytes=",
4613 [CGROUP_IO_READ_OPERATIONS] = "rios=",
4614 [CGROUP_IO_WRITE_OPERATIONS] = "wios=",
4615 };
4616 uint64_t acc[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {};
4617 _cleanup_free_ char *path = NULL;
4618 _cleanup_fclose_ FILE *f = NULL;
4619 int r;
4620
4621 assert(u);
4622
4623 if (!u->cgroup_path)
4624 return -ENODATA;
4625
4626 if (unit_has_host_root_cgroup(u))
4627 return -ENODATA; /* TODO: return useful data for the top-level cgroup */
4628
4629 r = cg_all_unified();
4630 if (r < 0)
4631 return r;
4632 if (r == 0) /* TODO: support cgroupv1 */
4633 return -ENODATA;
4634
4635 if (!FLAGS_SET(u->cgroup_realized_mask, CGROUP_MASK_IO))
4636 return -ENODATA;
4637
4638 r = cg_get_path("io", u->cgroup_path, "io.stat", &path);
4639 if (r < 0)
4640 return r;
4641
4642 f = fopen(path, "re");
4643 if (!f)
4644 return -errno;
4645
4646 for (;;) {
4647 _cleanup_free_ char *line = NULL;
4648 const char *p;
4649
4650 r = read_line(f, LONG_LINE_MAX, &line);
4651 if (r < 0)
4652 return r;
4653 if (r == 0)
4654 break;
4655
4656 p = line;
4657 p += strcspn(p, WHITESPACE); /* Skip over device major/minor */
4658 p += strspn(p, WHITESPACE); /* Skip over following whitespace */
4659
4660 for (;;) {
4661 _cleanup_free_ char *word = NULL;
4662
4663 r = extract_first_word(&p, &word, NULL, EXTRACT_RETAIN_ESCAPE);
4664 if (r < 0)
4665 return r;
4666 if (r == 0)
4667 break;
4668
4669 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
4670 const char *x;
4671
4672 x = startswith(word, field_names[i]);
4673 if (x) {
4674 uint64_t w;
4675
4676 r = safe_atou64(x, &w);
4677 if (r < 0)
4678 return r;
4679
4680 /* Sum up the stats of all devices */
4681 acc[i] += w;
4682 break;
4683 }
4684 }
4685 }
4686 }
4687
4688 memcpy(ret, acc, sizeof(acc));
4689 return 0;
4690 }
4691
4692 int unit_get_io_accounting(
4693 Unit *u,
4694 CGroupIOAccountingMetric metric,
4695 bool allow_cache,
4696 uint64_t *ret) {
4697
4698 uint64_t raw[_CGROUP_IO_ACCOUNTING_METRIC_MAX];
4699 int r;
4700
4701 /* Retrieve an IO account parameter. This will subtract the counter when the unit was started. */
4702
4703 if (!UNIT_CGROUP_BOOL(u, io_accounting))
4704 return -ENODATA;
4705
4706 if (allow_cache && u->io_accounting_last[metric] != UINT64_MAX)
4707 goto done;
4708
4709 r = unit_get_io_accounting_raw(u, raw);
4710 if (r == -ENODATA && u->io_accounting_last[metric] != UINT64_MAX)
4711 goto done;
4712 if (r < 0)
4713 return r;
4714
4715 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
4716 /* Saturated subtraction */
4717 if (raw[i] > u->io_accounting_base[i])
4718 u->io_accounting_last[i] = raw[i] - u->io_accounting_base[i];
4719 else
4720 u->io_accounting_last[i] = 0;
4721 }
4722
4723 done:
4724 if (ret)
4725 *ret = u->io_accounting_last[metric];
4726
4727 return 0;
4728 }
4729
4730 int unit_reset_cpu_accounting(Unit *u) {
4731 int r;
4732
4733 assert(u);
4734
4735 u->cpu_usage_last = NSEC_INFINITY;
4736
4737 r = unit_get_cpu_usage_raw(u, &u->cpu_usage_base);
4738 if (r < 0) {
4739 u->cpu_usage_base = 0;
4740 return r;
4741 }
4742
4743 return 0;
4744 }
4745
4746 void unit_reset_memory_accounting_last(Unit *u) {
4747 assert(u);
4748
4749 FOREACH_ARRAY(i, u->memory_accounting_last, ELEMENTSOF(u->memory_accounting_last))
4750 *i = UINT64_MAX;
4751 }
4752
4753 int unit_reset_ip_accounting(Unit *u) {
4754 int r = 0;
4755
4756 assert(u);
4757
4758 if (u->ip_accounting_ingress_map_fd >= 0)
4759 RET_GATHER(r, bpf_firewall_reset_accounting(u->ip_accounting_ingress_map_fd));
4760
4761 if (u->ip_accounting_egress_map_fd >= 0)
4762 RET_GATHER(r, bpf_firewall_reset_accounting(u->ip_accounting_egress_map_fd));
4763
4764 zero(u->ip_accounting_extra);
4765
4766 return r;
4767 }
4768
4769 void unit_reset_io_accounting_last(Unit *u) {
4770 assert(u);
4771
4772 FOREACH_ARRAY(i, u->io_accounting_last, _CGROUP_IO_ACCOUNTING_METRIC_MAX)
4773 *i = UINT64_MAX;
4774 }
4775
4776 int unit_reset_io_accounting(Unit *u) {
4777 int r;
4778
4779 assert(u);
4780
4781 unit_reset_io_accounting_last(u);
4782
4783 r = unit_get_io_accounting_raw(u, u->io_accounting_base);
4784 if (r < 0) {
4785 zero(u->io_accounting_base);
4786 return r;
4787 }
4788
4789 return 0;
4790 }
4791
4792 int unit_reset_accounting(Unit *u) {
4793 int r = 0;
4794
4795 assert(u);
4796
4797 RET_GATHER(r, unit_reset_cpu_accounting(u));
4798 RET_GATHER(r, unit_reset_io_accounting(u));
4799 RET_GATHER(r, unit_reset_ip_accounting(u));
4800 unit_reset_memory_accounting_last(u);
4801
4802 return r;
4803 }
4804
4805 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
4806 assert(u);
4807
4808 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4809 return;
4810
4811 if (m == 0)
4812 return;
4813
4814 /* always invalidate compat pairs together */
4815 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
4816 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
4817
4818 if (m & (CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT))
4819 m |= CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT;
4820
4821 if (FLAGS_SET(u->cgroup_invalidated_mask, m)) /* NOP? */
4822 return;
4823
4824 u->cgroup_invalidated_mask |= m;
4825 unit_add_to_cgroup_realize_queue(u);
4826 }
4827
4828 void unit_invalidate_cgroup_bpf(Unit *u) {
4829 assert(u);
4830
4831 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4832 return;
4833
4834 if (u->cgroup_invalidated_mask & CGROUP_MASK_BPF_FIREWALL) /* NOP? */
4835 return;
4836
4837 u->cgroup_invalidated_mask |= CGROUP_MASK_BPF_FIREWALL;
4838 unit_add_to_cgroup_realize_queue(u);
4839
4840 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
4841 * list of our children includes our own. */
4842 if (u->type == UNIT_SLICE) {
4843 Unit *member;
4844
4845 UNIT_FOREACH_DEPENDENCY(member, u, UNIT_ATOM_SLICE_OF)
4846 unit_invalidate_cgroup_bpf(member);
4847 }
4848 }
4849
4850 void unit_cgroup_catchup(Unit *u) {
4851 assert(u);
4852
4853 if (!UNIT_HAS_CGROUP_CONTEXT(u))
4854 return;
4855
4856 /* We dropped the inotify watch during reexec/reload, so we need to
4857 * check these as they may have changed.
4858 * Note that (currently) the kernel doesn't actually update cgroup
4859 * file modification times, so we can't just serialize and then check
4860 * the mtime for file(s) we are interested in. */
4861 (void) unit_check_cgroup_events(u);
4862 unit_add_to_cgroup_oom_queue(u);
4863 }
4864
4865 bool unit_cgroup_delegate(Unit *u) {
4866 CGroupContext *c;
4867
4868 assert(u);
4869
4870 if (!UNIT_VTABLE(u)->can_delegate)
4871 return false;
4872
4873 c = unit_get_cgroup_context(u);
4874 if (!c)
4875 return false;
4876
4877 return c->delegate;
4878 }
4879
4880 void manager_invalidate_startup_units(Manager *m) {
4881 Unit *u;
4882
4883 assert(m);
4884
4885 SET_FOREACH(u, m->startup_units)
4886 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO|CGROUP_MASK_CPUSET);
4887 }
4888
4889 int unit_cgroup_freezer_action(Unit *u, FreezerAction action) {
4890 _cleanup_free_ char *path = NULL;
4891 FreezerState target, kernel = _FREEZER_STATE_INVALID;
4892 int r, ret;
4893
4894 assert(u);
4895 assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
4896
4897 if (!cg_freezer_supported())
4898 return 0;
4899
4900 /* Ignore all requests to thaw init.scope or -.slice and reject all requests to freeze them */
4901 if (unit_has_name(u, SPECIAL_ROOT_SLICE) || unit_has_name(u, SPECIAL_INIT_SCOPE))
4902 return action == FREEZER_FREEZE ? -EPERM : 0;
4903
4904 if (!u->cgroup_realized)
4905 return -EBUSY;
4906
4907 if (action == FREEZER_THAW) {
4908 Unit *slice = UNIT_GET_SLICE(u);
4909
4910 if (slice) {
4911 r = unit_cgroup_freezer_action(slice, FREEZER_THAW);
4912 if (r < 0)
4913 return log_unit_error_errno(u, r, "Failed to thaw slice %s of unit: %m", slice->id);
4914 }
4915 }
4916
4917 target = action == FREEZER_FREEZE ? FREEZER_FROZEN : FREEZER_RUNNING;
4918
4919 r = unit_freezer_state_kernel(u, &kernel);
4920 if (r < 0)
4921 log_unit_debug_errno(u, r, "Failed to obtain cgroup freezer state: %m");
4922
4923 if (target == kernel) {
4924 u->freezer_state = target;
4925 if (action == FREEZER_FREEZE)
4926 return 0;
4927 ret = 0;
4928 } else
4929 ret = 1;
4930
4931 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.freeze", &path);
4932 if (r < 0)
4933 return r;
4934
4935 log_unit_debug(u, "%s unit.", action == FREEZER_FREEZE ? "Freezing" : "Thawing");
4936
4937 if (target != kernel) {
4938 if (action == FREEZER_FREEZE)
4939 u->freezer_state = FREEZER_FREEZING;
4940 else
4941 u->freezer_state = FREEZER_THAWING;
4942 }
4943
4944 r = write_string_file(path, one_zero(action == FREEZER_FREEZE), WRITE_STRING_FILE_DISABLE_BUFFER);
4945 if (r < 0)
4946 return r;
4947
4948 return ret;
4949 }
4950
4951 int unit_get_cpuset(Unit *u, CPUSet *cpus, const char *name) {
4952 _cleanup_free_ char *v = NULL;
4953 int r;
4954
4955 assert(u);
4956 assert(cpus);
4957
4958 if (!u->cgroup_path)
4959 return -ENODATA;
4960
4961 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUSET) == 0)
4962 return -ENODATA;
4963
4964 r = cg_all_unified();
4965 if (r < 0)
4966 return r;
4967 if (r == 0)
4968 return -ENODATA;
4969
4970 r = cg_get_attribute("cpuset", u->cgroup_path, name, &v);
4971 if (r == -ENOENT)
4972 return -ENODATA;
4973 if (r < 0)
4974 return r;
4975
4976 return parse_cpu_set_full(v, cpus, false, NULL, NULL, 0, NULL);
4977 }
4978
4979 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
4980 [CGROUP_DEVICE_POLICY_AUTO] = "auto",
4981 [CGROUP_DEVICE_POLICY_CLOSED] = "closed",
4982 [CGROUP_DEVICE_POLICY_STRICT] = "strict",
4983 };
4984
4985 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);
4986
4987 static const char* const freezer_action_table[_FREEZER_ACTION_MAX] = {
4988 [FREEZER_FREEZE] = "freeze",
4989 [FREEZER_THAW] = "thaw",
4990 };
4991
4992 DEFINE_STRING_TABLE_LOOKUP(freezer_action, FreezerAction);
4993
4994 static const char* const cgroup_pressure_watch_table[_CGROUP_PRESSURE_WATCH_MAX] = {
4995 [CGROUP_PRESSURE_WATCH_OFF] = "off",
4996 [CGROUP_PRESSURE_WATCH_AUTO] = "auto",
4997 [CGROUP_PRESSURE_WATCH_ON] = "on",
4998 [CGROUP_PRESSURE_WATCH_SKIP] = "skip",
4999 };
5000
5001 DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(cgroup_pressure_watch, CGroupPressureWatch, CGROUP_PRESSURE_WATCH_ON);
5002
5003 static const char* const cgroup_ip_accounting_metric_table[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
5004 [CGROUP_IP_INGRESS_BYTES] = "IPIngressBytes",
5005 [CGROUP_IP_EGRESS_BYTES] = "IPEgressBytes",
5006 [CGROUP_IP_INGRESS_PACKETS] = "IPIngressPackets",
5007 [CGROUP_IP_EGRESS_PACKETS] = "IPEgressPackets",
5008 };
5009
5010 DEFINE_STRING_TABLE_LOOKUP(cgroup_ip_accounting_metric, CGroupIPAccountingMetric);
5011
5012 static const char* const cgroup_io_accounting_metric_table[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
5013 [CGROUP_IO_READ_BYTES] = "IOReadBytes",
5014 [CGROUP_IO_WRITE_BYTES] = "IOWriteBytes",
5015 [CGROUP_IO_READ_OPERATIONS] = "IOReadOperations",
5016 [CGROUP_IO_WRITE_OPERATIONS] = "IOWriteOperations",
5017 };
5018
5019 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_accounting_metric, CGroupIOAccountingMetric);
5020
5021 static const char* const cgroup_memory_accounting_metric_table[_CGROUP_MEMORY_ACCOUNTING_METRIC_MAX] = {
5022 [CGROUP_MEMORY_PEAK] = "MemoryPeak",
5023 [CGROUP_MEMORY_SWAP_CURRENT] = "MemorySwapCurrent",
5024 [CGROUP_MEMORY_SWAP_PEAK] = "MemorySwapPeak",
5025 [CGROUP_MEMORY_ZSWAP_CURRENT] = "MemoryZSwapCurrent",
5026 };
5027
5028 DEFINE_STRING_TABLE_LOOKUP(cgroup_memory_accounting_metric, CGroupMemoryAccountingMetric);
5029
5030 static const char *const cgroup_limit_type_table[_CGROUP_LIMIT_TYPE_MAX] = {
5031 [CGROUP_LIMIT_MEMORY_MAX] = "EffectiveMemoryMax",
5032 [CGROUP_LIMIT_MEMORY_HIGH] = "EffectiveMemoryHigh",
5033 [CGROUP_LIMIT_TASKS_MAX] = "EffectiveTasksMax",
5034 };
5035
5036 DEFINE_STRING_TABLE_LOOKUP(cgroup_limit_type, CGroupLimitType);