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