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