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