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