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