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