]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/cgroup.c
bpf: optimize device type access away most of the time
[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;
963 int r;
964
965 assert_se(c = unit_get_cgroup_context(u));
966 assert_se(path = u->cgroup_path);
967
968 if (cg_all_unified() > 0) {
969 r = bpf_devices_cgroup_init(&prog, c->device_policy, c->device_allow);
970 if (r < 0)
971 return log_unit_warning_errno(u, r, "Failed to initialize device control bpf program: %m");
972
973 } else {
974 /* Changing the devices list of a populated cgroup might result in EINVAL, hence ignore
975 * EINVAL here. */
976
977 if (c->device_allow || c->device_policy != CGROUP_DEVICE_POLICY_AUTO)
978 r = cg_set_attribute("devices", path, "devices.deny", "a");
979 else
980 r = cg_set_attribute("devices", path, "devices.allow", "a");
981 if (r < 0)
982 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES, -EPERM) ? LOG_DEBUG : LOG_WARNING, r,
983 "Failed to reset devices.allow/devices.deny: %m");
984 }
985
986 if (c->device_policy == CGROUP_DEVICE_POLICY_CLOSED ||
987 (c->device_policy == CGROUP_DEVICE_POLICY_AUTO && c->device_allow))
988 (void) bpf_devices_whitelist_static(prog, path);
989
990 LIST_FOREACH(device_allow, a, c->device_allow) {
991 char acc[4], *val;
992 unsigned k = 0;
993
994 if (a->r)
995 acc[k++] = 'r';
996 if (a->w)
997 acc[k++] = 'w';
998 if (a->m)
999 acc[k++] = 'm';
1000
1001 if (k == 0)
1002 continue;
1003
1004 acc[k++] = 0;
1005
1006 if (path_startswith(a->path, "/dev/"))
1007 (void) bpf_devices_whitelist_device(prog, path, a->path, acc);
1008 else if ((val = startswith(a->path, "block-")))
1009 (void) bpf_devices_whitelist_major(prog, path, val, 'b', acc);
1010 else if ((val = startswith(a->path, "char-")))
1011 (void) bpf_devices_whitelist_major(prog, path, val, 'c', acc);
1012 else
1013 log_unit_debug(u, "Ignoring device '%s' while writing cgroup attribute.", a->path);
1014 }
1015
0848715c 1016 r = bpf_devices_apply_policy(prog, c->device_policy, c->device_allow, path, &u->bpf_device_control_installed);
8b139557
ZJS
1017 if (r < 0) {
1018 static bool warned = false;
1019
1020 log_full_errno(warned ? LOG_DEBUG : LOG_WARNING, r,
1021 "Unit %s configures device ACL, but the local system doesn't seem to support the BPF-based device controller.\n"
1022 "Proceeding WITHOUT applying ACL (all devices will be accessible)!\n"
1023 "(This warning is only shown for the first loaded unit using device ACL.)", u->id);
1024
1025 warned = true;
1026 }
1027 return r;
1028}
1029
906c06f6
DM
1030static void cgroup_context_apply(
1031 Unit *u,
1032 CGroupMask apply_mask,
906c06f6
DM
1033 ManagerState state) {
1034
f29ff115
TH
1035 const char *path;
1036 CGroupContext *c;
52fecf20 1037 bool is_host_root, is_local_root;
4ad49000
LP
1038 int r;
1039
f29ff115
TH
1040 assert(u);
1041
906c06f6 1042 /* Nothing to do? Exit early! */
17f14955 1043 if (apply_mask == 0)
4ad49000 1044 return;
8e274523 1045
52fecf20
LP
1046 /* Some cgroup attributes are not supported on the host root cgroup, hence silently ignore them here. And other
1047 * attributes should only be managed for cgroups further down the tree. */
1048 is_local_root = unit_has_name(u, SPECIAL_ROOT_SLICE);
1049 is_host_root = unit_has_host_root_cgroup(u);
f3725e64
LP
1050
1051 assert_se(c = unit_get_cgroup_context(u));
1052 assert_se(path = u->cgroup_path);
1053
52fecf20 1054 if (is_local_root) /* Make sure we don't try to display messages with an empty path. */
6da13913 1055 path = "/";
01efdf13 1056
be2c0327
LP
1057 /* We generally ignore errors caused by read-only mounted cgroup trees (assuming we are running in a container
1058 * then), and missing cgroups, i.e. EROFS and ENOENT. */
714e2e1d 1059
be2c0327
LP
1060 /* In fully unified mode these attributes don't exist on the host cgroup root. On legacy the weights exist, but
1061 * setting the weight makes very little sense on the host root cgroup, as there are no other cgroups at this
1062 * level. The quota exists there too, but any attempt to write to it is refused with EINVAL. Inside of
4e1dfa45 1063 * containers we want to leave control of these to the container manager (and if cgroup v2 delegation is used
be2c0327
LP
1064 * we couldn't even write to them if we wanted to). */
1065 if ((apply_mask & CGROUP_MASK_CPU) && !is_local_root) {
8e274523 1066
b4cccbc1 1067 if (cg_all_unified() > 0) {
be2c0327 1068 uint64_t weight;
b2f8b02e 1069
be2c0327
LP
1070 if (cgroup_context_has_cpu_weight(c))
1071 weight = cgroup_context_cpu_weight(c, state);
1072 else if (cgroup_context_has_cpu_shares(c)) {
1073 uint64_t shares;
66ebf6c0 1074
be2c0327
LP
1075 shares = cgroup_context_cpu_shares(c, state);
1076 weight = cgroup_cpu_shares_to_weight(shares);
66ebf6c0 1077
be2c0327
LP
1078 log_cgroup_compat(u, "Applying [Startup]CPUShares=%" PRIu64 " as [Startup]CPUWeight=%" PRIu64 " on %s",
1079 shares, weight, path);
1080 } else
1081 weight = CGROUP_WEIGHT_DEFAULT;
66ebf6c0 1082
be2c0327 1083 cgroup_apply_unified_cpu_weight(u, weight);
10f28641 1084 cgroup_apply_unified_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
66ebf6c0 1085
52fecf20 1086 } else {
be2c0327 1087 uint64_t shares;
52fecf20 1088
be2c0327
LP
1089 if (cgroup_context_has_cpu_weight(c)) {
1090 uint64_t weight;
52fecf20 1091
be2c0327
LP
1092 weight = cgroup_context_cpu_weight(c, state);
1093 shares = cgroup_cpu_weight_to_shares(weight);
52fecf20 1094
be2c0327
LP
1095 log_cgroup_compat(u, "Applying [Startup]CPUWeight=%" PRIu64 " as [Startup]CPUShares=%" PRIu64 " on %s",
1096 weight, shares, path);
1097 } else if (cgroup_context_has_cpu_shares(c))
1098 shares = cgroup_context_cpu_shares(c, state);
1099 else
1100 shares = CGROUP_CPU_SHARES_DEFAULT;
66ebf6c0 1101
be2c0327 1102 cgroup_apply_legacy_cpu_shares(u, shares);
10f28641 1103 cgroup_apply_legacy_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
66ebf6c0 1104 }
4ad49000
LP
1105 }
1106
047f5d63 1107 if ((apply_mask & CGROUP_MASK_CPUSET) && !is_local_root) {
2cea199e
ZJS
1108 cgroup_apply_unified_cpuset(u, &c->cpuset_cpus, "cpuset.cpus");
1109 cgroup_apply_unified_cpuset(u, &c->cpuset_mems, "cpuset.mems");
047f5d63
PH
1110 }
1111
4e1dfa45 1112 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroup v2
52fecf20
LP
1113 * controller), and in case of containers we want to leave control of these attributes to the container manager
1114 * (and we couldn't access that stuff anyway, even if we tried if proper delegation is used). */
1115 if ((apply_mask & CGROUP_MASK_IO) && !is_local_root) {
1116 char buf[8+DECIMAL_STR_MAX(uint64_t)+1];
1117 bool has_io, has_blockio;
1118 uint64_t weight;
13c31542 1119
52fecf20
LP
1120 has_io = cgroup_context_has_io_config(c);
1121 has_blockio = cgroup_context_has_blockio_config(c);
13c31542 1122
52fecf20
LP
1123 if (has_io)
1124 weight = cgroup_context_io_weight(c, state);
1125 else if (has_blockio) {
1126 uint64_t blkio_weight;
128fadc9 1127
52fecf20
LP
1128 blkio_weight = cgroup_context_blkio_weight(c, state);
1129 weight = cgroup_weight_blkio_to_io(blkio_weight);
128fadc9 1130
67e2ea15 1131 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight=%" PRIu64 " as [Startup]IOWeight=%" PRIu64,
52fecf20
LP
1132 blkio_weight, weight);
1133 } else
1134 weight = CGROUP_WEIGHT_DEFAULT;
13c31542 1135
52fecf20
LP
1136 xsprintf(buf, "default %" PRIu64 "\n", weight);
1137 (void) set_attribute_and_warn(u, "io", "io.weight", buf);
538b4852 1138
2dbc45ae
KK
1139 /* FIXME: drop this when distro kernels properly support BFQ through "io.weight"
1140 * See also: https://github.com/systemd/systemd/pull/13335 */
1141 xsprintf(buf, "%" PRIu64 "\n", weight);
1142 (void) set_attribute_and_warn(u, "io", "io.bfq.weight", buf);
1143
52fecf20
LP
1144 if (has_io) {
1145 CGroupIODeviceLatency *latency;
1146 CGroupIODeviceLimit *limit;
1147 CGroupIODeviceWeight *w;
128fadc9 1148
52fecf20
LP
1149 LIST_FOREACH(device_weights, w, c->io_device_weights)
1150 cgroup_apply_io_device_weight(u, w->path, w->weight);
128fadc9 1151
52fecf20
LP
1152 LIST_FOREACH(device_limits, limit, c->io_device_limits)
1153 cgroup_apply_io_device_limit(u, limit->path, limit->limits);
6ae4283c 1154
52fecf20
LP
1155 LIST_FOREACH(device_latencies, latency, c->io_device_latencies)
1156 cgroup_apply_io_device_latency(u, latency->path, latency->target_usec);
6ae4283c 1157
52fecf20
LP
1158 } else if (has_blockio) {
1159 CGroupBlockIODeviceWeight *w;
1160 CGroupBlockIODeviceBandwidth *b;
13c31542 1161
52fecf20
LP
1162 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
1163 weight = cgroup_weight_blkio_to_io(w->weight);
17ae2780 1164
67e2ea15 1165 log_cgroup_compat(u, "Applying BlockIODeviceWeight=%" PRIu64 " as IODeviceWeight=%" PRIu64 " for %s",
52fecf20 1166 w->weight, weight, w->path);
538b4852 1167
52fecf20
LP
1168 cgroup_apply_io_device_weight(u, w->path, weight);
1169 }
538b4852 1170
17ae2780 1171 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
538b4852
TH
1172 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
1173 CGroupIOLimitType type;
1174
1175 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
1176 limits[type] = cgroup_io_limit_defaults[type];
1177
1178 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
1179 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
1180
67e2ea15 1181 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax= for %s",
128fadc9
TH
1182 b->rbps, b->wbps, b->path);
1183
17ae2780 1184 cgroup_apply_io_device_limit(u, b->path, limits);
538b4852 1185 }
13c31542
TH
1186 }
1187 }
1188
906c06f6 1189 if (apply_mask & CGROUP_MASK_BLKIO) {
52fecf20 1190 bool has_io, has_blockio;
4ad49000 1191
52fecf20
LP
1192 has_io = cgroup_context_has_io_config(c);
1193 has_blockio = cgroup_context_has_blockio_config(c);
1194
1195 /* Applying a 'weight' never makes sense for the host root cgroup, and for containers this should be
1196 * left to our container manager, too. */
1197 if (!is_local_root) {
64faf04c
TH
1198 char buf[DECIMAL_STR_MAX(uint64_t)+1];
1199 uint64_t weight;
64faf04c 1200
7d862ab8 1201 if (has_io) {
52fecf20 1202 uint64_t io_weight;
128fadc9 1203
52fecf20 1204 io_weight = cgroup_context_io_weight(c, state);
538b4852 1205 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
128fadc9 1206
67e2ea15 1207 log_cgroup_compat(u, "Applying [Startup]IOWeight=%" PRIu64 " as [Startup]BlockIOWeight=%" PRIu64,
128fadc9 1208 io_weight, weight);
7d862ab8
TH
1209 } else if (has_blockio)
1210 weight = cgroup_context_blkio_weight(c, state);
1211 else
538b4852 1212 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
64faf04c
TH
1213
1214 xsprintf(buf, "%" PRIu64 "\n", weight);
293d32df 1215 (void) set_attribute_and_warn(u, "blkio", "blkio.weight", buf);
4ad49000 1216
7d862ab8 1217 if (has_io) {
538b4852
TH
1218 CGroupIODeviceWeight *w;
1219
128fadc9
TH
1220 LIST_FOREACH(device_weights, w, c->io_device_weights) {
1221 weight = cgroup_weight_io_to_blkio(w->weight);
1222
67e2ea15 1223 log_cgroup_compat(u, "Applying IODeviceWeight=%" PRIu64 " as BlockIODeviceWeight=%" PRIu64 " for %s",
128fadc9
TH
1224 w->weight, weight, w->path);
1225
1226 cgroup_apply_blkio_device_weight(u, w->path, weight);
1227 }
7d862ab8
TH
1228 } else if (has_blockio) {
1229 CGroupBlockIODeviceWeight *w;
1230
7d862ab8
TH
1231 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
1232 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
538b4852 1233 }
4ad49000
LP
1234 }
1235
5238e957 1236 /* The bandwidth limits are something that make sense to be applied to the host's root but not container
52fecf20
LP
1237 * roots, as there we want the container manager to handle it */
1238 if (is_host_root || !is_local_root) {
1239 if (has_io) {
1240 CGroupIODeviceLimit *l;
538b4852 1241
52fecf20 1242 LIST_FOREACH(device_limits, l, c->io_device_limits) {
67e2ea15 1243 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax= for %s",
52fecf20 1244 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
128fadc9 1245
52fecf20
LP
1246 cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]);
1247 }
1248 } else if (has_blockio) {
1249 CGroupBlockIODeviceBandwidth *b;
7d862ab8 1250
52fecf20
LP
1251 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
1252 cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps);
1253 }
d686d8a9 1254 }
8e274523
LP
1255 }
1256
be2c0327
LP
1257 /* In unified mode 'memory' attributes do not exist on the root cgroup. In legacy mode 'memory.limit_in_bytes'
1258 * exists on the root cgroup, but any writes to it are refused with EINVAL. And if we run in a container we
4e1dfa45 1259 * want to leave control to the container manager (and if proper cgroup v2 delegation is used we couldn't even
be2c0327
LP
1260 * write to this if we wanted to.) */
1261 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_local_root) {
efdb0237 1262
52fecf20 1263 if (cg_all_unified() > 0) {
be2c0327
LP
1264 uint64_t max, swap_max = CGROUP_LIMIT_MAX;
1265
c52db42b 1266 if (unit_has_unified_memory_config(u)) {
be2c0327
LP
1267 max = c->memory_max;
1268 swap_max = c->memory_swap_max;
1269 } else {
1270 max = c->memory_limit;
efdb0237 1271
be2c0327
LP
1272 if (max != CGROUP_LIMIT_MAX)
1273 log_cgroup_compat(u, "Applying MemoryLimit=%" PRIu64 " as MemoryMax=", max);
128fadc9 1274 }
da4d897e 1275
64fe532e 1276 cgroup_apply_unified_memory_limit(u, "memory.min", unit_get_ancestor_memory_min(u));
c52db42b 1277 cgroup_apply_unified_memory_limit(u, "memory.low", unit_get_ancestor_memory_low(u));
be2c0327
LP
1278 cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
1279 cgroup_apply_unified_memory_limit(u, "memory.max", max);
1280 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
128fadc9 1281
afcfaa69
LP
1282 (void) set_attribute_and_warn(u, "memory", "memory.oom.group", one_zero(c->memory_oom_group));
1283
be2c0327
LP
1284 } else {
1285 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
1286 uint64_t val;
52fecf20 1287
c52db42b 1288 if (unit_has_unified_memory_config(u)) {
be2c0327
LP
1289 val = c->memory_max;
1290 log_cgroup_compat(u, "Applying MemoryMax=%" PRIi64 " as MemoryLimit=", val);
1291 } else
1292 val = c->memory_limit;
78a4ee59 1293
be2c0327
LP
1294 if (val == CGROUP_LIMIT_MAX)
1295 strncpy(buf, "-1\n", sizeof(buf));
1296 else
1297 xsprintf(buf, "%" PRIu64 "\n", val);
1298
1299 (void) set_attribute_and_warn(u, "memory", "memory.limit_in_bytes", buf);
da4d897e 1300 }
4ad49000 1301 }
8e274523 1302
4e1dfa45 1303 /* On cgroup v2 we can apply BPF everywhere. On cgroup v1 we apply it everywhere except for the root of
52fecf20
LP
1304 * containers, where we leave this to the manager */
1305 if ((apply_mask & (CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES)) &&
8b139557
ZJS
1306 (is_host_root || cg_all_unified() > 0 || !is_local_root))
1307 (void) cgroup_apply_devices(u);
03a7b521 1308
00b5974f
LP
1309 if (apply_mask & CGROUP_MASK_PIDS) {
1310
52fecf20 1311 if (is_host_root) {
00b5974f
LP
1312 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1313 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1314 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1315 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1316 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1317 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1318 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1319 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1320 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1321 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
5238e957 1322 * which is desirable so that there's an official way to release control of the sysctl from
00b5974f
LP
1323 * systemd: set the limit to unbounded and reload. */
1324
1325 if (c->tasks_max != CGROUP_LIMIT_MAX) {
1326 u->manager->sysctl_pid_max_changed = true;
1327 r = procfs_tasks_set_limit(c->tasks_max);
1328 } else if (u->manager->sysctl_pid_max_changed)
1329 r = procfs_tasks_set_limit(TASKS_MAX);
1330 else
1331 r = 0;
00b5974f 1332 if (r < 0)
39b9fefb 1333 log_unit_full(u, LOG_LEVEL_CGROUP_WRITE(r), r,
00b5974f 1334 "Failed to write to tasks limit sysctls: %m");
52fecf20 1335 }
03a7b521 1336
52fecf20
LP
1337 /* The attribute itself is not available on the host root cgroup, and in the container case we want to
1338 * leave it for the container manager. */
1339 if (!is_local_root) {
00b5974f
LP
1340 if (c->tasks_max != CGROUP_LIMIT_MAX) {
1341 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
03a7b521 1342
00b5974f 1343 sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
293d32df 1344 (void) set_attribute_and_warn(u, "pids", "pids.max", buf);
00b5974f 1345 } else
589a5f7a 1346 (void) set_attribute_and_warn(u, "pids", "pids.max", "max\n");
00b5974f 1347 }
03a7b521 1348 }
906c06f6 1349
17f14955 1350 if (apply_mask & CGROUP_MASK_BPF_FIREWALL)
0f2d84d2 1351 cgroup_apply_firewall(u);
fb385181
LP
1352}
1353
16492445
LP
1354static bool unit_get_needs_bpf_firewall(Unit *u) {
1355 CGroupContext *c;
1356 Unit *p;
1357 assert(u);
1358
1359 c = unit_get_cgroup_context(u);
1360 if (!c)
1361 return false;
1362
1363 if (c->ip_accounting ||
1364 c->ip_address_allow ||
fab34748
KL
1365 c->ip_address_deny ||
1366 c->ip_filters_ingress ||
1367 c->ip_filters_egress)
16492445
LP
1368 return true;
1369
1370 /* If any parent slice has an IP access list defined, it applies too */
1371 for (p = UNIT_DEREF(u->slice); p; p = UNIT_DEREF(p->slice)) {
1372 c = unit_get_cgroup_context(p);
1373 if (!c)
1374 return false;
1375
1376 if (c->ip_address_allow ||
1377 c->ip_address_deny)
1378 return true;
1379 }
1380
1381 return false;
1382}
1383
c52db42b 1384static CGroupMask unit_get_cgroup_mask(Unit *u) {
efdb0237 1385 CGroupMask mask = 0;
c52db42b
CD
1386 CGroupContext *c;
1387
1388 assert(u);
1389
1390 c = unit_get_cgroup_context(u);
8e274523 1391
c710d3b4
CD
1392 assert(c);
1393
fae9bc29 1394 /* Figure out which controllers we need, based on the cgroup context object */
8e274523 1395
fae9bc29 1396 if (c->cpu_accounting)
f98c2585 1397 mask |= get_cpu_accounting_mask();
fae9bc29
LP
1398
1399 if (cgroup_context_has_cpu_weight(c) ||
66ebf6c0 1400 cgroup_context_has_cpu_shares(c) ||
3a43da28 1401 c->cpu_quota_per_sec_usec != USEC_INFINITY)
fae9bc29 1402 mask |= CGROUP_MASK_CPU;
ecedd90f 1403
047f5d63
PH
1404 if (c->cpuset_cpus.set || c->cpuset_mems.set)
1405 mask |= CGROUP_MASK_CPUSET;
1406
538b4852
TH
1407 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
1408 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
ecedd90f 1409
4ad49000 1410 if (c->memory_accounting ||
da4d897e 1411 c->memory_limit != CGROUP_LIMIT_MAX ||
c52db42b 1412 unit_has_unified_memory_config(u))
efdb0237 1413 mask |= CGROUP_MASK_MEMORY;
8e274523 1414
a931ad47 1415 if (c->device_allow ||
084870f9 1416 c->device_policy != CGROUP_DEVICE_POLICY_AUTO)
084c7007 1417 mask |= CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES;
4ad49000 1418
03a7b521 1419 if (c->tasks_accounting ||
8793fa25 1420 c->tasks_max != CGROUP_LIMIT_MAX)
03a7b521
LP
1421 mask |= CGROUP_MASK_PIDS;
1422
fae9bc29 1423 return CGROUP_MASK_EXTEND_JOINED(mask);
8e274523
LP
1424}
1425
53aea74a 1426static CGroupMask unit_get_bpf_mask(Unit *u) {
17f14955
RG
1427 CGroupMask mask = 0;
1428
fae9bc29
LP
1429 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
1430 * too. */
1431
17f14955
RG
1432 if (unit_get_needs_bpf_firewall(u))
1433 mask |= CGROUP_MASK_BPF_FIREWALL;
1434
1435 return mask;
1436}
1437
efdb0237 1438CGroupMask unit_get_own_mask(Unit *u) {
4ad49000 1439 CGroupContext *c;
8e274523 1440
442ce775
LP
1441 /* Returns the mask of controllers the unit needs for itself. If a unit is not properly loaded, return an empty
1442 * mask, as we shouldn't reflect it in the cgroup hierarchy then. */
1443
1444 if (u->load_state != UNIT_LOADED)
1445 return 0;
efdb0237 1446
4ad49000
LP
1447 c = unit_get_cgroup_context(u);
1448 if (!c)
1449 return 0;
8e274523 1450
c52db42b 1451 return (unit_get_cgroup_mask(u) | unit_get_bpf_mask(u) | unit_get_delegate_mask(u)) & ~unit_get_ancestor_disable_mask(u);
02638280
LP
1452}
1453
1454CGroupMask unit_get_delegate_mask(Unit *u) {
1455 CGroupContext *c;
1456
1457 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1458 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
19af675e 1459 *
02638280 1460 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
a931ad47 1461
1d9cc876 1462 if (!unit_cgroup_delegate(u))
02638280
LP
1463 return 0;
1464
1465 if (cg_all_unified() <= 0) {
a931ad47
LP
1466 ExecContext *e;
1467
1468 e = unit_get_exec_context(u);
02638280
LP
1469 if (e && !exec_context_maintains_privileges(e))
1470 return 0;
a931ad47
LP
1471 }
1472
1d9cc876 1473 assert_se(c = unit_get_cgroup_context(u));
fae9bc29 1474 return CGROUP_MASK_EXTEND_JOINED(c->delegate_controllers);
8e274523
LP
1475}
1476
efdb0237 1477CGroupMask unit_get_members_mask(Unit *u) {
4ad49000 1478 assert(u);
bc432dc7 1479
02638280 1480 /* Returns the mask of controllers all of the unit's children require, merged */
efdb0237 1481
bc432dc7 1482 if (u->cgroup_members_mask_valid)
26a17ca2 1483 return u->cgroup_members_mask; /* Use cached value if possible */
bc432dc7 1484
64e844e5 1485 u->cgroup_members_mask = 0;
bc432dc7
LP
1486
1487 if (u->type == UNIT_SLICE) {
eef85c4a 1488 void *v;
bc432dc7
LP
1489 Unit *member;
1490 Iterator i;
1491
eef85c4a 1492 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE], i) {
cb5e3bc3
CD
1493 if (UNIT_DEREF(member->slice) == u)
1494 u->cgroup_members_mask |= unit_get_subtree_mask(member); /* note that this calls ourselves again, for the children */
bc432dc7
LP
1495 }
1496 }
1497
1498 u->cgroup_members_mask_valid = true;
6414b7c9 1499 return u->cgroup_members_mask;
246aa6dd
LP
1500}
1501
efdb0237 1502CGroupMask unit_get_siblings_mask(Unit *u) {
4ad49000 1503 assert(u);
246aa6dd 1504
efdb0237
LP
1505 /* Returns the mask of controllers all of the unit's siblings
1506 * require, i.e. the members mask of the unit's parent slice
1507 * if there is one. */
1508
bc432dc7 1509 if (UNIT_ISSET(u->slice))
637f421e 1510 return unit_get_members_mask(UNIT_DEREF(u->slice));
4ad49000 1511
64e844e5 1512 return unit_get_subtree_mask(u); /* we are the top-level slice */
246aa6dd
LP
1513}
1514
4f6f62e4
CD
1515CGroupMask unit_get_disable_mask(Unit *u) {
1516 CGroupContext *c;
1517
1518 c = unit_get_cgroup_context(u);
1519 if (!c)
1520 return 0;
1521
1522 return c->disable_controllers;
1523}
1524
1525CGroupMask unit_get_ancestor_disable_mask(Unit *u) {
1526 CGroupMask mask;
1527
1528 assert(u);
1529 mask = unit_get_disable_mask(u);
1530
1531 /* Returns the mask of controllers which are marked as forcibly
1532 * disabled in any ancestor unit or the unit in question. */
1533
1534 if (UNIT_ISSET(u->slice))
1535 mask |= unit_get_ancestor_disable_mask(UNIT_DEREF(u->slice));
1536
1537 return mask;
1538}
1539
efdb0237
LP
1540CGroupMask unit_get_subtree_mask(Unit *u) {
1541
1542 /* Returns the mask of this subtree, meaning of the group
1543 * itself and its children. */
1544
1545 return unit_get_own_mask(u) | unit_get_members_mask(u);
1546}
1547
1548CGroupMask unit_get_target_mask(Unit *u) {
1549 CGroupMask mask;
1550
1551 /* This returns the cgroup mask of all controllers to enable
1552 * for a specific cgroup, i.e. everything it needs itself,
1553 * plus all that its children need, plus all that its siblings
1554 * need. This is primarily useful on the legacy cgroup
1555 * hierarchy, where we need to duplicate each cgroup in each
1556 * hierarchy that shall be enabled for it. */
6414b7c9 1557
efdb0237 1558 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
84d2744b
ZJS
1559
1560 if (mask & CGROUP_MASK_BPF_FIREWALL & ~u->manager->cgroup_supported)
1561 emit_bpf_firewall_warning(u);
1562
efdb0237 1563 mask &= u->manager->cgroup_supported;
c72703e2 1564 mask &= ~unit_get_ancestor_disable_mask(u);
efdb0237
LP
1565
1566 return mask;
1567}
1568
1569CGroupMask unit_get_enable_mask(Unit *u) {
1570 CGroupMask mask;
1571
1572 /* This returns the cgroup mask of all controllers to enable
1573 * for the children of a specific cgroup. This is primarily
1574 * useful for the unified cgroup hierarchy, where each cgroup
1575 * controls which controllers are enabled for its children. */
1576
1577 mask = unit_get_members_mask(u);
6414b7c9 1578 mask &= u->manager->cgroup_supported;
c72703e2 1579 mask &= ~unit_get_ancestor_disable_mask(u);
6414b7c9
DS
1580
1581 return mask;
1582}
1583
5af88058 1584void unit_invalidate_cgroup_members_masks(Unit *u) {
bc432dc7
LP
1585 assert(u);
1586
5af88058
LP
1587 /* Recurse invalidate the member masks cache all the way up the tree */
1588 u->cgroup_members_mask_valid = false;
bc432dc7 1589
5af88058
LP
1590 if (UNIT_ISSET(u->slice))
1591 unit_invalidate_cgroup_members_masks(UNIT_DEREF(u->slice));
6414b7c9
DS
1592}
1593
6592b975 1594const char *unit_get_realized_cgroup_path(Unit *u, CGroupMask mask) {
03b90d4b 1595
6592b975 1596 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
03b90d4b
LP
1597
1598 while (u) {
6592b975 1599
03b90d4b
LP
1600 if (u->cgroup_path &&
1601 u->cgroup_realized &&
d94a24ca 1602 FLAGS_SET(u->cgroup_realized_mask, mask))
03b90d4b
LP
1603 return u->cgroup_path;
1604
1605 u = UNIT_DEREF(u->slice);
1606 }
1607
1608 return NULL;
1609}
1610
6592b975
LP
1611static const char *migrate_callback(CGroupMask mask, void *userdata) {
1612 return unit_get_realized_cgroup_path(userdata, mask);
1613}
1614
303ee601 1615char *unit_default_cgroup_path(const Unit *u) {
efdb0237
LP
1616 _cleanup_free_ char *escaped = NULL, *slice = NULL;
1617 int r;
1618
1619 assert(u);
1620
1621 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1622 return strdup(u->manager->cgroup_root);
1623
1624 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1625 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1626 if (r < 0)
1627 return NULL;
1628 }
1629
1630 escaped = cg_escape(u->id);
1631 if (!escaped)
1632 return NULL;
1633
657ee2d8 1634 return path_join(empty_to_root(u->manager->cgroup_root), slice, escaped);
efdb0237
LP
1635}
1636
1637int unit_set_cgroup_path(Unit *u, const char *path) {
1638 _cleanup_free_ char *p = NULL;
1639 int r;
1640
1641 assert(u);
1642
5210387e
LP
1643 if (streq_ptr(u->cgroup_path, path))
1644 return 0;
1645
efdb0237
LP
1646 if (path) {
1647 p = strdup(path);
1648 if (!p)
1649 return -ENOMEM;
5210387e 1650 }
efdb0237
LP
1651
1652 if (p) {
1653 r = hashmap_put(u->manager->cgroup_unit, p, u);
1654 if (r < 0)
1655 return r;
1656 }
1657
1658 unit_release_cgroup(u);
ae2a15bc 1659 u->cgroup_path = TAKE_PTR(p);
efdb0237
LP
1660
1661 return 1;
1662}
1663
1664int unit_watch_cgroup(Unit *u) {
ab2c3861 1665 _cleanup_free_ char *events = NULL;
efdb0237
LP
1666 int r;
1667
1668 assert(u);
1669
0bb814c2
LP
1670 /* Watches the "cgroups.events" attribute of this unit's cgroup for "empty" events, but only if
1671 * cgroupv2 is available. */
1672
efdb0237
LP
1673 if (!u->cgroup_path)
1674 return 0;
1675
0bb814c2 1676 if (u->cgroup_control_inotify_wd >= 0)
efdb0237
LP
1677 return 0;
1678
1679 /* Only applies to the unified hierarchy */
c22800e4 1680 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
b4cccbc1
LP
1681 if (r < 0)
1682 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1683 if (r == 0)
efdb0237
LP
1684 return 0;
1685
0bb814c2 1686 /* No point in watch the top-level slice, it's never going to run empty. */
efdb0237
LP
1687 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1688 return 0;
1689
0bb814c2 1690 r = hashmap_ensure_allocated(&u->manager->cgroup_control_inotify_wd_unit, &trivial_hash_ops);
efdb0237
LP
1691 if (r < 0)
1692 return log_oom();
1693
ab2c3861 1694 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
efdb0237
LP
1695 if (r < 0)
1696 return log_oom();
1697
0bb814c2
LP
1698 u->cgroup_control_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1699 if (u->cgroup_control_inotify_wd < 0) {
efdb0237 1700
0bb814c2
LP
1701 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
1702 * is not an error */
efdb0237
LP
1703 return 0;
1704
0bb814c2 1705 return log_unit_error_errno(u, errno, "Failed to add control inotify watch descriptor for control group %s: %m", u->cgroup_path);
efdb0237
LP
1706 }
1707
0bb814c2 1708 r = hashmap_put(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd), u);
efdb0237 1709 if (r < 0)
0bb814c2 1710 return log_unit_error_errno(u, r, "Failed to add control inotify watch descriptor to hash map: %m");
efdb0237
LP
1711
1712 return 0;
1713}
1714
afcfaa69
LP
1715int unit_watch_cgroup_memory(Unit *u) {
1716 _cleanup_free_ char *events = NULL;
1717 CGroupContext *c;
1718 int r;
1719
1720 assert(u);
1721
1722 /* Watches the "memory.events" attribute of this unit's cgroup for "oom_kill" events, but only if
1723 * cgroupv2 is available. */
1724
1725 if (!u->cgroup_path)
1726 return 0;
1727
1728 c = unit_get_cgroup_context(u);
1729 if (!c)
1730 return 0;
1731
1732 /* The "memory.events" attribute is only available if the memory controller is on. Let's hence tie
1733 * this to memory accounting, in a way watching for OOM kills is a form of memory accounting after
1734 * all. */
1735 if (!c->memory_accounting)
1736 return 0;
1737
1738 /* Don't watch inner nodes, as the kernel doesn't report oom_kill events recursively currently, and
1739 * we also don't want to generate a log message for each parent cgroup of a process. */
1740 if (u->type == UNIT_SLICE)
1741 return 0;
1742
1743 if (u->cgroup_memory_inotify_wd >= 0)
1744 return 0;
1745
1746 /* Only applies to the unified hierarchy */
1747 r = cg_all_unified();
1748 if (r < 0)
1749 return log_error_errno(r, "Failed to determine whether the memory controller is unified: %m");
1750 if (r == 0)
1751 return 0;
1752
1753 r = hashmap_ensure_allocated(&u->manager->cgroup_memory_inotify_wd_unit, &trivial_hash_ops);
1754 if (r < 0)
1755 return log_oom();
1756
1757 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "memory.events", &events);
1758 if (r < 0)
1759 return log_oom();
1760
1761 u->cgroup_memory_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1762 if (u->cgroup_memory_inotify_wd < 0) {
1763
1764 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
1765 * is not an error */
1766 return 0;
1767
1768 return log_unit_error_errno(u, errno, "Failed to add memory inotify watch descriptor for control group %s: %m", u->cgroup_path);
1769 }
1770
1771 r = hashmap_put(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd), u);
1772 if (r < 0)
1773 return log_unit_error_errno(u, r, "Failed to add memory inotify watch descriptor to hash map: %m");
1774
1775 return 0;
1776}
1777
a4634b21
LP
1778int unit_pick_cgroup_path(Unit *u) {
1779 _cleanup_free_ char *path = NULL;
1780 int r;
1781
1782 assert(u);
1783
1784 if (u->cgroup_path)
1785 return 0;
1786
1787 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1788 return -EINVAL;
1789
1790 path = unit_default_cgroup_path(u);
1791 if (!path)
1792 return log_oom();
1793
1794 r = unit_set_cgroup_path(u, path);
1795 if (r == -EEXIST)
1796 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1797 if (r < 0)
1798 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1799
1800 return 0;
1801}
1802
efdb0237
LP
1803static int unit_create_cgroup(
1804 Unit *u,
1805 CGroupMask target_mask,
0d2d6fbf
CD
1806 CGroupMask enable_mask,
1807 ManagerState state) {
efdb0237 1808
65be7e06 1809 bool created;
27adcc97 1810 int r;
64747e2d 1811
4ad49000 1812 assert(u);
64747e2d 1813
27c4ed79 1814 if (!UNIT_HAS_CGROUP_CONTEXT(u))
0cd385d3
LP
1815 return 0;
1816
a4634b21
LP
1817 /* Figure out our cgroup path */
1818 r = unit_pick_cgroup_path(u);
1819 if (r < 0)
1820 return r;
b58b8e11 1821
03b90d4b 1822 /* First, create our own group */
efdb0237 1823 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
23bbb0de 1824 if (r < 0)
efdb0237 1825 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
490c5a37 1826 created = r;
efdb0237
LP
1827
1828 /* Start watching it */
1829 (void) unit_watch_cgroup(u);
afcfaa69 1830 (void) unit_watch_cgroup_memory(u);
efdb0237 1831
65be7e06 1832 /* Preserve enabled controllers in delegated units, adjust others. */
1fd3a10c 1833 if (created || !u->cgroup_realized || !unit_cgroup_delegate(u)) {
27adcc97 1834 CGroupMask result_mask = 0;
65be7e06
ZJS
1835
1836 /* Enable all controllers we need */
27adcc97 1837 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path, &result_mask);
65be7e06 1838 if (r < 0)
27adcc97
LP
1839 log_unit_warning_errno(u, r, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
1840
1841 /* If we just turned off a controller, this might release the controller for our parent too, let's
1842 * enqueue the parent for re-realization in that case again. */
1843 if (UNIT_ISSET(u->slice)) {
1844 CGroupMask turned_off;
1845
1846 turned_off = (u->cgroup_realized ? u->cgroup_enabled_mask & ~result_mask : 0);
1847 if (turned_off != 0) {
1848 Unit *parent;
1849
1850 /* Force the parent to propagate the enable mask to the kernel again, by invalidating
1851 * the controller we just turned off. */
1852
1853 for (parent = UNIT_DEREF(u->slice); parent; parent = UNIT_DEREF(parent->slice))
1854 unit_invalidate_cgroup(parent, turned_off);
1855 }
1856 }
1857
1858 /* Remember what's actually enabled now */
1859 u->cgroup_enabled_mask = result_mask;
65be7e06 1860 }
03b90d4b
LP
1861
1862 /* Keep track that this is now realized */
4ad49000 1863 u->cgroup_realized = true;
efdb0237 1864 u->cgroup_realized_mask = target_mask;
4ad49000 1865
1d9cc876 1866 if (u->type != UNIT_SLICE && !unit_cgroup_delegate(u)) {
0cd385d3
LP
1867
1868 /* Then, possibly move things over, but not if
1869 * subgroups may contain processes, which is the case
1870 * for slice and delegation units. */
1871 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1872 if (r < 0)
efdb0237 1873 log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
0cd385d3 1874 }
03b90d4b 1875
0d2d6fbf
CD
1876 /* Set attributes */
1877 cgroup_context_apply(u, target_mask, state);
1878 cgroup_xattr_apply(u);
1879
64747e2d
LP
1880 return 0;
1881}
1882
6592b975
LP
1883static int unit_attach_pid_to_cgroup_via_bus(Unit *u, pid_t pid, const char *suffix_path) {
1884 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1885 char *pp;
7b3fd631 1886 int r;
6592b975 1887
7b3fd631
LP
1888 assert(u);
1889
6592b975
LP
1890 if (MANAGER_IS_SYSTEM(u->manager))
1891 return -EINVAL;
1892
1893 if (!u->manager->system_bus)
1894 return -EIO;
1895
1896 if (!u->cgroup_path)
1897 return -EINVAL;
1898
1899 /* Determine this unit's cgroup path relative to our cgroup root */
1900 pp = path_startswith(u->cgroup_path, u->manager->cgroup_root);
1901 if (!pp)
1902 return -EINVAL;
1903
1904 pp = strjoina("/", pp, suffix_path);
858d36c1 1905 path_simplify(pp, false);
6592b975
LP
1906
1907 r = sd_bus_call_method(u->manager->system_bus,
1908 "org.freedesktop.systemd1",
1909 "/org/freedesktop/systemd1",
1910 "org.freedesktop.systemd1.Manager",
1911 "AttachProcessesToUnit",
1912 &error, NULL,
1913 "ssau",
1914 NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
7b3fd631 1915 if (r < 0)
6592b975
LP
1916 return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
1917
1918 return 0;
1919}
1920
1921int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
1922 CGroupMask delegated_mask;
1923 const char *p;
1924 Iterator i;
1925 void *pidp;
1926 int r, q;
1927
1928 assert(u);
1929
1930 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1931 return -EINVAL;
1932
1933 if (set_isempty(pids))
1934 return 0;
7b3fd631 1935
fab34748
KL
1936 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
1937 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
1938 r = bpf_firewall_load_custom(u);
1939 if (r < 0)
1940 return r;
1941
6592b975 1942 r = unit_realize_cgroup(u);
7b3fd631
LP
1943 if (r < 0)
1944 return r;
1945
6592b975
LP
1946 if (isempty(suffix_path))
1947 p = u->cgroup_path;
1948 else
270384b2 1949 p = prefix_roota(u->cgroup_path, suffix_path);
6592b975
LP
1950
1951 delegated_mask = unit_get_delegate_mask(u);
1952
1953 r = 0;
1954 SET_FOREACH(pidp, pids, i) {
1955 pid_t pid = PTR_TO_PID(pidp);
1956 CGroupController c;
1957
1958 /* First, attach the PID to the main cgroup hierarchy */
1959 q = cg_attach(SYSTEMD_CGROUP_CONTROLLER, p, pid);
1960 if (q < 0) {
1961 log_unit_debug_errno(u, q, "Couldn't move process " PID_FMT " to requested cgroup '%s': %m", pid, p);
1962
1963 if (MANAGER_IS_USER(u->manager) && IN_SET(q, -EPERM, -EACCES)) {
1964 int z;
1965
1966 /* If we are in a user instance, and we can't move the process ourselves due to
1967 * permission problems, let's ask the system instance about it instead. Since it's more
1968 * privileged it might be able to move the process across the leaves of a subtree who's
1969 * top node is not owned by us. */
1970
1971 z = unit_attach_pid_to_cgroup_via_bus(u, pid, suffix_path);
1972 if (z < 0)
1973 log_unit_debug_errno(u, z, "Couldn't move process " PID_FMT " to requested cgroup '%s' via the system bus either: %m", pid, p);
1974 else
1975 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1976 }
1977
1978 if (r >= 0)
1979 r = q; /* Remember first error */
1980
1981 continue;
1982 }
1983
1984 q = cg_all_unified();
1985 if (q < 0)
1986 return q;
1987 if (q > 0)
1988 continue;
1989
1990 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
1991 * innermost realized one */
1992
1993 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1994 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1995 const char *realized;
1996
1997 if (!(u->manager->cgroup_supported & bit))
1998 continue;
1999
2000 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
2001 if (delegated_mask & u->cgroup_realized_mask & bit) {
2002 q = cg_attach(cgroup_controller_to_string(c), p, pid);
2003 if (q >= 0)
2004 continue; /* Success! */
2005
2006 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",
2007 pid, p, cgroup_controller_to_string(c));
2008 }
2009
2010 /* So this controller is either not delegate or realized, or something else weird happened. In
2011 * that case let's attach the PID at least to the closest cgroup up the tree that is
2012 * realized. */
2013 realized = unit_get_realized_cgroup_path(u, bit);
2014 if (!realized)
2015 continue; /* Not even realized in the root slice? Then let's not bother */
2016
2017 q = cg_attach(cgroup_controller_to_string(c), realized, pid);
2018 if (q < 0)
2019 log_unit_debug_errno(u, q, "Failed to attach PID " PID_FMT " to realized cgroup %s in controller %s, ignoring: %m",
2020 pid, realized, cgroup_controller_to_string(c));
2021 }
2022 }
2023
2024 return r;
7b3fd631
LP
2025}
2026
906c06f6
DM
2027static bool unit_has_mask_realized(
2028 Unit *u,
2029 CGroupMask target_mask,
17f14955 2030 CGroupMask enable_mask) {
906c06f6 2031
bc432dc7
LP
2032 assert(u);
2033
d5095dcd
LP
2034 /* Returns true if this unit is fully realized. We check four things:
2035 *
2036 * 1. Whether the cgroup was created at all
4e1dfa45
CD
2037 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
2038 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
d5095dcd
LP
2039 * 4. Whether the invalidation mask is currently zero
2040 *
2041 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
4e1dfa45
CD
2042 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
2043 * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
2044 * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
d5095dcd
LP
2045 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
2046 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
2047 * simply don't matter. */
2048
906c06f6 2049 return u->cgroup_realized &&
d5095dcd
LP
2050 ((u->cgroup_realized_mask ^ target_mask) & CGROUP_MASK_V1) == 0 &&
2051 ((u->cgroup_enabled_mask ^ enable_mask) & CGROUP_MASK_V2) == 0 &&
17f14955 2052 u->cgroup_invalidated_mask == 0;
6414b7c9
DS
2053}
2054
4f6f62e4
CD
2055static bool unit_has_mask_disables_realized(
2056 Unit *u,
2057 CGroupMask target_mask,
2058 CGroupMask enable_mask) {
2059
2060 assert(u);
2061
2062 /* Returns true if all controllers which should be disabled are indeed disabled.
2063 *
2064 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
2065 * already removed. */
2066
2067 return !u->cgroup_realized ||
2068 (FLAGS_SET(u->cgroup_realized_mask, target_mask & CGROUP_MASK_V1) &&
2069 FLAGS_SET(u->cgroup_enabled_mask, enable_mask & CGROUP_MASK_V2));
2070}
2071
a57669d2
CD
2072static bool unit_has_mask_enables_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 enabled are indeed enabled.
2080 *
2081 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
2082 * we want to add is already added. */
2083
2084 return u->cgroup_realized &&
c72703e2
CD
2085 ((u->cgroup_realized_mask | target_mask) & CGROUP_MASK_V1) == (u->cgroup_realized_mask & CGROUP_MASK_V1) &&
2086 ((u->cgroup_enabled_mask | enable_mask) & CGROUP_MASK_V2) == (u->cgroup_enabled_mask & CGROUP_MASK_V2);
a57669d2
CD
2087}
2088
27adcc97 2089void unit_add_to_cgroup_realize_queue(Unit *u) {
2aa57a65
LP
2090 assert(u);
2091
2092 if (u->in_cgroup_realize_queue)
2093 return;
2094
2095 LIST_PREPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2096 u->in_cgroup_realize_queue = true;
2097}
2098
2099static void unit_remove_from_cgroup_realize_queue(Unit *u) {
2100 assert(u);
2101
2102 if (!u->in_cgroup_realize_queue)
2103 return;
2104
2105 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2106 u->in_cgroup_realize_queue = false;
2107}
2108
a57669d2
CD
2109/* Controllers can only be enabled breadth-first, from the root of the
2110 * hierarchy downwards to the unit in question. */
2111static int unit_realize_cgroup_now_enable(Unit *u, ManagerState state) {
2112 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2113 int r;
2114
2115 assert(u);
2116
2117 /* First go deal with this unit's parent, or we won't be able to enable
2118 * any new controllers at this layer. */
2119 if (UNIT_ISSET(u->slice)) {
2120 r = unit_realize_cgroup_now_enable(UNIT_DEREF(u->slice), state);
2121 if (r < 0)
2122 return r;
2123 }
2124
2125 target_mask = unit_get_target_mask(u);
2126 enable_mask = unit_get_enable_mask(u);
2127
2128 /* We can only enable in this direction, don't try to disable anything.
2129 */
2130 if (unit_has_mask_enables_realized(u, target_mask, enable_mask))
2131 return 0;
2132
2133 new_target_mask = u->cgroup_realized_mask | target_mask;
2134 new_enable_mask = u->cgroup_enabled_mask | enable_mask;
2135
c72703e2 2136 return unit_create_cgroup(u, new_target_mask, new_enable_mask, state);
a57669d2
CD
2137}
2138
4f6f62e4
CD
2139/* Controllers can only be disabled depth-first, from the leaves of the
2140 * hierarchy upwards to the unit in question. */
2141static int unit_realize_cgroup_now_disable(Unit *u, ManagerState state) {
2142 Iterator i;
2143 Unit *m;
2144 void *v;
2145
2146 assert(u);
2147
2148 if (u->type != UNIT_SLICE)
2149 return 0;
2150
2151 HASHMAP_FOREACH_KEY(v, m, u->dependencies[UNIT_BEFORE], i) {
2152 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2153 int r;
2154
2155 if (UNIT_DEREF(m->slice) != u)
2156 continue;
2157
2158 /* The cgroup for this unit might not actually be fully
2159 * realised yet, in which case it isn't holding any controllers
2160 * open anyway. */
2161 if (!m->cgroup_path)
2162 continue;
2163
2164 /* We must disable those below us first in order to release the
2165 * controller. */
2166 if (m->type == UNIT_SLICE)
2167 (void) unit_realize_cgroup_now_disable(m, state);
2168
2169 target_mask = unit_get_target_mask(m);
2170 enable_mask = unit_get_enable_mask(m);
2171
2172 /* We can only disable in this direction, don't try to enable
2173 * anything. */
2174 if (unit_has_mask_disables_realized(m, target_mask, enable_mask))
2175 continue;
2176
2177 new_target_mask = m->cgroup_realized_mask & target_mask;
2178 new_enable_mask = m->cgroup_enabled_mask & enable_mask;
2179
2180 r = unit_create_cgroup(m, new_target_mask, new_enable_mask, state);
2181 if (r < 0)
2182 return r;
2183 }
2184
2185 return 0;
2186}
a57669d2 2187
6414b7c9
DS
2188/* Check if necessary controllers and attributes for a unit are in place.
2189 *
a57669d2
CD
2190 * - If so, do nothing.
2191 * - If not, create paths, move processes over, and set attributes.
2192 *
2193 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
2194 * a depth-first way. As such the process looks like this:
2195 *
2196 * Suppose we have a cgroup hierarchy which looks like this:
2197 *
2198 * root
2199 * / \
2200 * / \
2201 * / \
2202 * a b
2203 * / \ / \
2204 * / \ / \
2205 * c d e f
2206 * / \ / \ / \ / \
2207 * h i j k l m n o
2208 *
2209 * 1. We want to realise cgroup "d" now.
c72703e2 2210 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
a57669d2
CD
2211 * 3. cgroup "k" just started requesting the memory controller.
2212 *
2213 * To make this work we must do the following in order:
2214 *
2215 * 1. Disable CPU controller in k, j
2216 * 2. Disable CPU controller in d
2217 * 3. Enable memory controller in root
2218 * 4. Enable memory controller in a
2219 * 5. Enable memory controller in d
2220 * 6. Enable memory controller in k
2221 *
2222 * Notice that we need to touch j in one direction, but not the other. We also
2223 * don't go beyond d when disabling -- it's up to "a" to get realized if it
2224 * wants to disable further. The basic rules are therefore:
2225 *
2226 * - If you're disabling something, you need to realise all of the cgroups from
2227 * your recursive descendants to the root. This starts from the leaves.
2228 * - If you're enabling something, you need to realise from the root cgroup
2229 * downwards, but you don't need to iterate your recursive descendants.
6414b7c9
DS
2230 *
2231 * Returns 0 on success and < 0 on failure. */
db785129 2232static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
efdb0237 2233 CGroupMask target_mask, enable_mask;
6414b7c9 2234 int r;
64747e2d 2235
4ad49000 2236 assert(u);
64747e2d 2237
2aa57a65 2238 unit_remove_from_cgroup_realize_queue(u);
64747e2d 2239
efdb0237 2240 target_mask = unit_get_target_mask(u);
ccf78df1
TH
2241 enable_mask = unit_get_enable_mask(u);
2242
17f14955 2243 if (unit_has_mask_realized(u, target_mask, enable_mask))
0a1eb06d 2244 return 0;
64747e2d 2245
4f6f62e4
CD
2246 /* Disable controllers below us, if there are any */
2247 r = unit_realize_cgroup_now_disable(u, state);
2248 if (r < 0)
2249 return r;
2250
2251 /* Enable controllers above us, if there are any */
6414b7c9 2252 if (UNIT_ISSET(u->slice)) {
a57669d2 2253 r = unit_realize_cgroup_now_enable(UNIT_DEREF(u->slice), state);
6414b7c9
DS
2254 if (r < 0)
2255 return r;
2256 }
4ad49000 2257
0d2d6fbf
CD
2258 /* Now actually deal with the cgroup we were trying to realise and set attributes */
2259 r = unit_create_cgroup(u, target_mask, enable_mask, state);
6414b7c9
DS
2260 if (r < 0)
2261 return r;
2262
c2baf11c
LP
2263 /* Now, reset the invalidation mask */
2264 u->cgroup_invalidated_mask = 0;
6414b7c9 2265 return 0;
64747e2d
LP
2266}
2267
91a6073e 2268unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
db785129 2269 ManagerState state;
4ad49000 2270 unsigned n = 0;
db785129 2271 Unit *i;
6414b7c9 2272 int r;
ecedd90f 2273
91a6073e
LP
2274 assert(m);
2275
db785129
LP
2276 state = manager_state(m);
2277
91a6073e
LP
2278 while ((i = m->cgroup_realize_queue)) {
2279 assert(i->in_cgroup_realize_queue);
ecedd90f 2280
2aa57a65
LP
2281 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
2282 /* Maybe things changed, and the unit is not actually active anymore? */
2283 unit_remove_from_cgroup_realize_queue(i);
2284 continue;
2285 }
2286
db785129 2287 r = unit_realize_cgroup_now(i, state);
6414b7c9 2288 if (r < 0)
efdb0237 2289 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
0a1eb06d 2290
4ad49000
LP
2291 n++;
2292 }
ecedd90f 2293
4ad49000 2294 return n;
8e274523
LP
2295}
2296
91a6073e 2297static void unit_add_siblings_to_cgroup_realize_queue(Unit *u) {
4ad49000 2298 Unit *slice;
ca949c9d 2299
4ad49000
LP
2300 /* This adds the siblings of the specified unit and the
2301 * siblings of all parent units to the cgroup queue. (But
2302 * neither the specified unit itself nor the parents.) */
2303
2304 while ((slice = UNIT_DEREF(u->slice))) {
2305 Iterator i;
2306 Unit *m;
eef85c4a 2307 void *v;
8f53a7b8 2308
eef85c4a 2309 HASHMAP_FOREACH_KEY(v, m, u->dependencies[UNIT_BEFORE], i) {
6414b7c9
DS
2310 /* Skip units that have a dependency on the slice
2311 * but aren't actually in it. */
4ad49000 2312 if (UNIT_DEREF(m->slice) != slice)
50159e6a 2313 continue;
8e274523 2314
6414b7c9
DS
2315 /* No point in doing cgroup application for units
2316 * without active processes. */
2317 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
2318 continue;
2319
2320 /* If the unit doesn't need any new controllers
2321 * and has current ones realized, it doesn't need
2322 * any changes. */
906c06f6
DM
2323 if (unit_has_mask_realized(m,
2324 unit_get_target_mask(m),
17f14955 2325 unit_get_enable_mask(m)))
6414b7c9
DS
2326 continue;
2327
91a6073e 2328 unit_add_to_cgroup_realize_queue(m);
50159e6a
LP
2329 }
2330
4ad49000 2331 u = slice;
8e274523 2332 }
4ad49000
LP
2333}
2334
0a1eb06d 2335int unit_realize_cgroup(Unit *u) {
4ad49000
LP
2336 assert(u);
2337
35b7ff80 2338 if (!UNIT_HAS_CGROUP_CONTEXT(u))
0a1eb06d 2339 return 0;
8e274523 2340
4ad49000
LP
2341 /* So, here's the deal: when realizing the cgroups for this
2342 * unit, we need to first create all parents, but there's more
2343 * actually: for the weight-based controllers we also need to
2344 * make sure that all our siblings (i.e. units that are in the
73e231ab 2345 * same slice as we are) have cgroups, too. Otherwise, things
4ad49000
LP
2346 * would become very uneven as each of their processes would
2347 * get as much resources as all our group together. This call
2348 * will synchronously create the parent cgroups, but will
2349 * defer work on the siblings to the next event loop
2350 * iteration. */
ca949c9d 2351
4ad49000 2352 /* Add all sibling slices to the cgroup queue. */
91a6073e 2353 unit_add_siblings_to_cgroup_realize_queue(u);
4ad49000 2354
6414b7c9 2355 /* And realize this one now (and apply the values) */
db785129 2356 return unit_realize_cgroup_now(u, manager_state(u->manager));
8e274523
LP
2357}
2358
efdb0237
LP
2359void unit_release_cgroup(Unit *u) {
2360 assert(u);
2361
8a0d5388
LP
2362 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
2363 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
efdb0237
LP
2364
2365 if (u->cgroup_path) {
2366 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
2367 u->cgroup_path = mfree(u->cgroup_path);
2368 }
2369
0bb814c2
LP
2370 if (u->cgroup_control_inotify_wd >= 0) {
2371 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_control_inotify_wd) < 0)
2372 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 2373
0bb814c2
LP
2374 (void) hashmap_remove(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd));
2375 u->cgroup_control_inotify_wd = -1;
efdb0237 2376 }
afcfaa69
LP
2377
2378 if (u->cgroup_memory_inotify_wd >= 0) {
2379 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_memory_inotify_wd) < 0)
2380 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);
2381
2382 (void) hashmap_remove(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd));
2383 u->cgroup_memory_inotify_wd = -1;
2384 }
efdb0237
LP
2385}
2386
2387void unit_prune_cgroup(Unit *u) {
8e274523 2388 int r;
efdb0237 2389 bool is_root_slice;
8e274523 2390
4ad49000 2391 assert(u);
8e274523 2392
efdb0237
LP
2393 /* Removes the cgroup, if empty and possible, and stops watching it. */
2394
4ad49000
LP
2395 if (!u->cgroup_path)
2396 return;
8e274523 2397
fe700f46
LP
2398 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
2399
efdb0237
LP
2400 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
2401
2402 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
0219b352
DB
2403 if (r < 0)
2404 /* One reason we could have failed here is, that the cgroup still contains a process.
2405 * However, if the cgroup becomes removable at a later time, it might be removed when
2406 * the containing slice is stopped. So even if we failed now, this unit shouldn't assume
2407 * that the cgroup is still realized the next time it is started. Do not return early
2408 * on error, continue cleanup. */
2409 log_unit_full(u, r == -EBUSY ? LOG_DEBUG : LOG_WARNING, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
8e274523 2410
efdb0237
LP
2411 if (is_root_slice)
2412 return;
2413
2414 unit_release_cgroup(u);
0a1eb06d 2415
4ad49000 2416 u->cgroup_realized = false;
bc432dc7 2417 u->cgroup_realized_mask = 0;
ccf78df1 2418 u->cgroup_enabled_mask = 0;
084c7007
RG
2419
2420 u->bpf_device_control_installed = bpf_program_unref(u->bpf_device_control_installed);
8e274523
LP
2421}
2422
efdb0237 2423int unit_search_main_pid(Unit *u, pid_t *ret) {
4ad49000 2424 _cleanup_fclose_ FILE *f = NULL;
4d051546 2425 pid_t pid = 0, npid;
efdb0237 2426 int r;
4ad49000
LP
2427
2428 assert(u);
efdb0237 2429 assert(ret);
4ad49000
LP
2430
2431 if (!u->cgroup_path)
efdb0237 2432 return -ENXIO;
4ad49000 2433
efdb0237
LP
2434 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
2435 if (r < 0)
2436 return r;
4ad49000 2437
4ad49000 2438 while (cg_read_pid(f, &npid) > 0) {
4ad49000
LP
2439
2440 if (npid == pid)
2441 continue;
8e274523 2442
4d051546 2443 if (pid_is_my_child(npid) == 0)
4ad49000 2444 continue;
8e274523 2445
efdb0237 2446 if (pid != 0)
4ad49000
LP
2447 /* Dang, there's more than one daemonized PID
2448 in this group, so we don't know what process
2449 is the main process. */
efdb0237
LP
2450
2451 return -ENODATA;
8e274523 2452
4ad49000 2453 pid = npid;
8e274523
LP
2454 }
2455
efdb0237
LP
2456 *ret = pid;
2457 return 0;
2458}
2459
2460static int unit_watch_pids_in_path(Unit *u, const char *path) {
b3c5bad3 2461 _cleanup_closedir_ DIR *d = NULL;
efdb0237
LP
2462 _cleanup_fclose_ FILE *f = NULL;
2463 int ret = 0, r;
2464
2465 assert(u);
2466 assert(path);
2467
2468 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
2469 if (r < 0)
2470 ret = r;
2471 else {
2472 pid_t pid;
2473
2474 while ((r = cg_read_pid(f, &pid)) > 0) {
f75f613d 2475 r = unit_watch_pid(u, pid, false);
efdb0237
LP
2476 if (r < 0 && ret >= 0)
2477 ret = r;
2478 }
2479
2480 if (r < 0 && ret >= 0)
2481 ret = r;
2482 }
2483
2484 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
2485 if (r < 0) {
2486 if (ret >= 0)
2487 ret = r;
2488 } else {
2489 char *fn;
2490
2491 while ((r = cg_read_subgroup(d, &fn)) > 0) {
2492 _cleanup_free_ char *p = NULL;
2493
95b21cff 2494 p = path_join(empty_to_root(path), fn);
efdb0237
LP
2495 free(fn);
2496
2497 if (!p)
2498 return -ENOMEM;
2499
2500 r = unit_watch_pids_in_path(u, p);
2501 if (r < 0 && ret >= 0)
2502 ret = r;
2503 }
2504
2505 if (r < 0 && ret >= 0)
2506 ret = r;
2507 }
2508
2509 return ret;
2510}
2511
11aef522
LP
2512int unit_synthesize_cgroup_empty_event(Unit *u) {
2513 int r;
2514
2515 assert(u);
2516
2517 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
2518 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
2519 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
2520
2521 if (!u->cgroup_path)
2522 return -ENOENT;
2523
2524 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2525 if (r < 0)
2526 return r;
2527 if (r > 0) /* On unified we have reliable notifications, and don't need this */
2528 return 0;
2529
2530 if (!set_isempty(u->pids))
2531 return 0;
2532
2533 unit_add_to_cgroup_empty_queue(u);
2534 return 0;
2535}
2536
efdb0237 2537int unit_watch_all_pids(Unit *u) {
b4cccbc1
LP
2538 int r;
2539
efdb0237
LP
2540 assert(u);
2541
2542 /* Adds all PIDs from our cgroup to the set of PIDs we
2543 * watch. This is a fallback logic for cases where we do not
2544 * get reliable cgroup empty notifications: we try to use
2545 * SIGCHLD as replacement. */
2546
2547 if (!u->cgroup_path)
2548 return -ENOENT;
2549
c22800e4 2550 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
b4cccbc1
LP
2551 if (r < 0)
2552 return r;
2553 if (r > 0) /* On unified we can use proper notifications */
efdb0237
LP
2554 return 0;
2555
2556 return unit_watch_pids_in_path(u, u->cgroup_path);
2557}
2558
09e24654
LP
2559static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
2560 Manager *m = userdata;
2561 Unit *u;
efdb0237
LP
2562 int r;
2563
09e24654
LP
2564 assert(s);
2565 assert(m);
efdb0237 2566
09e24654
LP
2567 u = m->cgroup_empty_queue;
2568 if (!u)
efdb0237
LP
2569 return 0;
2570
09e24654
LP
2571 assert(u->in_cgroup_empty_queue);
2572 u->in_cgroup_empty_queue = false;
2573 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
2574
2575 if (m->cgroup_empty_queue) {
2576 /* More stuff queued, let's make sure we remain enabled */
2577 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
2578 if (r < 0)
19a691a9 2579 log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
09e24654 2580 }
efdb0237
LP
2581
2582 unit_add_to_gc_queue(u);
2583
2584 if (UNIT_VTABLE(u)->notify_cgroup_empty)
2585 UNIT_VTABLE(u)->notify_cgroup_empty(u);
2586
2587 return 0;
2588}
2589
09e24654
LP
2590void unit_add_to_cgroup_empty_queue(Unit *u) {
2591 int r;
2592
2593 assert(u);
2594
2595 /* Note that there are four different ways how cgroup empty events reach us:
2596 *
2597 * 1. On the unified hierarchy we get an inotify event on the cgroup
2598 *
2599 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2600 *
2601 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2602 *
2603 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2604 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2605 *
2606 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2607 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2608 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2609 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2610 * case for scope units). */
2611
2612 if (u->in_cgroup_empty_queue)
2613 return;
2614
2615 /* Let's verify that the cgroup is really empty */
2616 if (!u->cgroup_path)
2617 return;
2618 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
2619 if (r < 0) {
2620 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", u->cgroup_path);
2621 return;
2622 }
2623 if (r == 0)
2624 return;
2625
2626 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
2627 u->in_cgroup_empty_queue = true;
2628
2629 /* Trigger the defer event */
2630 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
2631 if (r < 0)
2632 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
2633}
2634
2ba6ae6b 2635int unit_check_oom(Unit *u) {
afcfaa69
LP
2636 _cleanup_free_ char *oom_kill = NULL;
2637 bool increased;
2638 uint64_t c;
2639 int r;
2640
2641 if (!u->cgroup_path)
2642 return 0;
2643
2644 r = cg_get_keyed_attribute("memory", u->cgroup_path, "memory.events", STRV_MAKE("oom_kill"), &oom_kill);
2645 if (r < 0)
2646 return log_unit_debug_errno(u, r, "Failed to read oom_kill field of memory.events cgroup attribute: %m");
2647
2648 r = safe_atou64(oom_kill, &c);
2649 if (r < 0)
2650 return log_unit_debug_errno(u, r, "Failed to parse oom_kill field: %m");
2651
2652 increased = c > u->oom_kill_last;
2653 u->oom_kill_last = c;
2654
2655 if (!increased)
2656 return 0;
2657
2658 log_struct(LOG_NOTICE,
2659 "MESSAGE_ID=" SD_MESSAGE_UNIT_OUT_OF_MEMORY_STR,
2660 LOG_UNIT_ID(u),
2661 LOG_UNIT_INVOCATION_ID(u),
2662 LOG_UNIT_MESSAGE(u, "A process of this unit has been killed by the OOM killer."));
2663
2664 if (UNIT_VTABLE(u)->notify_cgroup_oom)
2665 UNIT_VTABLE(u)->notify_cgroup_oom(u);
2666
2667 return 1;
2668}
2669
2670static int on_cgroup_oom_event(sd_event_source *s, void *userdata) {
2671 Manager *m = userdata;
2672 Unit *u;
2673 int r;
2674
2675 assert(s);
2676 assert(m);
2677
2678 u = m->cgroup_oom_queue;
2679 if (!u)
2680 return 0;
2681
2682 assert(u->in_cgroup_oom_queue);
2683 u->in_cgroup_oom_queue = false;
2684 LIST_REMOVE(cgroup_oom_queue, m->cgroup_oom_queue, u);
2685
2686 if (m->cgroup_oom_queue) {
2687 /* More stuff queued, let's make sure we remain enabled */
2688 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
2689 if (r < 0)
2690 log_debug_errno(r, "Failed to reenable cgroup oom event source, ignoring: %m");
2691 }
2692
2693 (void) unit_check_oom(u);
2694 return 0;
2695}
2696
2697static void unit_add_to_cgroup_oom_queue(Unit *u) {
2698 int r;
2699
2700 assert(u);
2701
2702 if (u->in_cgroup_oom_queue)
2703 return;
2704 if (!u->cgroup_path)
2705 return;
2706
2707 LIST_PREPEND(cgroup_oom_queue, u->manager->cgroup_oom_queue, u);
2708 u->in_cgroup_oom_queue = true;
2709
2710 /* Trigger the defer event */
2711 if (!u->manager->cgroup_oom_event_source) {
2712 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
2713
2714 r = sd_event_add_defer(u->manager->event, &s, on_cgroup_oom_event, u->manager);
2715 if (r < 0) {
2716 log_error_errno(r, "Failed to create cgroup oom event source: %m");
2717 return;
2718 }
2719
2720 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_NORMAL-8);
2721 if (r < 0) {
2722 log_error_errno(r, "Failed to set priority of cgroup oom event source: %m");
2723 return;
2724 }
2725
2726 (void) sd_event_source_set_description(s, "cgroup-oom");
2727 u->manager->cgroup_oom_event_source = TAKE_PTR(s);
2728 }
2729
2730 r = sd_event_source_set_enabled(u->manager->cgroup_oom_event_source, SD_EVENT_ONESHOT);
2731 if (r < 0)
2732 log_error_errno(r, "Failed to enable cgroup oom event source: %m");
2733}
2734
efdb0237
LP
2735static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2736 Manager *m = userdata;
2737
2738 assert(s);
2739 assert(fd >= 0);
2740 assert(m);
2741
2742 for (;;) {
2743 union inotify_event_buffer buffer;
2744 struct inotify_event *e;
2745 ssize_t l;
2746
2747 l = read(fd, &buffer, sizeof(buffer));
2748 if (l < 0) {
47249640 2749 if (IN_SET(errno, EINTR, EAGAIN))
efdb0237
LP
2750 return 0;
2751
2752 return log_error_errno(errno, "Failed to read control group inotify events: %m");
2753 }
2754
2755 FOREACH_INOTIFY_EVENT(e, buffer, l) {
2756 Unit *u;
2757
2758 if (e->wd < 0)
2759 /* Queue overflow has no watch descriptor */
2760 continue;
2761
2762 if (e->mask & IN_IGNORED)
2763 /* The watch was just removed */
2764 continue;
2765
afcfaa69
LP
2766 /* Note that inotify might deliver events for a watch even after it was removed,
2767 * because it was queued before the removal. Let's ignore this here safely. */
2768
0bb814c2 2769 u = hashmap_get(m->cgroup_control_inotify_wd_unit, INT_TO_PTR(e->wd));
afcfaa69
LP
2770 if (u)
2771 unit_add_to_cgroup_empty_queue(u);
efdb0237 2772
afcfaa69
LP
2773 u = hashmap_get(m->cgroup_memory_inotify_wd_unit, INT_TO_PTR(e->wd));
2774 if (u)
2775 unit_add_to_cgroup_oom_queue(u);
efdb0237
LP
2776 }
2777 }
8e274523
LP
2778}
2779
17f14955
RG
2780static int cg_bpf_mask_supported(CGroupMask *ret) {
2781 CGroupMask mask = 0;
2782 int r;
2783
2784 /* BPF-based firewall */
2785 r = bpf_firewall_supported();
2786 if (r > 0)
2787 mask |= CGROUP_MASK_BPF_FIREWALL;
2788
084c7007
RG
2789 /* BPF-based device access control */
2790 r = bpf_devices_supported();
2791 if (r > 0)
2792 mask |= CGROUP_MASK_BPF_DEVICES;
2793
17f14955
RG
2794 *ret = mask;
2795 return 0;
2796}
2797
8e274523 2798int manager_setup_cgroup(Manager *m) {
9444b1f2 2799 _cleanup_free_ char *path = NULL;
10bd3e2e 2800 const char *scope_path;
efdb0237 2801 CGroupController c;
b4cccbc1 2802 int r, all_unified;
17f14955 2803 CGroupMask mask;
efdb0237 2804 char *e;
8e274523
LP
2805
2806 assert(m);
2807
35d2e7ec 2808 /* 1. Determine hierarchy */
efdb0237 2809 m->cgroup_root = mfree(m->cgroup_root);
9444b1f2 2810 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
23bbb0de
MS
2811 if (r < 0)
2812 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
8e274523 2813
efdb0237
LP
2814 /* Chop off the init scope, if we are already located in it */
2815 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
0d8c31ff 2816
efdb0237
LP
2817 /* LEGACY: Also chop off the system slice if we are in
2818 * it. This is to support live upgrades from older systemd
2819 * versions where PID 1 was moved there. Also see
2820 * cg_get_root_path(). */
463d0d15 2821 if (!e && MANAGER_IS_SYSTEM(m)) {
9444b1f2 2822 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
15c60e99 2823 if (!e)
efdb0237 2824 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
0baf24dd 2825 }
efdb0237
LP
2826 if (e)
2827 *e = 0;
7ccfb64a 2828
7546145e
LP
2829 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2830 * easily prepend it everywhere. */
2831 delete_trailing_chars(m->cgroup_root, "/");
8e274523 2832
35d2e7ec 2833 /* 2. Show data */
9444b1f2 2834 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
23bbb0de
MS
2835 if (r < 0)
2836 return log_error_errno(r, "Cannot find cgroup mount point: %m");
8e274523 2837
d4d99bc6 2838 r = cg_unified();
415fc41c
TH
2839 if (r < 0)
2840 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
5da38d07 2841
b4cccbc1 2842 all_unified = cg_all_unified();
d4c819ed
ZJS
2843 if (all_unified < 0)
2844 return log_error_errno(all_unified, "Couldn't determine whether we are in all unified mode: %m");
2845 if (all_unified > 0)
efdb0237 2846 log_debug("Unified cgroup hierarchy is located at %s.", path);
b4cccbc1 2847 else {
c22800e4 2848 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
b4cccbc1
LP
2849 if (r < 0)
2850 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
2851 if (r > 0)
2852 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
2853 else
2854 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
2855 }
efdb0237 2856
09e24654
LP
2857 /* 3. Allocate cgroup empty defer event source */
2858 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2859 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
2860 if (r < 0)
2861 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
2862
cbe83389
LP
2863 /* Schedule cgroup empty checks early, but after having processed service notification messages or
2864 * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of
2865 * notification, and we collected the metadata the notification and SIGCHLD stuff offers first. */
09e24654
LP
2866 r = sd_event_source_set_priority(m->cgroup_empty_event_source, SD_EVENT_PRIORITY_NORMAL-5);
2867 if (r < 0)
2868 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
2869
2870 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
2871 if (r < 0)
2872 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
2873
2874 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
2875
2876 /* 4. Install notifier inotify object, or agent */
10bd3e2e 2877 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
c6c18be3 2878
09e24654 2879 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
efdb0237 2880
10bd3e2e
LP
2881 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2882 safe_close(m->cgroup_inotify_fd);
efdb0237 2883
10bd3e2e
LP
2884 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
2885 if (m->cgroup_inotify_fd < 0)
2886 return log_error_errno(errno, "Failed to create control group inotify object: %m");
efdb0237 2887
10bd3e2e
LP
2888 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
2889 if (r < 0)
2890 return log_error_errno(r, "Failed to watch control group inotify object: %m");
efdb0237 2891
cbe83389
LP
2892 /* Process cgroup empty notifications early. Note that when this event is dispatched it'll
2893 * just add the unit to a cgroup empty queue, hence let's run earlier than that. Also see
2894 * handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2895 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-9);
10bd3e2e
LP
2896 if (r < 0)
2897 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
efdb0237 2898
10bd3e2e 2899 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
efdb0237 2900
611c4f8a 2901 } else if (MANAGER_IS_SYSTEM(m) && manager_owns_host_root_cgroup(m) && !MANAGER_IS_TEST_RUN(m)) {
efdb0237 2902
10bd3e2e
LP
2903 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2904 * since it does not generate events when control groups with children run empty. */
8e274523 2905
10bd3e2e 2906 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
23bbb0de 2907 if (r < 0)
10bd3e2e
LP
2908 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
2909 else if (r > 0)
2910 log_debug("Installed release agent.");
2911 else if (r == 0)
2912 log_debug("Release agent already installed.");
2913 }
efdb0237 2914
09e24654 2915 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
10bd3e2e
LP
2916 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2917 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
aa77e234
MS
2918 if (r >= 0) {
2919 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2920 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2921 if (r < 0)
2922 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
c6c18be3 2923
aa77e234
MS
2924 /* 6. And pin it, so that it cannot be unmounted */
2925 safe_close(m->pin_cgroupfs_fd);
2926 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
2927 if (m->pin_cgroupfs_fd < 0)
2928 return log_error_errno(errno, "Failed to open pin file: %m");
0d8c31ff 2929
638cece4 2930 } else if (!MANAGER_IS_TEST_RUN(m))
aa77e234 2931 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
10bd3e2e 2932
09e24654 2933 /* 7. Always enable hierarchical support if it exists... */
638cece4 2934 if (!all_unified && !MANAGER_IS_TEST_RUN(m))
10bd3e2e 2935 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
c6c18be3 2936
17f14955 2937 /* 8. Figure out which controllers are supported */
efdb0237
LP
2938 r = cg_mask_supported(&m->cgroup_supported);
2939 if (r < 0)
2940 return log_error_errno(r, "Failed to determine supported controllers: %m");
17f14955
RG
2941
2942 /* 9. Figure out which bpf-based pseudo-controllers are supported */
2943 r = cg_bpf_mask_supported(&mask);
2944 if (r < 0)
2945 return log_error_errno(r, "Failed to determine supported bpf-based pseudo-controllers: %m");
2946 m->cgroup_supported |= mask;
2947
2948 /* 10. Log which controllers are supported */
efdb0237 2949 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
eee0a1e4 2950 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
9156e799 2951
a32360f1 2952 return 0;
8e274523
LP
2953}
2954
c6c18be3 2955void manager_shutdown_cgroup(Manager *m, bool delete) {
8e274523
LP
2956 assert(m);
2957
9444b1f2
LP
2958 /* We can't really delete the group, since we are in it. But
2959 * let's trim it. */
f6c63f6f 2960 if (delete && m->cgroup_root && m->test_run_flags != MANAGER_TEST_RUN_MINIMAL)
efdb0237
LP
2961 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
2962
09e24654
LP
2963 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2964
0bb814c2 2965 m->cgroup_control_inotify_wd_unit = hashmap_free(m->cgroup_control_inotify_wd_unit);
afcfaa69 2966 m->cgroup_memory_inotify_wd_unit = hashmap_free(m->cgroup_memory_inotify_wd_unit);
efdb0237
LP
2967
2968 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2969 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
8e274523 2970
03e334a1 2971 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
c6c18be3 2972
efdb0237 2973 m->cgroup_root = mfree(m->cgroup_root);
8e274523
LP
2974}
2975
4ad49000 2976Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
acb14d31 2977 char *p;
4ad49000 2978 Unit *u;
acb14d31
LP
2979
2980 assert(m);
2981 assert(cgroup);
acb14d31 2982
4ad49000
LP
2983 u = hashmap_get(m->cgroup_unit, cgroup);
2984 if (u)
2985 return u;
acb14d31 2986
8e70580b 2987 p = strdupa(cgroup);
acb14d31
LP
2988 for (;;) {
2989 char *e;
2990
2991 e = strrchr(p, '/');
efdb0237
LP
2992 if (!e || e == p)
2993 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
acb14d31
LP
2994
2995 *e = 0;
2996
4ad49000
LP
2997 u = hashmap_get(m->cgroup_unit, p);
2998 if (u)
2999 return u;
acb14d31
LP
3000 }
3001}
3002
b3ac818b 3003Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
4ad49000 3004 _cleanup_free_ char *cgroup = NULL;
8e274523 3005
8c47c732
LP
3006 assert(m);
3007
62a76913 3008 if (!pid_is_valid(pid))
b3ac818b
LP
3009 return NULL;
3010
62a76913 3011 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup) < 0)
b3ac818b
LP
3012 return NULL;
3013
3014 return manager_get_unit_by_cgroup(m, cgroup);
3015}
3016
3017Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
62a76913 3018 Unit *u, **array;
b3ac818b
LP
3019
3020 assert(m);
3021
62a76913
LP
3022 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
3023 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
3024 * relevant one as children of the process will be assigned to that one, too, before all else. */
3025
3026 if (!pid_is_valid(pid))
8c47c732
LP
3027 return NULL;
3028
2ca9d979 3029 if (pid == getpid_cached())
efdb0237
LP
3030 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
3031
62a76913 3032 u = manager_get_unit_by_pid_cgroup(m, pid);
5fe8876b
LP
3033 if (u)
3034 return u;
3035
62a76913 3036 u = hashmap_get(m->watch_pids, PID_TO_PTR(pid));
5fe8876b
LP
3037 if (u)
3038 return u;
3039
62a76913
LP
3040 array = hashmap_get(m->watch_pids, PID_TO_PTR(-pid));
3041 if (array)
3042 return array[0];
3043
3044 return NULL;
6dde1f33 3045}
4fbf50b3 3046
4ad49000
LP
3047int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
3048 Unit *u;
4fbf50b3 3049
4ad49000
LP
3050 assert(m);
3051 assert(cgroup);
4fbf50b3 3052
09e24654
LP
3053 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
3054 * or from the --system instance */
3055
d8fdc620
LP
3056 log_debug("Got cgroup empty notification for: %s", cgroup);
3057
4ad49000 3058 u = manager_get_unit_by_cgroup(m, cgroup);
5ad096b3
LP
3059 if (!u)
3060 return 0;
b56c28c3 3061
09e24654
LP
3062 unit_add_to_cgroup_empty_queue(u);
3063 return 1;
5ad096b3
LP
3064}
3065
3066int unit_get_memory_current(Unit *u, uint64_t *ret) {
3067 _cleanup_free_ char *v = NULL;
3068 int r;
3069
3070 assert(u);
3071 assert(ret);
3072
2e4025c0 3073 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
cf3b4be1
LP
3074 return -ENODATA;
3075
5ad096b3
LP
3076 if (!u->cgroup_path)
3077 return -ENODATA;
3078
1f73aa00 3079 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
611c4f8a 3080 if (unit_has_host_root_cgroup(u))
c482724a 3081 return procfs_memory_get_used(ret);
1f73aa00 3082
efdb0237 3083 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
5ad096b3
LP
3084 return -ENODATA;
3085
b4cccbc1
LP
3086 r = cg_all_unified();
3087 if (r < 0)
3088 return r;
3089 if (r > 0)
efdb0237 3090 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
b4cccbc1
LP
3091 else
3092 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
5ad096b3
LP
3093 if (r == -ENOENT)
3094 return -ENODATA;
3095 if (r < 0)
3096 return r;
3097
3098 return safe_atou64(v, ret);
3099}
3100
03a7b521
LP
3101int unit_get_tasks_current(Unit *u, uint64_t *ret) {
3102 _cleanup_free_ char *v = NULL;
3103 int r;
3104
3105 assert(u);
3106 assert(ret);
3107
2e4025c0 3108 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
cf3b4be1
LP
3109 return -ENODATA;
3110
03a7b521
LP
3111 if (!u->cgroup_path)
3112 return -ENODATA;
3113
c36a69f4 3114 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
611c4f8a 3115 if (unit_has_host_root_cgroup(u))
c36a69f4
LP
3116 return procfs_tasks_get_current(ret);
3117
1f73aa00
LP
3118 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
3119 return -ENODATA;
3120
03a7b521
LP
3121 r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
3122 if (r == -ENOENT)
3123 return -ENODATA;
3124 if (r < 0)
3125 return r;
3126
3127 return safe_atou64(v, ret);
3128}
3129
5ad096b3
LP
3130static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
3131 _cleanup_free_ char *v = NULL;
3132 uint64_t ns;
3133 int r;
3134
3135 assert(u);
3136 assert(ret);
3137
3138 if (!u->cgroup_path)
3139 return -ENODATA;
3140
1f73aa00 3141 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
611c4f8a 3142 if (unit_has_host_root_cgroup(u))
1f73aa00
LP
3143 return procfs_cpu_get_usage(ret);
3144
f98c2585
CD
3145 /* Requisite controllers for CPU accounting are not enabled */
3146 if ((get_cpu_accounting_mask() & ~u->cgroup_realized_mask) != 0)
3147 return -ENODATA;
3148
92a99304
LP
3149 r = cg_all_unified();
3150 if (r < 0)
3151 return r;
b4cccbc1 3152 if (r > 0) {
66ebf6c0
TH
3153 _cleanup_free_ char *val = NULL;
3154 uint64_t us;
5ad096b3 3155
b734a4ff 3156 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
b734a4ff
LP
3157 if (IN_SET(r, -ENOENT, -ENXIO))
3158 return -ENODATA;
d742f4b5
LP
3159 if (r < 0)
3160 return r;
66ebf6c0
TH
3161
3162 r = safe_atou64(val, &us);
3163 if (r < 0)
3164 return r;
3165
3166 ns = us * NSEC_PER_USEC;
3167 } else {
66ebf6c0
TH
3168 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
3169 if (r == -ENOENT)
3170 return -ENODATA;
3171 if (r < 0)
3172 return r;
3173
3174 r = safe_atou64(v, &ns);
3175 if (r < 0)
3176 return r;
3177 }
5ad096b3
LP
3178
3179 *ret = ns;
3180 return 0;
3181}
3182
3183int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
3184 nsec_t ns;
3185 int r;
3186
fe700f46
LP
3187 assert(u);
3188
3189 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
3190 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
3191 * call this function with a NULL return value. */
3192
2e4025c0 3193 if (!UNIT_CGROUP_BOOL(u, cpu_accounting))
cf3b4be1
LP
3194 return -ENODATA;
3195
5ad096b3 3196 r = unit_get_cpu_usage_raw(u, &ns);
fe700f46
LP
3197 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
3198 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
3199 * cached value. */
3200
3201 if (ret)
3202 *ret = u->cpu_usage_last;
3203 return 0;
3204 }
5ad096b3
LP
3205 if (r < 0)
3206 return r;
3207
66ebf6c0
TH
3208 if (ns > u->cpu_usage_base)
3209 ns -= u->cpu_usage_base;
5ad096b3
LP
3210 else
3211 ns = 0;
3212
fe700f46
LP
3213 u->cpu_usage_last = ns;
3214 if (ret)
3215 *ret = ns;
3216
5ad096b3
LP
3217 return 0;
3218}
3219
906c06f6
DM
3220int unit_get_ip_accounting(
3221 Unit *u,
3222 CGroupIPAccountingMetric metric,
3223 uint64_t *ret) {
3224
6b659ed8 3225 uint64_t value;
906c06f6
DM
3226 int fd, r;
3227
3228 assert(u);
3229 assert(metric >= 0);
3230 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
3231 assert(ret);
3232
2e4025c0 3233 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
cf3b4be1
LP
3234 return -ENODATA;
3235
906c06f6
DM
3236 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
3237 u->ip_accounting_ingress_map_fd :
3238 u->ip_accounting_egress_map_fd;
906c06f6
DM
3239 if (fd < 0)
3240 return -ENODATA;
3241
3242 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
6b659ed8 3243 r = bpf_firewall_read_accounting(fd, &value, NULL);
906c06f6 3244 else
6b659ed8
LP
3245 r = bpf_firewall_read_accounting(fd, NULL, &value);
3246 if (r < 0)
3247 return r;
3248
3249 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
3250 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
3251 * ip_accounting_extra[] field, and add them in here transparently. */
3252
3253 *ret = value + u->ip_accounting_extra[metric];
906c06f6
DM
3254
3255 return r;
3256}
3257
fbe14fc9
LP
3258static int unit_get_io_accounting_raw(Unit *u, uint64_t ret[static _CGROUP_IO_ACCOUNTING_METRIC_MAX]) {
3259 static const char *const field_names[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3260 [CGROUP_IO_READ_BYTES] = "rbytes=",
3261 [CGROUP_IO_WRITE_BYTES] = "wbytes=",
3262 [CGROUP_IO_READ_OPERATIONS] = "rios=",
3263 [CGROUP_IO_WRITE_OPERATIONS] = "wios=",
3264 };
3265 uint64_t acc[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {};
3266 _cleanup_free_ char *path = NULL;
3267 _cleanup_fclose_ FILE *f = NULL;
3268 int r;
3269
3270 assert(u);
3271
3272 if (!u->cgroup_path)
3273 return -ENODATA;
3274
3275 if (unit_has_host_root_cgroup(u))
3276 return -ENODATA; /* TODO: return useful data for the top-level cgroup */
3277
3278 r = cg_all_unified();
3279 if (r < 0)
3280 return r;
3281 if (r == 0) /* TODO: support cgroupv1 */
3282 return -ENODATA;
3283
3284 if (!FLAGS_SET(u->cgroup_realized_mask, CGROUP_MASK_IO))
3285 return -ENODATA;
3286
3287 r = cg_get_path("io", u->cgroup_path, "io.stat", &path);
3288 if (r < 0)
3289 return r;
3290
3291 f = fopen(path, "re");
3292 if (!f)
3293 return -errno;
3294
3295 for (;;) {
3296 _cleanup_free_ char *line = NULL;
3297 const char *p;
3298
3299 r = read_line(f, LONG_LINE_MAX, &line);
3300 if (r < 0)
3301 return r;
3302 if (r == 0)
3303 break;
3304
3305 p = line;
3306 p += strcspn(p, WHITESPACE); /* Skip over device major/minor */
3307 p += strspn(p, WHITESPACE); /* Skip over following whitespace */
3308
3309 for (;;) {
3310 _cleanup_free_ char *word = NULL;
3311
3312 r = extract_first_word(&p, &word, NULL, EXTRACT_RETAIN_ESCAPE);
3313 if (r < 0)
3314 return r;
3315 if (r == 0)
3316 break;
3317
3318 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
3319 const char *x;
3320
3321 x = startswith(word, field_names[i]);
3322 if (x) {
3323 uint64_t w;
3324
3325 r = safe_atou64(x, &w);
3326 if (r < 0)
3327 return r;
3328
3329 /* Sum up the stats of all devices */
3330 acc[i] += w;
3331 break;
3332 }
3333 }
3334 }
3335 }
3336
3337 memcpy(ret, acc, sizeof(acc));
3338 return 0;
3339}
3340
3341int unit_get_io_accounting(
3342 Unit *u,
3343 CGroupIOAccountingMetric metric,
3344 bool allow_cache,
3345 uint64_t *ret) {
3346
3347 uint64_t raw[_CGROUP_IO_ACCOUNTING_METRIC_MAX];
3348 int r;
3349
3350 /* Retrieve an IO account parameter. This will subtract the counter when the unit was started. */
3351
3352 if (!UNIT_CGROUP_BOOL(u, io_accounting))
3353 return -ENODATA;
3354
3355 if (allow_cache && u->io_accounting_last[metric] != UINT64_MAX)
3356 goto done;
3357
3358 r = unit_get_io_accounting_raw(u, raw);
3359 if (r == -ENODATA && u->io_accounting_last[metric] != UINT64_MAX)
3360 goto done;
3361 if (r < 0)
3362 return r;
3363
3364 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
3365 /* Saturated subtraction */
3366 if (raw[i] > u->io_accounting_base[i])
3367 u->io_accounting_last[i] = raw[i] - u->io_accounting_base[i];
3368 else
3369 u->io_accounting_last[i] = 0;
3370 }
3371
3372done:
3373 if (ret)
3374 *ret = u->io_accounting_last[metric];
3375
3376 return 0;
3377}
3378
906c06f6 3379int unit_reset_cpu_accounting(Unit *u) {
5ad096b3
LP
3380 int r;
3381
3382 assert(u);
3383
fe700f46
LP
3384 u->cpu_usage_last = NSEC_INFINITY;
3385
0bbff7d6 3386 r = unit_get_cpu_usage_raw(u, &u->cpu_usage_base);
5ad096b3 3387 if (r < 0) {
66ebf6c0 3388 u->cpu_usage_base = 0;
5ad096b3 3389 return r;
b56c28c3 3390 }
2633eb83 3391
4ad49000 3392 return 0;
4fbf50b3
LP
3393}
3394
906c06f6
DM
3395int unit_reset_ip_accounting(Unit *u) {
3396 int r = 0, q = 0;
3397
3398 assert(u);
3399
3400 if (u->ip_accounting_ingress_map_fd >= 0)
3401 r = bpf_firewall_reset_accounting(u->ip_accounting_ingress_map_fd);
3402
3403 if (u->ip_accounting_egress_map_fd >= 0)
3404 q = bpf_firewall_reset_accounting(u->ip_accounting_egress_map_fd);
3405
6b659ed8
LP
3406 zero(u->ip_accounting_extra);
3407
906c06f6
DM
3408 return r < 0 ? r : q;
3409}
3410
fbe14fc9
LP
3411int unit_reset_io_accounting(Unit *u) {
3412 int r;
3413
3414 assert(u);
3415
3416 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++)
3417 u->io_accounting_last[i] = UINT64_MAX;
3418
3419 r = unit_get_io_accounting_raw(u, u->io_accounting_base);
3420 if (r < 0) {
3421 zero(u->io_accounting_base);
3422 return r;
3423 }
3424
3425 return 0;
3426}
3427
9b2559a1 3428int unit_reset_accounting(Unit *u) {
fbe14fc9 3429 int r, q, v;
9b2559a1
LP
3430
3431 assert(u);
3432
3433 r = unit_reset_cpu_accounting(u);
fbe14fc9
LP
3434 q = unit_reset_io_accounting(u);
3435 v = unit_reset_ip_accounting(u);
9b2559a1 3436
fbe14fc9 3437 return r < 0 ? r : q < 0 ? q : v;
9b2559a1
LP
3438}
3439
e7ab4d1a
LP
3440void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
3441 assert(u);
3442
3443 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3444 return;
3445
3446 if (m == 0)
3447 return;
3448
538b4852
TH
3449 /* always invalidate compat pairs together */
3450 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
3451 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
3452
7cce4fb7
LP
3453 if (m & (CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT))
3454 m |= CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT;
3455
e00068e7 3456 if (FLAGS_SET(u->cgroup_invalidated_mask, m)) /* NOP? */
e7ab4d1a
LP
3457 return;
3458
e00068e7 3459 u->cgroup_invalidated_mask |= m;
91a6073e 3460 unit_add_to_cgroup_realize_queue(u);
e7ab4d1a
LP
3461}
3462
906c06f6
DM
3463void unit_invalidate_cgroup_bpf(Unit *u) {
3464 assert(u);
3465
3466 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3467 return;
3468
17f14955 3469 if (u->cgroup_invalidated_mask & CGROUP_MASK_BPF_FIREWALL) /* NOP? */
906c06f6
DM
3470 return;
3471
17f14955 3472 u->cgroup_invalidated_mask |= CGROUP_MASK_BPF_FIREWALL;
91a6073e 3473 unit_add_to_cgroup_realize_queue(u);
906c06f6
DM
3474
3475 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
3476 * list of our children includes our own. */
3477 if (u->type == UNIT_SLICE) {
3478 Unit *member;
3479 Iterator i;
eef85c4a 3480 void *v;
906c06f6 3481
eef85c4a 3482 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE], i) {
cb5e3bc3
CD
3483 if (UNIT_DEREF(member->slice) == u)
3484 unit_invalidate_cgroup_bpf(member);
906c06f6
DM
3485 }
3486 }
3487}
3488
1d9cc876
LP
3489bool unit_cgroup_delegate(Unit *u) {
3490 CGroupContext *c;
3491
3492 assert(u);
3493
3494 if (!UNIT_VTABLE(u)->can_delegate)
3495 return false;
3496
3497 c = unit_get_cgroup_context(u);
3498 if (!c)
3499 return false;
3500
3501 return c->delegate;
3502}
3503
e7ab4d1a
LP
3504void manager_invalidate_startup_units(Manager *m) {
3505 Iterator i;
3506 Unit *u;
3507
3508 assert(m);
3509
3510 SET_FOREACH(u, m->startup_units, i)
13c31542 3511 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
e7ab4d1a
LP
3512}
3513
da8e1782
MO
3514static int unit_get_nice(Unit *u) {
3515 ExecContext *ec;
3516
3517 ec = unit_get_exec_context(u);
3518 return ec ? ec->nice : 0;
3519}
3520
3521static uint64_t unit_get_cpu_weight(Unit *u) {
3522 ManagerState state = manager_state(u->manager);
3523 CGroupContext *cc;
3524
3525 cc = unit_get_cgroup_context(u);
3526 return cc ? cgroup_context_cpu_weight(cc, state) : CGROUP_WEIGHT_DEFAULT;
3527}
3528
3529int compare_job_priority(const void *a, const void *b) {
3530 const Job *x = a, *y = b;
3531 int nice_x, nice_y;
3532 uint64_t weight_x, weight_y;
3533 int ret;
3534
217b7b33
ZJS
3535 if ((ret = CMP(x->unit->type, y->unit->type)) != 0)
3536 return -ret;
3537
da8e1782
MO
3538 weight_x = unit_get_cpu_weight(x->unit);
3539 weight_y = unit_get_cpu_weight(y->unit);
3540
217b7b33
ZJS
3541 if ((ret = CMP(weight_x, weight_y)) != 0)
3542 return -ret;
da8e1782
MO
3543
3544 nice_x = unit_get_nice(x->unit);
3545 nice_y = unit_get_nice(y->unit);
3546
3547 if ((ret = CMP(nice_x, nice_y)) != 0)
3548 return ret;
3549
da8e1782
MO
3550 return strcmp(x->unit->id, y->unit->id);
3551}
3552
4ad49000 3553static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
084870f9
ZJS
3554 [CGROUP_DEVICE_POLICY_AUTO] = "auto",
3555 [CGROUP_DEVICE_POLICY_CLOSED] = "closed",
3556 [CGROUP_DEVICE_POLICY_STRICT] = "strict",
4ad49000 3557};
4fbf50b3 3558
047f5d63
PH
3559int unit_get_cpuset(Unit *u, CPUSet *cpus, const char *name) {
3560 _cleanup_free_ char *v = NULL;
3561 int r;
3562
3563 assert(u);
3564 assert(cpus);
3565
3566 if (!u->cgroup_path)
3567 return -ENODATA;
3568
3569 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUSET) == 0)
3570 return -ENODATA;
3571
3572 r = cg_all_unified();
3573 if (r < 0)
3574 return r;
3575 if (r == 0)
3576 return -ENODATA;
3577 if (r > 0)
3578 r = cg_get_attribute("cpuset", u->cgroup_path, name, &v);
3579 if (r == -ENOENT)
3580 return -ENODATA;
3581 if (r < 0)
3582 return r;
3583
3584 return parse_cpu_set_full(v, cpus, false, NULL, NULL, 0, NULL);
3585}
3586
4ad49000 3587DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);