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