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