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