]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/cgroup.c
core: move reset_arguments() to the end of main's finish
[thirdparty/systemd.git] / src / core / cgroup.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <fcntl.h>
4
5 #include "sd-messages.h"
6
7 #include "alloc-util.h"
8 #include "blockdev-util.h"
9 #include "bpf-devices.h"
10 #include "bpf-firewall.h"
11 #include "btrfs-util.h"
12 #include "bus-error.h"
13 #include "cgroup-setup.h"
14 #include "cgroup-util.h"
15 #include "cgroup.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "fs-util.h"
19 #include "io-util.h"
20 #include "limits-util.h"
21 #include "nulstr-util.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 #include "process-util.h"
25 #include "procfs-util.h"
26 #include "special.h"
27 #include "stat-util.h"
28 #include "stdio-util.h"
29 #include "string-table.h"
30 #include "string-util.h"
31 #include "virt.h"
32
33 #define CGROUP_CPU_QUOTA_DEFAULT_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
34
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
40 uint64_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
47 bool manager_owns_host_root_cgroup(Manager *m) {
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
55 if (MANAGER_IS_USER(m))
56 return false;
57
58 if (detect_container() > 0)
59 return false;
60
61 return empty_or_root(m->cgroup_root);
62 }
63
64 bool unit_has_host_root_cgroup(Unit *u) {
65 assert(u);
66
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. */
69
70 if (!manager_owns_host_root_cgroup(u->manager))
71 return false;
72
73 return unit_has_name(u, SPECIAL_ROOT_SLICE);
74 }
75
76 static 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_errno(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
87 static void cgroup_compat_warn(void) {
88 static bool cgroup_compat_warned = false;
89
90 if (cgroup_compat_warned)
91 return;
92
93 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
94 "See cgroup-compat debug messages for details.");
95
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__); \
102 } while (false)
103
104 void cgroup_context_init(CGroupContext *c) {
105 assert(c);
106
107 /* Initialize everything to the kernel defaults. */
108
109 *c = (CGroupContext) {
110 .cpu_weight = CGROUP_WEIGHT_INVALID,
111 .startup_cpu_weight = CGROUP_WEIGHT_INVALID,
112 .cpu_quota_per_sec_usec = USEC_INFINITY,
113 .cpu_quota_period_usec = USEC_INFINITY,
114
115 .cpu_shares = CGROUP_CPU_SHARES_INVALID,
116 .startup_cpu_shares = CGROUP_CPU_SHARES_INVALID,
117
118 .memory_high = CGROUP_LIMIT_MAX,
119 .memory_max = CGROUP_LIMIT_MAX,
120 .memory_swap_max = CGROUP_LIMIT_MAX,
121
122 .memory_limit = CGROUP_LIMIT_MAX,
123
124 .io_weight = CGROUP_WEIGHT_INVALID,
125 .startup_io_weight = CGROUP_WEIGHT_INVALID,
126
127 .blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
128 .startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID,
129
130 .tasks_max = TASKS_MAX_UNSET,
131 };
132 }
133
134 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
135 assert(c);
136 assert(a);
137
138 LIST_REMOVE(device_allow, c->device_allow, a);
139 free(a->path);
140 free(a);
141 }
142
143 void 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
152 void 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
161 void 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
170 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
171 assert(c);
172 assert(w);
173
174 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
175 free(w->path);
176 free(w);
177 }
178
179 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
180 assert(c);
181 assert(b);
182
183 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
184 free(b->path);
185 free(b);
186 }
187
188 void cgroup_context_done(CGroupContext *c) {
189 assert(c);
190
191 while (c->io_device_weights)
192 cgroup_context_free_io_device_weight(c, c->io_device_weights);
193
194 while (c->io_device_latencies)
195 cgroup_context_free_io_device_latency(c, c->io_device_latencies);
196
197 while (c->io_device_limits)
198 cgroup_context_free_io_device_limit(c, c->io_device_limits);
199
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);
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);
211
212 c->ip_filters_ingress = strv_free(c->ip_filters_ingress);
213 c->ip_filters_egress = strv_free(c->ip_filters_egress);
214
215 cpu_set_reset(&c->cpuset_cpus);
216 cpu_set_reset(&c->cpuset_mems);
217 }
218
219 static int unit_get_kernel_memory_limit(Unit *u, const char *file, uint64_t *ret) {
220 assert(u);
221
222 if (!u->cgroup_realized)
223 return -EOWNERDEAD;
224
225 return cg_get_attribute_as_uint64("memory", u->cgroup_path, file, ret);
226 }
227
228 static 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
320 #define FORMAT_CGROUP_DIFF_MAX 128
321
322 static 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
351 void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
352 _cleanup_free_ char *disable_controllers_str = NULL, *cpuset_cpus = NULL, *cpuset_mems = NULL;
353 CGroupIODeviceLimit *il;
354 CGroupIODeviceWeight *iw;
355 CGroupIODeviceLatency *l;
356 CGroupBlockIODeviceBandwidth *b;
357 CGroupBlockIODeviceWeight *w;
358 CGroupDeviceAllow *a;
359 CGroupContext *c;
360 IPAddressAccessItem *iaai;
361 char **path;
362 char q[FORMAT_TIMESPAN_MAX];
363 char v[FORMAT_TIMESPAN_MAX];
364
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);
372 assert(f);
373
374 c = unit_get_cgroup_context(u);
375 assert(c);
376
377 prefix = strempty(prefix);
378
379 (void) cg_mask_to_string(c->disable_controllers, &disable_controllers_str);
380
381 cpuset_cpus = cpu_set_to_range_string(&c->cpuset_cpus);
382 cpuset_mems = cpu_set_to_range_string(&c->cpuset_mems);
383
384 fprintf(f,
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"
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"
410 "%sMemoryLimit: %" PRIu64 "\n"
411 "%sTasksMax: %" PRIu64 "\n"
412 "%sDevicePolicy: %s\n"
413 "%sDisableControllers: %s\n"
414 "%sDelegate: %s\n",
415 prefix, yes_no(c->cpu_accounting),
416 prefix, yes_no(c->io_accounting),
417 prefix, yes_no(c->blockio_accounting),
418 prefix, yes_no(c->memory_accounting),
419 prefix, yes_no(c->tasks_accounting),
420 prefix, yes_no(c->ip_accounting),
421 prefix, c->cpu_weight,
422 prefix, c->startup_cpu_weight,
423 prefix, c->cpu_shares,
424 prefix, c->startup_cpu_shares,
425 prefix, format_timespan(q, sizeof(q), c->cpu_quota_per_sec_usec, 1),
426 prefix, format_timespan(v, sizeof(v), c->cpu_quota_period_usec, 1),
427 prefix, strempty(cpuset_cpus),
428 prefix, strempty(cpuset_mems),
429 prefix, c->io_weight,
430 prefix, c->startup_io_weight,
431 prefix, c->blockio_weight,
432 prefix, c->startup_blockio_weight,
433 prefix, c->default_memory_min,
434 prefix, c->default_memory_low,
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"),
440 prefix, c->memory_limit,
441 prefix, tasks_max_resolve(&c->tasks_max),
442 prefix, cgroup_device_policy_to_string(c->device_policy),
443 prefix, strempty(disable_controllers_str),
444 prefix, yes_no(c->delegate));
445
446 if (c->delegate) {
447 _cleanup_free_ char *t = NULL;
448
449 (void) cg_mask_to_string(c->delegate_controllers, &t);
450
451 fprintf(f, "%sDelegateControllers: %s\n",
452 prefix,
453 strempty(t));
454 }
455
456 LIST_FOREACH(device_allow, a, c->device_allow)
457 fprintf(f,
458 "%sDeviceAllow: %s %s%s%s\n",
459 prefix,
460 a->path,
461 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
462
463 LIST_FOREACH(device_weights, iw, c->io_device_weights)
464 fprintf(f,
465 "%sIODeviceWeight: %s %" PRIu64 "\n",
466 prefix,
467 iw->path,
468 iw->weight);
469
470 LIST_FOREACH(device_latencies, l, c->io_device_latencies)
471 fprintf(f,
472 "%sIODeviceLatencyTargetSec: %s %s\n",
473 prefix,
474 l->path,
475 format_timespan(q, sizeof(q), l->target_usec, 1));
476
477 LIST_FOREACH(device_limits, il, c->io_device_limits) {
478 char buf[FORMAT_BYTES_MAX];
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,
484 "%s%s: %s %s\n",
485 prefix,
486 cgroup_io_limit_type_to_string(type),
487 il->path,
488 format_bytes(buf, sizeof(buf), il->limits[type]));
489 }
490
491 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
492 fprintf(f,
493 "%sBlockIODeviceWeight: %s %" PRIu64,
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
501 if (b->rbps != CGROUP_LIMIT_MAX)
502 fprintf(f,
503 "%sBlockIOReadBandwidth: %s %s\n",
504 prefix,
505 b->path,
506 format_bytes(buf, sizeof(buf), b->rbps));
507 if (b->wbps != CGROUP_LIMIT_MAX)
508 fprintf(f,
509 "%sBlockIOWriteBandwidth: %s %s\n",
510 prefix,
511 b->path,
512 format_bytes(buf, sizeof(buf), b->wbps));
513 }
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);
519 fprintf(f, "%sIPAddressAllow: %s/%u\n", prefix, strnull(k), iaai->prefixlen);
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);
526 fprintf(f, "%sIPAddressDeny: %s/%u\n", prefix, strnull(k), iaai->prefixlen);
527 }
528
529 STRV_FOREACH(path, c->ip_filters_ingress)
530 fprintf(f, "%sIPIngressFilterPath: %s\n", prefix, *path);
531
532 STRV_FOREACH(path, c->ip_filters_egress)
533 fprintf(f, "%sIPEgressFilterPath: %s\n", prefix, *path);
534 }
535
536 int 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),
554 .r = isempty(mode) || strchr(mode, 'r'),
555 .w = isempty(mode) || strchr(mode, 'w'),
556 .m = isempty(mode) || strchr(mode, 'm'),
557 };
558
559 LIST_PREPEND(device_allow, c->device_allow, a);
560 TAKE_PTR(a);
561
562 return 0;
563 }
564
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); \
577 if (c && c->entry##_set) \
578 return c->entry; \
579 \
580 while ((u = UNIT_DEREF(u->slice))) { \
581 c = unit_get_cgroup_context(u); \
582 if (c && c->default_##entry##_set) \
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; \
589 }
590
591 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_low);
592 UNIT_DEFINE_ANCESTOR_MEMORY_LOOKUP(memory_min);
593
594 static 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
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 }
611
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 }
624 }
625
626 static int lookup_block_device(const char *p, dev_t *ret) {
627 dev_t rdev, dev = 0;
628 mode_t mode;
629 int r;
630
631 assert(p);
632 assert(ret);
633
634 r = device_path_parse_major_minor(p, &mode, &rdev);
635 if (r == -ENODEV) { /* not a parsable device node, need to go to disk */
636 struct stat st;
637
638 if (stat(p, &st) < 0)
639 return log_warning_errno(errno, "Couldn't stat device '%s': %m", p);
640
641 mode = st.st_mode;
642 rdev = st.st_rdev;
643 dev = st.st_dev;
644 } else if (r < 0)
645 return log_warning_errno(r, "Failed to parse major/minor from path '%s': %m", p);
646
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))
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 */
654 else {
655 /* If this is btrfs, getting the backing block device is a bit harder */
656 r = btrfs_get_block_device(p, ret);
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)
661 return log_warning_errno(r, "Failed to determine block device backing btrfs file system '%s': %m", p);
662 }
663
664 /* If this is a LUKS/DM device, recursively try to get the originating block device */
665 while (block_get_originating(*ret, ret) > 0);
666
667 /* If this is a partition, try to get the originating block device */
668 (void) block_get_whole_disk(*ret, ret);
669 return 0;
670 }
671
672 static 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
677 static 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
682 static 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
692 static 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
702 usec_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
711 static 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];
727 log_unit_full(u, u->warned_clamping_cpu_quota_period ? LOG_DEBUG : LOG_WARNING,
728 "Clamping CPU interval for cpu.max: period is now %s",
729 format_timespan(v, sizeof(v), new_period, 1));
730 u->warned_clamping_cpu_quota_period = true;
731 }
732
733 return new_period;
734 }
735
736 static void cgroup_apply_unified_cpu_weight(Unit *u, uint64_t weight) {
737 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
738
739 xsprintf(buf, "%" PRIu64 "\n", weight);
740 (void) set_attribute_and_warn(u, "cpu", "cpu.weight", buf);
741 }
742
743 static void cgroup_apply_unified_cpu_quota(Unit *u, usec_t quota, usec_t period) {
744 char buf[(DECIMAL_STR_MAX(usec_t) + 1) * 2 + 1];
745
746 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
747 if (quota != USEC_INFINITY)
748 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
749 MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC), period);
750 else
751 xsprintf(buf, "max " USEC_FMT "\n", period);
752 (void) set_attribute_and_warn(u, "cpu", "cpu.max", buf);
753 }
754
755 static void cgroup_apply_legacy_cpu_shares(Unit *u, uint64_t shares) {
756 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
757
758 xsprintf(buf, "%" PRIu64 "\n", shares);
759 (void) set_attribute_and_warn(u, "cpu", "cpu.shares", buf);
760 }
761
762 static void cgroup_apply_legacy_cpu_quota(Unit *u, usec_t quota, usec_t period) {
763 char buf[DECIMAL_STR_MAX(usec_t) + 2];
764
765 period = cgroup_cpu_adjust_period_and_log(u, period, quota);
766
767 xsprintf(buf, USEC_FMT "\n", period);
768 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_period_us", buf);
769
770 if (quota != USEC_INFINITY) {
771 xsprintf(buf, USEC_FMT "\n", MAX(quota * period / USEC_PER_SEC, USEC_PER_MSEC));
772 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", buf);
773 } else
774 (void) set_attribute_and_warn(u, "cpu", "cpu.cfs_quota_us", "-1\n");
775 }
776
777 static 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
782 static 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
787 static void cgroup_apply_unified_cpuset(Unit *u, const CPUSet *cpus, const char *name) {
788 _cleanup_free_ char *buf = NULL;
789
790 buf = cpu_set_to_range_string(cpus);
791 if (!buf) {
792 log_oom();
793 return;
794 }
795
796 (void) set_attribute_and_warn(u, "cpuset", name, buf);
797 }
798
799 static bool cgroup_context_has_io_config(CGroupContext *c) {
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 ||
804 c->io_device_latencies ||
805 c->io_device_limits;
806 }
807
808 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
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
816 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
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
826 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
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
836 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
837 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
838 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
839 }
840
841 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
842 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
843 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
844 }
845
846 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
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);
856 (void) set_attribute_and_warn(u, "io", "io.weight", buf);
857 }
858
859 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
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);
869 (void) set_attribute_and_warn(u, "blkio", "blkio.weight_device", buf);
870 }
871
872 static 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
886 (void) set_attribute_and_warn(u, "io", "io.latency", buf);
887 }
888
889 static void cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
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;
894 int r;
895
896 r = lookup_block_device(dev_path, &dev);
897 if (r < 0)
898 return;
899
900 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
901 if (limits[type] != cgroup_io_limit_defaults[type])
902 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
903 else
904 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
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]);
909 (void) set_attribute_and_warn(u, "io", "io.max", buf);
910 }
911
912 static void cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
913 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
914 dev_t dev;
915 int r;
916
917 r = lookup_block_device(dev_path, &dev);
918 if (r < 0)
919 return;
920
921 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), rbps);
922 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.read_bps_device", buf);
923
924 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), wbps);
925 (void) set_attribute_and_warn(u, "blkio", "blkio.throttle.write_bps_device", buf);
926 }
927
928 static 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
936 return unit_get_ancestor_memory_min(u) > 0 || unit_get_ancestor_memory_low(u) > 0 ||
937 c->memory_high != CGROUP_LIMIT_MAX || c->memory_max != CGROUP_LIMIT_MAX ||
938 c->memory_swap_max != CGROUP_LIMIT_MAX;
939 }
940
941 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
942 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max\n";
943
944 if (v != CGROUP_LIMIT_MAX)
945 xsprintf(buf, "%" PRIu64 "\n", v);
946
947 (void) set_attribute_and_warn(u, "memory", file, buf);
948 }
949
950 static void cgroup_apply_firewall(Unit *u) {
951 assert(u);
952
953 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
954
955 if (bpf_firewall_compile(u) < 0)
956 return;
957
958 (void) bpf_firewall_load_custom(u);
959 (void) bpf_firewall_install(u);
960 }
961
962 static int cgroup_apply_devices(Unit *u) {
963 _cleanup_(bpf_program_unrefp) BPFProgram *prog = NULL;
964 const char *path;
965 CGroupContext *c;
966 CGroupDeviceAllow *a;
967 CGroupDevicePolicy policy;
968 int r;
969
970 assert_se(c = unit_get_cgroup_context(u));
971 assert_se(path = u->cgroup_path);
972
973 policy = c->device_policy;
974
975 if (cg_all_unified() > 0) {
976 r = bpf_devices_cgroup_init(&prog, policy, c->device_allow);
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
984 if (c->device_allow || policy != CGROUP_DEVICE_POLICY_AUTO)
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_errno(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
993 bool allow_list_static = policy == CGROUP_DEVICE_POLICY_CLOSED ||
994 (policy == CGROUP_DEVICE_POLICY_AUTO && c->device_allow);
995 if (allow_list_static)
996 (void) bpf_devices_allow_list_static(prog, path);
997
998 bool any = allow_list_static;
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';
1009 if (k == 0)
1010 continue;
1011 acc[k++] = 0;
1012
1013 if (path_startswith(a->path, "/dev/"))
1014 r = bpf_devices_allow_list_device(prog, path, a->path, acc);
1015 else if ((val = startswith(a->path, "block-")))
1016 r = bpf_devices_allow_list_major(prog, path, val, 'b', acc);
1017 else if ((val = startswith(a->path, "char-")))
1018 r = bpf_devices_allow_list_major(prog, path, val, 'c', acc);
1019 else {
1020 log_unit_debug(u, "Ignoring device '%s' while writing cgroup attribute.", a->path);
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
1032 but no allow-listing rules (outro would contain an unreachable instruction for successful
1033 return). */
1034 policy = CGROUP_DEVICE_POLICY_STRICT;
1035 }
1036
1037 r = bpf_devices_apply_policy(prog, policy, any, path, &u->bpf_device_control_installed);
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
1051 static void cgroup_context_apply(
1052 Unit *u,
1053 CGroupMask apply_mask,
1054 ManagerState state) {
1055
1056 const char *path;
1057 CGroupContext *c;
1058 bool is_host_root, is_local_root;
1059 int r;
1060
1061 assert(u);
1062
1063 /* Nothing to do? Exit early! */
1064 if (apply_mask == 0)
1065 return;
1066
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);
1071
1072 assert_se(c = unit_get_cgroup_context(u));
1073 assert_se(path = u->cgroup_path);
1074
1075 if (is_local_root) /* Make sure we don't try to display messages with an empty path. */
1076 path = "/";
1077
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. */
1080
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
1084 * containers we want to leave control of these to the container manager (and if cgroup v2 delegation is used
1085 * we couldn't even write to them if we wanted to). */
1086 if ((apply_mask & CGROUP_MASK_CPU) && !is_local_root) {
1087
1088 if (cg_all_unified() > 0) {
1089 uint64_t weight;
1090
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;
1095
1096 shares = cgroup_context_cpu_shares(c, state);
1097 weight = cgroup_cpu_shares_to_weight(shares);
1098
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;
1103
1104 cgroup_apply_unified_cpu_weight(u, weight);
1105 cgroup_apply_unified_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
1106
1107 } else {
1108 uint64_t shares;
1109
1110 if (cgroup_context_has_cpu_weight(c)) {
1111 uint64_t weight;
1112
1113 weight = cgroup_context_cpu_weight(c, state);
1114 shares = cgroup_cpu_weight_to_shares(weight);
1115
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;
1122
1123 cgroup_apply_legacy_cpu_shares(u, shares);
1124 cgroup_apply_legacy_cpu_quota(u, c->cpu_quota_per_sec_usec, c->cpu_quota_period_usec);
1125 }
1126 }
1127
1128 if ((apply_mask & CGROUP_MASK_CPUSET) && !is_local_root) {
1129 cgroup_apply_unified_cpuset(u, &c->cpuset_cpus, "cpuset.cpus");
1130 cgroup_apply_unified_cpuset(u, &c->cpuset_mems, "cpuset.mems");
1131 }
1132
1133 /* The 'io' controller attributes are not exported on the host's root cgroup (being a pure cgroup v2
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;
1140
1141 has_io = cgroup_context_has_io_config(c);
1142 has_blockio = cgroup_context_has_blockio_config(c);
1143
1144 if (has_io)
1145 weight = cgroup_context_io_weight(c, state);
1146 else if (has_blockio) {
1147 uint64_t blkio_weight;
1148
1149 blkio_weight = cgroup_context_blkio_weight(c, state);
1150 weight = cgroup_weight_blkio_to_io(blkio_weight);
1151
1152 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight=%" PRIu64 " as [Startup]IOWeight=%" PRIu64,
1153 blkio_weight, weight);
1154 } else
1155 weight = CGROUP_WEIGHT_DEFAULT;
1156
1157 xsprintf(buf, "default %" PRIu64 "\n", weight);
1158 (void) set_attribute_and_warn(u, "io", "io.weight", buf);
1159
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
1165 if (has_io) {
1166 CGroupIODeviceLatency *latency;
1167 CGroupIODeviceLimit *limit;
1168 CGroupIODeviceWeight *w;
1169
1170 LIST_FOREACH(device_weights, w, c->io_device_weights)
1171 cgroup_apply_io_device_weight(u, w->path, w->weight);
1172
1173 LIST_FOREACH(device_limits, limit, c->io_device_limits)
1174 cgroup_apply_io_device_limit(u, limit->path, limit->limits);
1175
1176 LIST_FOREACH(device_latencies, latency, c->io_device_latencies)
1177 cgroup_apply_io_device_latency(u, latency->path, latency->target_usec);
1178
1179 } else if (has_blockio) {
1180 CGroupBlockIODeviceWeight *w;
1181 CGroupBlockIODeviceBandwidth *b;
1182
1183 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
1184 weight = cgroup_weight_blkio_to_io(w->weight);
1185
1186 log_cgroup_compat(u, "Applying BlockIODeviceWeight=%" PRIu64 " as IODeviceWeight=%" PRIu64 " for %s",
1187 w->weight, weight, w->path);
1188
1189 cgroup_apply_io_device_weight(u, w->path, weight);
1190 }
1191
1192 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
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
1202 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax= for %s",
1203 b->rbps, b->wbps, b->path);
1204
1205 cgroup_apply_io_device_limit(u, b->path, limits);
1206 }
1207 }
1208 }
1209
1210 if (apply_mask & CGROUP_MASK_BLKIO) {
1211 bool has_io, has_blockio;
1212
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) {
1219 char buf[DECIMAL_STR_MAX(uint64_t)+1];
1220 uint64_t weight;
1221
1222 if (has_io) {
1223 uint64_t io_weight;
1224
1225 io_weight = cgroup_context_io_weight(c, state);
1226 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
1227
1228 log_cgroup_compat(u, "Applying [Startup]IOWeight=%" PRIu64 " as [Startup]BlockIOWeight=%" PRIu64,
1229 io_weight, weight);
1230 } else if (has_blockio)
1231 weight = cgroup_context_blkio_weight(c, state);
1232 else
1233 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
1234
1235 xsprintf(buf, "%" PRIu64 "\n", weight);
1236 (void) set_attribute_and_warn(u, "blkio", "blkio.weight", buf);
1237
1238 if (has_io) {
1239 CGroupIODeviceWeight *w;
1240
1241 LIST_FOREACH(device_weights, w, c->io_device_weights) {
1242 weight = cgroup_weight_io_to_blkio(w->weight);
1243
1244 log_cgroup_compat(u, "Applying IODeviceWeight=%" PRIu64 " as BlockIODeviceWeight=%" PRIu64 " for %s",
1245 w->weight, weight, w->path);
1246
1247 cgroup_apply_blkio_device_weight(u, w->path, weight);
1248 }
1249 } else if (has_blockio) {
1250 CGroupBlockIODeviceWeight *w;
1251
1252 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
1253 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
1254 }
1255 }
1256
1257 /* The bandwidth limits are something that make sense to be applied to the host's root but not container
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;
1262
1263 LIST_FOREACH(device_limits, l, c->io_device_limits) {
1264 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth=%" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax= for %s",
1265 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
1266
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;
1271
1272 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
1273 cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps);
1274 }
1275 }
1276 }
1277
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
1280 * want to leave control to the container manager (and if proper cgroup v2 delegation is used we couldn't even
1281 * write to this if we wanted to.) */
1282 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_local_root) {
1283
1284 if (cg_all_unified() > 0) {
1285 uint64_t max, swap_max = CGROUP_LIMIT_MAX;
1286
1287 if (unit_has_unified_memory_config(u)) {
1288 max = c->memory_max;
1289 swap_max = c->memory_swap_max;
1290 } else {
1291 max = c->memory_limit;
1292
1293 if (max != CGROUP_LIMIT_MAX)
1294 log_cgroup_compat(u, "Applying MemoryLimit=%" PRIu64 " as MemoryMax=", max);
1295 }
1296
1297 cgroup_apply_unified_memory_limit(u, "memory.min", unit_get_ancestor_memory_min(u));
1298 cgroup_apply_unified_memory_limit(u, "memory.low", unit_get_ancestor_memory_low(u));
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);
1302
1303 (void) set_attribute_and_warn(u, "memory", "memory.oom.group", one_zero(c->memory_oom_group));
1304
1305 } else {
1306 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
1307 uint64_t val;
1308
1309 if (unit_has_unified_memory_config(u)) {
1310 val = c->memory_max;
1311 log_cgroup_compat(u, "Applying MemoryMax=%" PRIi64 " as MemoryLimit=", val);
1312 } else
1313 val = c->memory_limit;
1314
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);
1321 }
1322 }
1323
1324 /* On cgroup v2 we can apply BPF everywhere. On cgroup v1 we apply it everywhere except for the root of
1325 * containers, where we leave this to the manager */
1326 if ((apply_mask & (CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES)) &&
1327 (is_host_root || cg_all_unified() > 0 || !is_local_root))
1328 (void) cgroup_apply_devices(u);
1329
1330 if (apply_mask & CGROUP_MASK_PIDS) {
1331
1332 if (is_host_root) {
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,
1343 * which is desirable so that there's an official way to release control of the sysctl from
1344 * systemd: set the limit to unbounded and reload. */
1345
1346 if (tasks_max_isset(&c->tasks_max)) {
1347 u->manager->sysctl_pid_max_changed = true;
1348 r = procfs_tasks_set_limit(tasks_max_resolve(&c->tasks_max));
1349 } else if (u->manager->sysctl_pid_max_changed)
1350 r = procfs_tasks_set_limit(TASKS_MAX);
1351 else
1352 r = 0;
1353 if (r < 0)
1354 log_unit_full_errno(u, LOG_LEVEL_CGROUP_WRITE(r), r,
1355 "Failed to write to tasks limit sysctls: %m");
1356 }
1357
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) {
1361 if (tasks_max_isset(&c->tasks_max)) {
1362 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
1363
1364 xsprintf(buf, "%" PRIu64 "\n", tasks_max_resolve(&c->tasks_max));
1365 (void) set_attribute_and_warn(u, "pids", "pids.max", buf);
1366 } else
1367 (void) set_attribute_and_warn(u, "pids", "pids.max", "max\n");
1368 }
1369 }
1370
1371 if (apply_mask & CGROUP_MASK_BPF_FIREWALL)
1372 cgroup_apply_firewall(u);
1373 }
1374
1375 static 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 ||
1386 c->ip_address_deny ||
1387 c->ip_filters_ingress ||
1388 c->ip_filters_egress)
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
1405 static CGroupMask unit_get_cgroup_mask(Unit *u) {
1406 CGroupMask mask = 0;
1407 CGroupContext *c;
1408
1409 assert(u);
1410
1411 c = unit_get_cgroup_context(u);
1412
1413 assert(c);
1414
1415 /* Figure out which controllers we need, based on the cgroup context object */
1416
1417 if (c->cpu_accounting)
1418 mask |= get_cpu_accounting_mask();
1419
1420 if (cgroup_context_has_cpu_weight(c) ||
1421 cgroup_context_has_cpu_shares(c) ||
1422 c->cpu_quota_per_sec_usec != USEC_INFINITY)
1423 mask |= CGROUP_MASK_CPU;
1424
1425 if (c->cpuset_cpus.set || c->cpuset_mems.set)
1426 mask |= CGROUP_MASK_CPUSET;
1427
1428 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
1429 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
1430
1431 if (c->memory_accounting ||
1432 c->memory_limit != CGROUP_LIMIT_MAX ||
1433 unit_has_unified_memory_config(u))
1434 mask |= CGROUP_MASK_MEMORY;
1435
1436 if (c->device_allow ||
1437 c->device_policy != CGROUP_DEVICE_POLICY_AUTO)
1438 mask |= CGROUP_MASK_DEVICES | CGROUP_MASK_BPF_DEVICES;
1439
1440 if (c->tasks_accounting ||
1441 tasks_max_isset(&c->tasks_max))
1442 mask |= CGROUP_MASK_PIDS;
1443
1444 return CGROUP_MASK_EXTEND_JOINED(mask);
1445 }
1446
1447 static CGroupMask unit_get_bpf_mask(Unit *u) {
1448 CGroupMask mask = 0;
1449
1450 /* Figure out which controllers we need, based on the cgroup context, possibly taking into account children
1451 * too. */
1452
1453 if (unit_get_needs_bpf_firewall(u))
1454 mask |= CGROUP_MASK_BPF_FIREWALL;
1455
1456 return mask;
1457 }
1458
1459 CGroupMask unit_get_own_mask(Unit *u) {
1460 CGroupContext *c;
1461
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;
1467
1468 c = unit_get_cgroup_context(u);
1469 if (!c)
1470 return 0;
1471
1472 return unit_get_cgroup_mask(u) | unit_get_bpf_mask(u) | unit_get_delegate_mask(u);
1473 }
1474
1475 CGroupMask 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.
1480 *
1481 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1482
1483 if (!unit_cgroup_delegate(u))
1484 return 0;
1485
1486 if (cg_all_unified() <= 0) {
1487 ExecContext *e;
1488
1489 e = unit_get_exec_context(u);
1490 if (e && !exec_context_maintains_privileges(e))
1491 return 0;
1492 }
1493
1494 assert_se(c = unit_get_cgroup_context(u));
1495 return CGROUP_MASK_EXTEND_JOINED(c->delegate_controllers);
1496 }
1497
1498 static CGroupMask unit_get_subtree_mask(Unit *u) {
1499
1500 /* Returns the mask of this subtree, meaning of the group
1501 * itself and its children. */
1502
1503 return unit_get_own_mask(u) | unit_get_members_mask(u);
1504 }
1505
1506 CGroupMask unit_get_members_mask(Unit *u) {
1507 assert(u);
1508
1509 /* Returns the mask of controllers all of the unit's children require, merged */
1510
1511 if (u->cgroup_members_mask_valid)
1512 return u->cgroup_members_mask; /* Use cached value if possible */
1513
1514 u->cgroup_members_mask = 0;
1515
1516 if (u->type == UNIT_SLICE) {
1517 void *v;
1518 Unit *member;
1519
1520 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE])
1521 if (UNIT_DEREF(member->slice) == u)
1522 u->cgroup_members_mask |= unit_get_subtree_mask(member); /* note that this calls ourselves again, for the children */
1523 }
1524
1525 u->cgroup_members_mask_valid = true;
1526 return u->cgroup_members_mask;
1527 }
1528
1529 CGroupMask unit_get_siblings_mask(Unit *u) {
1530 assert(u);
1531
1532 /* Returns the mask of controllers all of the unit's siblings
1533 * require, i.e. the members mask of the unit's parent slice
1534 * if there is one. */
1535
1536 if (UNIT_ISSET(u->slice))
1537 return unit_get_members_mask(UNIT_DEREF(u->slice));
1538
1539 return unit_get_subtree_mask(u); /* we are the top-level slice */
1540 }
1541
1542 static CGroupMask unit_get_disable_mask(Unit *u) {
1543 CGroupContext *c;
1544
1545 c = unit_get_cgroup_context(u);
1546 if (!c)
1547 return 0;
1548
1549 return c->disable_controllers;
1550 }
1551
1552 CGroupMask unit_get_ancestor_disable_mask(Unit *u) {
1553 CGroupMask mask;
1554
1555 assert(u);
1556 mask = unit_get_disable_mask(u);
1557
1558 /* Returns the mask of controllers which are marked as forcibly
1559 * disabled in any ancestor unit or the unit in question. */
1560
1561 if (UNIT_ISSET(u->slice))
1562 mask |= unit_get_ancestor_disable_mask(UNIT_DEREF(u->slice));
1563
1564 return mask;
1565 }
1566
1567 CGroupMask unit_get_target_mask(Unit *u) {
1568 CGroupMask mask;
1569
1570 /* This returns the cgroup mask of all controllers to enable
1571 * for a specific cgroup, i.e. everything it needs itself,
1572 * plus all that its children need, plus all that its siblings
1573 * need. This is primarily useful on the legacy cgroup
1574 * hierarchy, where we need to duplicate each cgroup in each
1575 * hierarchy that shall be enabled for it. */
1576
1577 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
1578
1579 if (mask & CGROUP_MASK_BPF_FIREWALL & ~u->manager->cgroup_supported)
1580 emit_bpf_firewall_warning(u);
1581
1582 mask &= u->manager->cgroup_supported;
1583 mask &= ~unit_get_ancestor_disable_mask(u);
1584
1585 return mask;
1586 }
1587
1588 CGroupMask unit_get_enable_mask(Unit *u) {
1589 CGroupMask mask;
1590
1591 /* This returns the cgroup mask of all controllers to enable
1592 * for the children of a specific cgroup. This is primarily
1593 * useful for the unified cgroup hierarchy, where each cgroup
1594 * controls which controllers are enabled for its children. */
1595
1596 mask = unit_get_members_mask(u);
1597 mask &= u->manager->cgroup_supported;
1598 mask &= ~unit_get_ancestor_disable_mask(u);
1599
1600 return mask;
1601 }
1602
1603 void unit_invalidate_cgroup_members_masks(Unit *u) {
1604 assert(u);
1605
1606 /* Recurse invalidate the member masks cache all the way up the tree */
1607 u->cgroup_members_mask_valid = false;
1608
1609 if (UNIT_ISSET(u->slice))
1610 unit_invalidate_cgroup_members_masks(UNIT_DEREF(u->slice));
1611 }
1612
1613 const char *unit_get_realized_cgroup_path(Unit *u, CGroupMask mask) {
1614
1615 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
1616
1617 while (u) {
1618
1619 if (u->cgroup_path &&
1620 u->cgroup_realized &&
1621 FLAGS_SET(u->cgroup_realized_mask, mask))
1622 return u->cgroup_path;
1623
1624 u = UNIT_DEREF(u->slice);
1625 }
1626
1627 return NULL;
1628 }
1629
1630 static const char *migrate_callback(CGroupMask mask, void *userdata) {
1631 /* If not realized at all, migrate to root ("").
1632 * It may happen if we're upgrading from older version that didn't clean up.
1633 */
1634 return strempty(unit_get_realized_cgroup_path(userdata, mask));
1635 }
1636
1637 char *unit_default_cgroup_path(const Unit *u) {
1638 _cleanup_free_ char *escaped = NULL, *slice = NULL;
1639 int r;
1640
1641 assert(u);
1642
1643 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1644 return strdup(u->manager->cgroup_root);
1645
1646 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1647 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1648 if (r < 0)
1649 return NULL;
1650 }
1651
1652 escaped = cg_escape(u->id);
1653 if (!escaped)
1654 return NULL;
1655
1656 return path_join(empty_to_root(u->manager->cgroup_root), slice, escaped);
1657 }
1658
1659 int unit_set_cgroup_path(Unit *u, const char *path) {
1660 _cleanup_free_ char *p = NULL;
1661 int r;
1662
1663 assert(u);
1664
1665 if (streq_ptr(u->cgroup_path, path))
1666 return 0;
1667
1668 if (path) {
1669 p = strdup(path);
1670 if (!p)
1671 return -ENOMEM;
1672 }
1673
1674 if (p) {
1675 r = hashmap_put(u->manager->cgroup_unit, p, u);
1676 if (r < 0)
1677 return r;
1678 }
1679
1680 unit_release_cgroup(u);
1681 u->cgroup_path = TAKE_PTR(p);
1682
1683 return 1;
1684 }
1685
1686 int unit_watch_cgroup(Unit *u) {
1687 _cleanup_free_ char *events = NULL;
1688 int r;
1689
1690 assert(u);
1691
1692 /* Watches the "cgroups.events" attribute of this unit's cgroup for "empty" events, but only if
1693 * cgroupv2 is available. */
1694
1695 if (!u->cgroup_path)
1696 return 0;
1697
1698 if (u->cgroup_control_inotify_wd >= 0)
1699 return 0;
1700
1701 /* Only applies to the unified hierarchy */
1702 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1703 if (r < 0)
1704 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1705 if (r == 0)
1706 return 0;
1707
1708 /* No point in watch the top-level slice, it's never going to run empty. */
1709 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1710 return 0;
1711
1712 r = hashmap_ensure_allocated(&u->manager->cgroup_control_inotify_wd_unit, &trivial_hash_ops);
1713 if (r < 0)
1714 return log_oom();
1715
1716 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1717 if (r < 0)
1718 return log_oom();
1719
1720 u->cgroup_control_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1721 if (u->cgroup_control_inotify_wd < 0) {
1722
1723 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
1724 * is not an error */
1725 return 0;
1726
1727 return log_unit_error_errno(u, errno, "Failed to add control inotify watch descriptor for control group %s: %m", u->cgroup_path);
1728 }
1729
1730 r = hashmap_put(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd), u);
1731 if (r < 0)
1732 return log_unit_error_errno(u, r, "Failed to add control inotify watch descriptor to hash map: %m");
1733
1734 return 0;
1735 }
1736
1737 int unit_watch_cgroup_memory(Unit *u) {
1738 _cleanup_free_ char *events = NULL;
1739 CGroupContext *c;
1740 int r;
1741
1742 assert(u);
1743
1744 /* Watches the "memory.events" attribute of this unit's cgroup for "oom_kill" events, but only if
1745 * cgroupv2 is available. */
1746
1747 if (!u->cgroup_path)
1748 return 0;
1749
1750 c = unit_get_cgroup_context(u);
1751 if (!c)
1752 return 0;
1753
1754 /* The "memory.events" attribute is only available if the memory controller is on. Let's hence tie
1755 * this to memory accounting, in a way watching for OOM kills is a form of memory accounting after
1756 * all. */
1757 if (!c->memory_accounting)
1758 return 0;
1759
1760 /* Don't watch inner nodes, as the kernel doesn't report oom_kill events recursively currently, and
1761 * we also don't want to generate a log message for each parent cgroup of a process. */
1762 if (u->type == UNIT_SLICE)
1763 return 0;
1764
1765 if (u->cgroup_memory_inotify_wd >= 0)
1766 return 0;
1767
1768 /* Only applies to the unified hierarchy */
1769 r = cg_all_unified();
1770 if (r < 0)
1771 return log_error_errno(r, "Failed to determine whether the memory controller is unified: %m");
1772 if (r == 0)
1773 return 0;
1774
1775 r = hashmap_ensure_allocated(&u->manager->cgroup_memory_inotify_wd_unit, &trivial_hash_ops);
1776 if (r < 0)
1777 return log_oom();
1778
1779 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "memory.events", &events);
1780 if (r < 0)
1781 return log_oom();
1782
1783 u->cgroup_memory_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1784 if (u->cgroup_memory_inotify_wd < 0) {
1785
1786 if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
1787 * is not an error */
1788 return 0;
1789
1790 return log_unit_error_errno(u, errno, "Failed to add memory inotify watch descriptor for control group %s: %m", u->cgroup_path);
1791 }
1792
1793 r = hashmap_put(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd), u);
1794 if (r < 0)
1795 return log_unit_error_errno(u, r, "Failed to add memory inotify watch descriptor to hash map: %m");
1796
1797 return 0;
1798 }
1799
1800 int unit_pick_cgroup_path(Unit *u) {
1801 _cleanup_free_ char *path = NULL;
1802 int r;
1803
1804 assert(u);
1805
1806 if (u->cgroup_path)
1807 return 0;
1808
1809 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1810 return -EINVAL;
1811
1812 path = unit_default_cgroup_path(u);
1813 if (!path)
1814 return log_oom();
1815
1816 r = unit_set_cgroup_path(u, path);
1817 if (r == -EEXIST)
1818 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1819 if (r < 0)
1820 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1821
1822 return 0;
1823 }
1824
1825 static int unit_update_cgroup(
1826 Unit *u,
1827 CGroupMask target_mask,
1828 CGroupMask enable_mask,
1829 ManagerState state) {
1830
1831 bool created, is_root_slice;
1832 CGroupMask migrate_mask = 0;
1833 int r;
1834
1835 assert(u);
1836
1837 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1838 return 0;
1839
1840 /* Figure out our cgroup path */
1841 r = unit_pick_cgroup_path(u);
1842 if (r < 0)
1843 return r;
1844
1845 /* First, create our own group */
1846 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1847 if (r < 0)
1848 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1849 created = r;
1850
1851 /* Start watching it */
1852 (void) unit_watch_cgroup(u);
1853 (void) unit_watch_cgroup_memory(u);
1854
1855
1856 /* For v2 we preserve enabled controllers in delegated units, adjust others,
1857 * for v1 we figure out which controller hierarchies need migration. */
1858 if (created || !u->cgroup_realized || !unit_cgroup_delegate(u)) {
1859 CGroupMask result_mask = 0;
1860
1861 /* Enable all controllers we need */
1862 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path, &result_mask);
1863 if (r < 0)
1864 log_unit_warning_errno(u, r, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
1865
1866 /* Remember what's actually enabled now */
1867 u->cgroup_enabled_mask = result_mask;
1868
1869 migrate_mask = u->cgroup_realized_mask ^ target_mask;
1870 }
1871
1872 /* Keep track that this is now realized */
1873 u->cgroup_realized = true;
1874 u->cgroup_realized_mask = target_mask;
1875
1876 /* Migrate processes in controller hierarchies both downwards (enabling) and upwards (disabling).
1877 *
1878 * Unnecessary controller cgroups are trimmed (after emptied by upward migration).
1879 * We perform migration also with whole slices for cases when users don't care about leave
1880 * granularity. Since delegated_mask is subset of target mask, we won't trim slice subtree containing
1881 * delegated units.
1882 */
1883 if (cg_all_unified() == 0) {
1884 r = cg_migrate_v1_controllers(u->manager->cgroup_supported, migrate_mask, u->cgroup_path, migrate_callback, u);
1885 if (r < 0)
1886 log_unit_warning_errno(u, r, "Failed to migrate controller cgroups from %s, ignoring: %m", u->cgroup_path);
1887
1888 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1889 r = cg_trim_v1_controllers(u->manager->cgroup_supported, ~target_mask, u->cgroup_path, !is_root_slice);
1890 if (r < 0)
1891 log_unit_warning_errno(u, r, "Failed to delete controller cgroups %s, ignoring: %m", u->cgroup_path);
1892 }
1893
1894 /* Set attributes */
1895 cgroup_context_apply(u, target_mask, state);
1896 cgroup_xattr_apply(u);
1897
1898 return 0;
1899 }
1900
1901 static int unit_attach_pid_to_cgroup_via_bus(Unit *u, pid_t pid, const char *suffix_path) {
1902 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1903 char *pp;
1904 int r;
1905
1906 assert(u);
1907
1908 if (MANAGER_IS_SYSTEM(u->manager))
1909 return -EINVAL;
1910
1911 if (!u->manager->system_bus)
1912 return -EIO;
1913
1914 if (!u->cgroup_path)
1915 return -EINVAL;
1916
1917 /* Determine this unit's cgroup path relative to our cgroup root */
1918 pp = path_startswith(u->cgroup_path, u->manager->cgroup_root);
1919 if (!pp)
1920 return -EINVAL;
1921
1922 pp = strjoina("/", pp, suffix_path);
1923 path_simplify(pp, false);
1924
1925 r = sd_bus_call_method(u->manager->system_bus,
1926 "org.freedesktop.systemd1",
1927 "/org/freedesktop/systemd1",
1928 "org.freedesktop.systemd1.Manager",
1929 "AttachProcessesToUnit",
1930 &error, NULL,
1931 "ssau",
1932 NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
1933 if (r < 0)
1934 return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
1935
1936 return 0;
1937 }
1938
1939 int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
1940 CGroupMask delegated_mask;
1941 const char *p;
1942 void *pidp;
1943 int r, q;
1944
1945 assert(u);
1946
1947 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1948 return -EINVAL;
1949
1950 if (set_isempty(pids))
1951 return 0;
1952
1953 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
1954 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
1955 r = bpf_firewall_load_custom(u);
1956 if (r < 0)
1957 return r;
1958
1959 r = unit_realize_cgroup(u);
1960 if (r < 0)
1961 return r;
1962
1963 if (isempty(suffix_path))
1964 p = u->cgroup_path;
1965 else
1966 p = prefix_roota(u->cgroup_path, suffix_path);
1967
1968 delegated_mask = unit_get_delegate_mask(u);
1969
1970 r = 0;
1971 SET_FOREACH(pidp, pids) {
1972 pid_t pid = PTR_TO_PID(pidp);
1973 CGroupController c;
1974
1975 /* First, attach the PID to the main cgroup hierarchy */
1976 q = cg_attach(SYSTEMD_CGROUP_CONTROLLER, p, pid);
1977 if (q < 0) {
1978 log_unit_debug_errno(u, q, "Couldn't move process " PID_FMT " to requested cgroup '%s': %m", pid, p);
1979
1980 if (MANAGER_IS_USER(u->manager) && ERRNO_IS_PRIVILEGE(q)) {
1981 int z;
1982
1983 /* If we are in a user instance, and we can't move the process ourselves due to
1984 * permission problems, let's ask the system instance about it instead. Since it's more
1985 * privileged it might be able to move the process across the leaves of a subtree who's
1986 * top node is not owned by us. */
1987
1988 z = unit_attach_pid_to_cgroup_via_bus(u, pid, suffix_path);
1989 if (z < 0)
1990 log_unit_debug_errno(u, z, "Couldn't move process " PID_FMT " to requested cgroup '%s' via the system bus either: %m", pid, p);
1991 else
1992 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1993 }
1994
1995 if (r >= 0)
1996 r = q; /* Remember first error */
1997
1998 continue;
1999 }
2000
2001 q = cg_all_unified();
2002 if (q < 0)
2003 return q;
2004 if (q > 0)
2005 continue;
2006
2007 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
2008 * innermost realized one */
2009
2010 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2011 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2012 const char *realized;
2013
2014 if (!(u->manager->cgroup_supported & bit))
2015 continue;
2016
2017 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
2018 if (delegated_mask & u->cgroup_realized_mask & bit) {
2019 q = cg_attach(cgroup_controller_to_string(c), p, pid);
2020 if (q >= 0)
2021 continue; /* Success! */
2022
2023 log_unit_debug_errno(u, q, "Failed to attach PID " PID_FMT " to requested cgroup %s in controller %s, falling back to unit's cgroup: %m",
2024 pid, p, cgroup_controller_to_string(c));
2025 }
2026
2027 /* So this controller is either not delegate or realized, or something else weird happened. In
2028 * that case let's attach the PID at least to the closest cgroup up the tree that is
2029 * realized. */
2030 realized = unit_get_realized_cgroup_path(u, bit);
2031 if (!realized)
2032 continue; /* Not even realized in the root slice? Then let's not bother */
2033
2034 q = cg_attach(cgroup_controller_to_string(c), realized, pid);
2035 if (q < 0)
2036 log_unit_debug_errno(u, q, "Failed to attach PID " PID_FMT " to realized cgroup %s in controller %s, ignoring: %m",
2037 pid, realized, cgroup_controller_to_string(c));
2038 }
2039 }
2040
2041 return r;
2042 }
2043
2044 static bool unit_has_mask_realized(
2045 Unit *u,
2046 CGroupMask target_mask,
2047 CGroupMask enable_mask) {
2048
2049 assert(u);
2050
2051 /* Returns true if this unit is fully realized. We check four things:
2052 *
2053 * 1. Whether the cgroup was created at all
2054 * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
2055 * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
2056 * 4. Whether the invalidation mask is currently zero
2057 *
2058 * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
2059 * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
2060 * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
2061 * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
2062 * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
2063 * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
2064 * simply don't matter. */
2065
2066 return u->cgroup_realized &&
2067 ((u->cgroup_realized_mask ^ target_mask) & CGROUP_MASK_V1) == 0 &&
2068 ((u->cgroup_enabled_mask ^ enable_mask) & CGROUP_MASK_V2) == 0 &&
2069 u->cgroup_invalidated_mask == 0;
2070 }
2071
2072 static bool unit_has_mask_disables_realized(
2073 Unit *u,
2074 CGroupMask target_mask,
2075 CGroupMask enable_mask) {
2076
2077 assert(u);
2078
2079 /* Returns true if all controllers which should be disabled are indeed disabled.
2080 *
2081 * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
2082 * already removed. */
2083
2084 return !u->cgroup_realized ||
2085 (FLAGS_SET(u->cgroup_realized_mask, target_mask & CGROUP_MASK_V1) &&
2086 FLAGS_SET(u->cgroup_enabled_mask, enable_mask & CGROUP_MASK_V2));
2087 }
2088
2089 static bool unit_has_mask_enables_realized(
2090 Unit *u,
2091 CGroupMask target_mask,
2092 CGroupMask enable_mask) {
2093
2094 assert(u);
2095
2096 /* Returns true if all controllers which should be enabled are indeed enabled.
2097 *
2098 * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
2099 * we want to add is already added. */
2100
2101 return u->cgroup_realized &&
2102 ((u->cgroup_realized_mask | target_mask) & CGROUP_MASK_V1) == (u->cgroup_realized_mask & CGROUP_MASK_V1) &&
2103 ((u->cgroup_enabled_mask | enable_mask) & CGROUP_MASK_V2) == (u->cgroup_enabled_mask & CGROUP_MASK_V2);
2104 }
2105
2106 static void unit_add_to_cgroup_realize_queue(Unit *u) {
2107 assert(u);
2108
2109 if (u->in_cgroup_realize_queue)
2110 return;
2111
2112 LIST_APPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2113 u->in_cgroup_realize_queue = true;
2114 }
2115
2116 static void unit_remove_from_cgroup_realize_queue(Unit *u) {
2117 assert(u);
2118
2119 if (!u->in_cgroup_realize_queue)
2120 return;
2121
2122 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
2123 u->in_cgroup_realize_queue = false;
2124 }
2125
2126 /* Controllers can only be enabled breadth-first, from the root of the
2127 * hierarchy downwards to the unit in question. */
2128 static int unit_realize_cgroup_now_enable(Unit *u, ManagerState state) {
2129 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2130 int r;
2131
2132 assert(u);
2133
2134 /* First go deal with this unit's parent, or we won't be able to enable
2135 * any new controllers at this layer. */
2136 if (UNIT_ISSET(u->slice)) {
2137 r = unit_realize_cgroup_now_enable(UNIT_DEREF(u->slice), state);
2138 if (r < 0)
2139 return r;
2140 }
2141
2142 target_mask = unit_get_target_mask(u);
2143 enable_mask = unit_get_enable_mask(u);
2144
2145 /* We can only enable in this direction, don't try to disable anything.
2146 */
2147 if (unit_has_mask_enables_realized(u, target_mask, enable_mask))
2148 return 0;
2149
2150 new_target_mask = u->cgroup_realized_mask | target_mask;
2151 new_enable_mask = u->cgroup_enabled_mask | enable_mask;
2152
2153 return unit_update_cgroup(u, new_target_mask, new_enable_mask, state);
2154 }
2155
2156 /* Controllers can only be disabled depth-first, from the leaves of the
2157 * hierarchy upwards to the unit in question. */
2158 static int unit_realize_cgroup_now_disable(Unit *u, ManagerState state) {
2159 Unit *m;
2160 void *v;
2161
2162 assert(u);
2163
2164 if (u->type != UNIT_SLICE)
2165 return 0;
2166
2167 HASHMAP_FOREACH_KEY(v, m, u->dependencies[UNIT_BEFORE]) {
2168 CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
2169 int r;
2170
2171 if (UNIT_DEREF(m->slice) != u)
2172 continue;
2173
2174 /* The cgroup for this unit might not actually be fully
2175 * realised yet, in which case it isn't holding any controllers
2176 * open anyway. */
2177 if (!m->cgroup_realized)
2178 continue;
2179
2180 /* We must disable those below us first in order to release the
2181 * controller. */
2182 if (m->type == UNIT_SLICE)
2183 (void) unit_realize_cgroup_now_disable(m, state);
2184
2185 target_mask = unit_get_target_mask(m);
2186 enable_mask = unit_get_enable_mask(m);
2187
2188 /* We can only disable in this direction, don't try to enable
2189 * anything. */
2190 if (unit_has_mask_disables_realized(m, target_mask, enable_mask))
2191 continue;
2192
2193 new_target_mask = m->cgroup_realized_mask & target_mask;
2194 new_enable_mask = m->cgroup_enabled_mask & enable_mask;
2195
2196 r = unit_update_cgroup(m, new_target_mask, new_enable_mask, state);
2197 if (r < 0)
2198 return r;
2199 }
2200
2201 return 0;
2202 }
2203
2204 /* Check if necessary controllers and attributes for a unit are in place.
2205 *
2206 * - If so, do nothing.
2207 * - If not, create paths, move processes over, and set attributes.
2208 *
2209 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
2210 * a depth-first way. As such the process looks like this:
2211 *
2212 * Suppose we have a cgroup hierarchy which looks like this:
2213 *
2214 * root
2215 * / \
2216 * / \
2217 * / \
2218 * a b
2219 * / \ / \
2220 * / \ / \
2221 * c d e f
2222 * / \ / \ / \ / \
2223 * h i j k l m n o
2224 *
2225 * 1. We want to realise cgroup "d" now.
2226 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
2227 * 3. cgroup "k" just started requesting the memory controller.
2228 *
2229 * To make this work we must do the following in order:
2230 *
2231 * 1. Disable CPU controller in k, j
2232 * 2. Disable CPU controller in d
2233 * 3. Enable memory controller in root
2234 * 4. Enable memory controller in a
2235 * 5. Enable memory controller in d
2236 * 6. Enable memory controller in k
2237 *
2238 * Notice that we need to touch j in one direction, but not the other. We also
2239 * don't go beyond d when disabling -- it's up to "a" to get realized if it
2240 * wants to disable further. The basic rules are therefore:
2241 *
2242 * - If you're disabling something, you need to realise all of the cgroups from
2243 * your recursive descendants to the root. This starts from the leaves.
2244 * - If you're enabling something, you need to realise from the root cgroup
2245 * downwards, but you don't need to iterate your recursive descendants.
2246 *
2247 * Returns 0 on success and < 0 on failure. */
2248 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
2249 CGroupMask target_mask, enable_mask;
2250 int r;
2251
2252 assert(u);
2253
2254 unit_remove_from_cgroup_realize_queue(u);
2255
2256 target_mask = unit_get_target_mask(u);
2257 enable_mask = unit_get_enable_mask(u);
2258
2259 if (unit_has_mask_realized(u, target_mask, enable_mask))
2260 return 0;
2261
2262 /* Disable controllers below us, if there are any */
2263 r = unit_realize_cgroup_now_disable(u, state);
2264 if (r < 0)
2265 return r;
2266
2267 /* Enable controllers above us, if there are any */
2268 if (UNIT_ISSET(u->slice)) {
2269 r = unit_realize_cgroup_now_enable(UNIT_DEREF(u->slice), state);
2270 if (r < 0)
2271 return r;
2272 }
2273
2274 /* Now actually deal with the cgroup we were trying to realise and set attributes */
2275 r = unit_update_cgroup(u, target_mask, enable_mask, state);
2276 if (r < 0)
2277 return r;
2278
2279 /* Now, reset the invalidation mask */
2280 u->cgroup_invalidated_mask = 0;
2281 return 0;
2282 }
2283
2284 unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
2285 ManagerState state;
2286 unsigned n = 0;
2287 Unit *i;
2288 int r;
2289
2290 assert(m);
2291
2292 state = manager_state(m);
2293
2294 while ((i = m->cgroup_realize_queue)) {
2295 assert(i->in_cgroup_realize_queue);
2296
2297 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
2298 /* Maybe things changed, and the unit is not actually active anymore? */
2299 unit_remove_from_cgroup_realize_queue(i);
2300 continue;
2301 }
2302
2303 r = unit_realize_cgroup_now(i, state);
2304 if (r < 0)
2305 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
2306
2307 n++;
2308 }
2309
2310 return n;
2311 }
2312
2313 void unit_add_family_to_cgroup_realize_queue(Unit *u) {
2314 assert(u);
2315 assert(u->type == UNIT_SLICE);
2316
2317 /* Family of a unit for is defined as (immediate) children of the unit and immediate children of all
2318 * its ancestors.
2319 *
2320 * Ideally we would enqueue ancestor path only (bottom up). However, on cgroup-v1 scheduling becomes
2321 * very weird if two units that own processes reside in the same slice, but one is realized in the
2322 * "cpu" hierarchy and one is not (for example because one has CPUWeight= set and the other does
2323 * not), because that means individual processes need to be scheduled against whole cgroups. Let's
2324 * avoid this asymmetry by always ensuring that siblings of a unit are always realized in their v1
2325 * controller hierarchies too (if unit requires the controller to be realized).
2326 *
2327 * The function must invalidate cgroup_members_mask of all ancestors in order to calculate up to date
2328 * masks. */
2329
2330 do {
2331 Unit *m;
2332 void *v;
2333
2334 /* Children of u likely changed when we're called */
2335 u->cgroup_members_mask_valid = false;
2336
2337 HASHMAP_FOREACH_KEY(v, m, u->dependencies[UNIT_BEFORE]) {
2338 /* Skip units that have a dependency on the slice but aren't actually in it. */
2339 if (UNIT_DEREF(m->slice) != u)
2340 continue;
2341
2342 /* No point in doing cgroup application for units without active processes. */
2343 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
2344 continue;
2345
2346 /* We only enqueue siblings if they were realized once at least, in the main
2347 * hierarchy. */
2348 if (!m->cgroup_realized)
2349 continue;
2350
2351 /* If the unit doesn't need any new controllers and has current ones realized, it
2352 * doesn't need any changes. */
2353 if (unit_has_mask_realized(m,
2354 unit_get_target_mask(m),
2355 unit_get_enable_mask(m)))
2356 continue;
2357
2358 unit_add_to_cgroup_realize_queue(m);
2359 }
2360
2361 /* Parent comes after children */
2362 unit_add_to_cgroup_realize_queue(u);
2363 } while ((u = UNIT_DEREF(u->slice)));
2364 }
2365
2366 int unit_realize_cgroup(Unit *u) {
2367 assert(u);
2368
2369 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2370 return 0;
2371
2372 /* So, here's the deal: when realizing the cgroups for this unit, we need to first create all
2373 * parents, but there's more actually: for the weight-based controllers we also need to make sure
2374 * that all our siblings (i.e. units that are in the same slice as we are) have cgroups, too. On the
2375 * other hand, when a controller is removed from realized set, it may become unnecessary in siblings
2376 * and ancestors and they should be (de)realized too.
2377 *
2378 * This call will defer work on the siblings and derealized ancestors to the next event loop
2379 * iteration and synchronously creates the parent cgroups (unit_realize_cgroup_now). */
2380
2381 if (UNIT_ISSET(u->slice))
2382 unit_add_family_to_cgroup_realize_queue(UNIT_DEREF(u->slice));
2383
2384 /* And realize this one now (and apply the values) */
2385 return unit_realize_cgroup_now(u, manager_state(u->manager));
2386 }
2387
2388 void unit_release_cgroup(Unit *u) {
2389 assert(u);
2390
2391 /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
2392 * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
2393
2394 if (u->cgroup_path) {
2395 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
2396 u->cgroup_path = mfree(u->cgroup_path);
2397 }
2398
2399 if (u->cgroup_control_inotify_wd >= 0) {
2400 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_control_inotify_wd) < 0)
2401 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);
2402
2403 (void) hashmap_remove(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(u->cgroup_control_inotify_wd));
2404 u->cgroup_control_inotify_wd = -1;
2405 }
2406
2407 if (u->cgroup_memory_inotify_wd >= 0) {
2408 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_memory_inotify_wd) < 0)
2409 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);
2410
2411 (void) hashmap_remove(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(u->cgroup_memory_inotify_wd));
2412 u->cgroup_memory_inotify_wd = -1;
2413 }
2414 }
2415
2416 void unit_prune_cgroup(Unit *u) {
2417 int r;
2418 bool is_root_slice;
2419
2420 assert(u);
2421
2422 /* Removes the cgroup, if empty and possible, and stops watching it. */
2423
2424 if (!u->cgroup_path)
2425 return;
2426
2427 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
2428
2429 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
2430
2431 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
2432 if (r < 0)
2433 /* One reason we could have failed here is, that the cgroup still contains a process.
2434 * However, if the cgroup becomes removable at a later time, it might be removed when
2435 * the containing slice is stopped. So even if we failed now, this unit shouldn't assume
2436 * that the cgroup is still realized the next time it is started. Do not return early
2437 * on error, continue cleanup. */
2438 log_unit_full_errno(u, r == -EBUSY ? LOG_DEBUG : LOG_WARNING, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
2439
2440 if (is_root_slice)
2441 return;
2442
2443 unit_release_cgroup(u);
2444
2445 u->cgroup_realized = false;
2446 u->cgroup_realized_mask = 0;
2447 u->cgroup_enabled_mask = 0;
2448
2449 u->bpf_device_control_installed = bpf_program_unref(u->bpf_device_control_installed);
2450 }
2451
2452 int unit_search_main_pid(Unit *u, pid_t *ret) {
2453 _cleanup_fclose_ FILE *f = NULL;
2454 pid_t pid = 0, npid;
2455 int r;
2456
2457 assert(u);
2458 assert(ret);
2459
2460 if (!u->cgroup_path)
2461 return -ENXIO;
2462
2463 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
2464 if (r < 0)
2465 return r;
2466
2467 while (cg_read_pid(f, &npid) > 0) {
2468
2469 if (npid == pid)
2470 continue;
2471
2472 if (pid_is_my_child(npid) == 0)
2473 continue;
2474
2475 if (pid != 0)
2476 /* Dang, there's more than one daemonized PID
2477 in this group, so we don't know what process
2478 is the main process. */
2479
2480 return -ENODATA;
2481
2482 pid = npid;
2483 }
2484
2485 *ret = pid;
2486 return 0;
2487 }
2488
2489 static int unit_watch_pids_in_path(Unit *u, const char *path) {
2490 _cleanup_closedir_ DIR *d = NULL;
2491 _cleanup_fclose_ FILE *f = NULL;
2492 int ret = 0, r;
2493
2494 assert(u);
2495 assert(path);
2496
2497 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
2498 if (r < 0)
2499 ret = r;
2500 else {
2501 pid_t pid;
2502
2503 while ((r = cg_read_pid(f, &pid)) > 0) {
2504 r = unit_watch_pid(u, pid, false);
2505 if (r < 0 && ret >= 0)
2506 ret = r;
2507 }
2508
2509 if (r < 0 && ret >= 0)
2510 ret = r;
2511 }
2512
2513 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
2514 if (r < 0) {
2515 if (ret >= 0)
2516 ret = r;
2517 } else {
2518 char *fn;
2519
2520 while ((r = cg_read_subgroup(d, &fn)) > 0) {
2521 _cleanup_free_ char *p = NULL;
2522
2523 p = path_join(empty_to_root(path), fn);
2524 free(fn);
2525
2526 if (!p)
2527 return -ENOMEM;
2528
2529 r = unit_watch_pids_in_path(u, p);
2530 if (r < 0 && ret >= 0)
2531 ret = r;
2532 }
2533
2534 if (r < 0 && ret >= 0)
2535 ret = r;
2536 }
2537
2538 return ret;
2539 }
2540
2541 int unit_synthesize_cgroup_empty_event(Unit *u) {
2542 int r;
2543
2544 assert(u);
2545
2546 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
2547 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
2548 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
2549
2550 if (!u->cgroup_path)
2551 return -ENOENT;
2552
2553 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2554 if (r < 0)
2555 return r;
2556 if (r > 0) /* On unified we have reliable notifications, and don't need this */
2557 return 0;
2558
2559 if (!set_isempty(u->pids))
2560 return 0;
2561
2562 unit_add_to_cgroup_empty_queue(u);
2563 return 0;
2564 }
2565
2566 int unit_watch_all_pids(Unit *u) {
2567 int r;
2568
2569 assert(u);
2570
2571 /* Adds all PIDs from our cgroup to the set of PIDs we
2572 * watch. This is a fallback logic for cases where we do not
2573 * get reliable cgroup empty notifications: we try to use
2574 * SIGCHLD as replacement. */
2575
2576 if (!u->cgroup_path)
2577 return -ENOENT;
2578
2579 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2580 if (r < 0)
2581 return r;
2582 if (r > 0) /* On unified we can use proper notifications */
2583 return 0;
2584
2585 return unit_watch_pids_in_path(u, u->cgroup_path);
2586 }
2587
2588 static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
2589 Manager *m = userdata;
2590 Unit *u;
2591 int r;
2592
2593 assert(s);
2594 assert(m);
2595
2596 u = m->cgroup_empty_queue;
2597 if (!u)
2598 return 0;
2599
2600 assert(u->in_cgroup_empty_queue);
2601 u->in_cgroup_empty_queue = false;
2602 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
2603
2604 if (m->cgroup_empty_queue) {
2605 /* More stuff queued, let's make sure we remain enabled */
2606 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
2607 if (r < 0)
2608 log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
2609 }
2610
2611 unit_add_to_gc_queue(u);
2612
2613 if (UNIT_VTABLE(u)->notify_cgroup_empty)
2614 UNIT_VTABLE(u)->notify_cgroup_empty(u);
2615
2616 return 0;
2617 }
2618
2619 void unit_add_to_cgroup_empty_queue(Unit *u) {
2620 int r;
2621
2622 assert(u);
2623
2624 /* Note that there are four different ways how cgroup empty events reach us:
2625 *
2626 * 1. On the unified hierarchy we get an inotify event on the cgroup
2627 *
2628 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2629 *
2630 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2631 *
2632 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2633 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2634 *
2635 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2636 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2637 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2638 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2639 * case for scope units). */
2640
2641 if (u->in_cgroup_empty_queue)
2642 return;
2643
2644 /* Let's verify that the cgroup is really empty */
2645 if (!u->cgroup_path)
2646 return;
2647
2648 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
2649 if (r < 0) {
2650 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", u->cgroup_path);
2651 return;
2652 }
2653 if (r == 0)
2654 return;
2655
2656 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
2657 u->in_cgroup_empty_queue = true;
2658
2659 /* Trigger the defer event */
2660 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
2661 if (r < 0)
2662 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
2663 }
2664
2665 static void unit_remove_from_cgroup_empty_queue(Unit *u) {
2666 assert(u);
2667
2668 if (!u->in_cgroup_empty_queue)
2669 return;
2670
2671 LIST_REMOVE(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
2672 u->in_cgroup_empty_queue = false;
2673 }
2674
2675 int unit_check_oom(Unit *u) {
2676 _cleanup_free_ char *oom_kill = NULL;
2677 bool increased;
2678 uint64_t c;
2679 int r;
2680
2681 if (!u->cgroup_path)
2682 return 0;
2683
2684 r = cg_get_keyed_attribute("memory", u->cgroup_path, "memory.events", STRV_MAKE("oom_kill"), &oom_kill);
2685 if (r < 0)
2686 return log_unit_debug_errno(u, r, "Failed to read oom_kill field of memory.events cgroup attribute: %m");
2687
2688 r = safe_atou64(oom_kill, &c);
2689 if (r < 0)
2690 return log_unit_debug_errno(u, r, "Failed to parse oom_kill field: %m");
2691
2692 increased = c > u->oom_kill_last;
2693 u->oom_kill_last = c;
2694
2695 if (!increased)
2696 return 0;
2697
2698 log_struct(LOG_NOTICE,
2699 "MESSAGE_ID=" SD_MESSAGE_UNIT_OUT_OF_MEMORY_STR,
2700 LOG_UNIT_ID(u),
2701 LOG_UNIT_INVOCATION_ID(u),
2702 LOG_UNIT_MESSAGE(u, "A process of this unit has been killed by the OOM killer."));
2703
2704 if (UNIT_VTABLE(u)->notify_cgroup_oom)
2705 UNIT_VTABLE(u)->notify_cgroup_oom(u);
2706
2707 return 1;
2708 }
2709
2710 static int on_cgroup_oom_event(sd_event_source *s, void *userdata) {
2711 Manager *m = userdata;
2712 Unit *u;
2713 int r;
2714
2715 assert(s);
2716 assert(m);
2717
2718 u = m->cgroup_oom_queue;
2719 if (!u)
2720 return 0;
2721
2722 assert(u->in_cgroup_oom_queue);
2723 u->in_cgroup_oom_queue = false;
2724 LIST_REMOVE(cgroup_oom_queue, m->cgroup_oom_queue, u);
2725
2726 if (m->cgroup_oom_queue) {
2727 /* More stuff queued, let's make sure we remain enabled */
2728 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
2729 if (r < 0)
2730 log_debug_errno(r, "Failed to reenable cgroup oom event source, ignoring: %m");
2731 }
2732
2733 (void) unit_check_oom(u);
2734 return 0;
2735 }
2736
2737 static void unit_add_to_cgroup_oom_queue(Unit *u) {
2738 int r;
2739
2740 assert(u);
2741
2742 if (u->in_cgroup_oom_queue)
2743 return;
2744 if (!u->cgroup_path)
2745 return;
2746
2747 LIST_PREPEND(cgroup_oom_queue, u->manager->cgroup_oom_queue, u);
2748 u->in_cgroup_oom_queue = true;
2749
2750 /* Trigger the defer event */
2751 if (!u->manager->cgroup_oom_event_source) {
2752 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
2753
2754 r = sd_event_add_defer(u->manager->event, &s, on_cgroup_oom_event, u->manager);
2755 if (r < 0) {
2756 log_error_errno(r, "Failed to create cgroup oom event source: %m");
2757 return;
2758 }
2759
2760 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_NORMAL-8);
2761 if (r < 0) {
2762 log_error_errno(r, "Failed to set priority of cgroup oom event source: %m");
2763 return;
2764 }
2765
2766 (void) sd_event_source_set_description(s, "cgroup-oom");
2767 u->manager->cgroup_oom_event_source = TAKE_PTR(s);
2768 }
2769
2770 r = sd_event_source_set_enabled(u->manager->cgroup_oom_event_source, SD_EVENT_ONESHOT);
2771 if (r < 0)
2772 log_error_errno(r, "Failed to enable cgroup oom event source: %m");
2773 }
2774
2775 static int unit_check_cgroup_events(Unit *u) {
2776 char *values[2] = {};
2777 int r;
2778
2779 assert(u);
2780
2781 r = cg_get_keyed_attribute_graceful(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events",
2782 STRV_MAKE("populated", "frozen"), values);
2783 if (r < 0)
2784 return r;
2785
2786 /* The cgroup.events notifications can be merged together so act as we saw the given state for the
2787 * first time. The functions we call to handle given state are idempotent, which makes them
2788 * effectively remember the previous state. */
2789 if (values[0]) {
2790 if (streq(values[0], "1"))
2791 unit_remove_from_cgroup_empty_queue(u);
2792 else
2793 unit_add_to_cgroup_empty_queue(u);
2794 }
2795
2796 /* Disregard freezer state changes due to operations not initiated by us */
2797 if (values[1] && IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_THAWING)) {
2798 if (streq(values[1], "0"))
2799 unit_thawed(u);
2800 else
2801 unit_frozen(u);
2802 }
2803
2804 free(values[0]);
2805 free(values[1]);
2806
2807 return 0;
2808 }
2809
2810 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2811 Manager *m = userdata;
2812
2813 assert(s);
2814 assert(fd >= 0);
2815 assert(m);
2816
2817 for (;;) {
2818 union inotify_event_buffer buffer;
2819 struct inotify_event *e;
2820 ssize_t l;
2821
2822 l = read(fd, &buffer, sizeof(buffer));
2823 if (l < 0) {
2824 if (IN_SET(errno, EINTR, EAGAIN))
2825 return 0;
2826
2827 return log_error_errno(errno, "Failed to read control group inotify events: %m");
2828 }
2829
2830 FOREACH_INOTIFY_EVENT(e, buffer, l) {
2831 Unit *u;
2832
2833 if (e->wd < 0)
2834 /* Queue overflow has no watch descriptor */
2835 continue;
2836
2837 if (e->mask & IN_IGNORED)
2838 /* The watch was just removed */
2839 continue;
2840
2841 /* Note that inotify might deliver events for a watch even after it was removed,
2842 * because it was queued before the removal. Let's ignore this here safely. */
2843
2844 u = hashmap_get(m->cgroup_control_inotify_wd_unit, INT_TO_PTR(e->wd));
2845 if (u)
2846 unit_check_cgroup_events(u);
2847
2848 u = hashmap_get(m->cgroup_memory_inotify_wd_unit, INT_TO_PTR(e->wd));
2849 if (u)
2850 unit_add_to_cgroup_oom_queue(u);
2851 }
2852 }
2853 }
2854
2855 static int cg_bpf_mask_supported(CGroupMask *ret) {
2856 CGroupMask mask = 0;
2857 int r;
2858
2859 /* BPF-based firewall */
2860 r = bpf_firewall_supported();
2861 if (r > 0)
2862 mask |= CGROUP_MASK_BPF_FIREWALL;
2863
2864 /* BPF-based device access control */
2865 r = bpf_devices_supported();
2866 if (r > 0)
2867 mask |= CGROUP_MASK_BPF_DEVICES;
2868
2869 *ret = mask;
2870 return 0;
2871 }
2872
2873 int manager_setup_cgroup(Manager *m) {
2874 _cleanup_free_ char *path = NULL;
2875 const char *scope_path;
2876 CGroupController c;
2877 int r, all_unified;
2878 CGroupMask mask;
2879 char *e;
2880
2881 assert(m);
2882
2883 /* 1. Determine hierarchy */
2884 m->cgroup_root = mfree(m->cgroup_root);
2885 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
2886 if (r < 0)
2887 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
2888
2889 /* Chop off the init scope, if we are already located in it */
2890 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2891
2892 /* LEGACY: Also chop off the system slice if we are in
2893 * it. This is to support live upgrades from older systemd
2894 * versions where PID 1 was moved there. Also see
2895 * cg_get_root_path(). */
2896 if (!e && MANAGER_IS_SYSTEM(m)) {
2897 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
2898 if (!e)
2899 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
2900 }
2901 if (e)
2902 *e = 0;
2903
2904 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2905 * easily prepend it everywhere. */
2906 delete_trailing_chars(m->cgroup_root, "/");
2907
2908 /* 2. Show data */
2909 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
2910 if (r < 0)
2911 return log_error_errno(r, "Cannot find cgroup mount point: %m");
2912
2913 r = cg_unified();
2914 if (r < 0)
2915 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
2916
2917 all_unified = cg_all_unified();
2918 if (all_unified < 0)
2919 return log_error_errno(all_unified, "Couldn't determine whether we are in all unified mode: %m");
2920 if (all_unified > 0)
2921 log_debug("Unified cgroup hierarchy is located at %s.", path);
2922 else {
2923 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2924 if (r < 0)
2925 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
2926 if (r > 0)
2927 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
2928 else
2929 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
2930 }
2931
2932 /* 3. Allocate cgroup empty defer event source */
2933 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2934 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
2935 if (r < 0)
2936 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
2937
2938 /* Schedule cgroup empty checks early, but after having processed service notification messages or
2939 * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of
2940 * notification, and we collected the metadata the notification and SIGCHLD stuff offers first. */
2941 r = sd_event_source_set_priority(m->cgroup_empty_event_source, SD_EVENT_PRIORITY_NORMAL-5);
2942 if (r < 0)
2943 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
2944
2945 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
2946 if (r < 0)
2947 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
2948
2949 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
2950
2951 /* 4. Install notifier inotify object, or agent */
2952 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
2953
2954 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2955
2956 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2957 safe_close(m->cgroup_inotify_fd);
2958
2959 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
2960 if (m->cgroup_inotify_fd < 0)
2961 return log_error_errno(errno, "Failed to create control group inotify object: %m");
2962
2963 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
2964 if (r < 0)
2965 return log_error_errno(r, "Failed to watch control group inotify object: %m");
2966
2967 /* Process cgroup empty notifications early. Note that when this event is dispatched it'll
2968 * just add the unit to a cgroup empty queue, hence let's run earlier than that. Also see
2969 * handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2970 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-9);
2971 if (r < 0)
2972 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
2973
2974 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
2975
2976 } else if (MANAGER_IS_SYSTEM(m) && manager_owns_host_root_cgroup(m) && !MANAGER_IS_TEST_RUN(m)) {
2977
2978 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2979 * since it does not generate events when control groups with children run empty. */
2980
2981 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
2982 if (r < 0)
2983 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
2984 else if (r > 0)
2985 log_debug("Installed release agent.");
2986 else if (r == 0)
2987 log_debug("Release agent already installed.");
2988 }
2989
2990 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2991 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2992 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2993 if (r >= 0) {
2994 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2995 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2996 if (r < 0)
2997 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
2998
2999 /* 6. And pin it, so that it cannot be unmounted */
3000 safe_close(m->pin_cgroupfs_fd);
3001 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
3002 if (m->pin_cgroupfs_fd < 0)
3003 return log_error_errno(errno, "Failed to open pin file: %m");
3004
3005 } else if (!MANAGER_IS_TEST_RUN(m))
3006 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
3007
3008 /* 7. Always enable hierarchical support if it exists... */
3009 if (!all_unified && !MANAGER_IS_TEST_RUN(m))
3010 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
3011
3012 /* 8. Figure out which controllers are supported */
3013 r = cg_mask_supported(&m->cgroup_supported);
3014 if (r < 0)
3015 return log_error_errno(r, "Failed to determine supported controllers: %m");
3016
3017 /* 9. Figure out which bpf-based pseudo-controllers are supported */
3018 r = cg_bpf_mask_supported(&mask);
3019 if (r < 0)
3020 return log_error_errno(r, "Failed to determine supported bpf-based pseudo-controllers: %m");
3021 m->cgroup_supported |= mask;
3022
3023 /* 10. Log which controllers are supported */
3024 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
3025 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
3026
3027 return 0;
3028 }
3029
3030 void manager_shutdown_cgroup(Manager *m, bool delete) {
3031 assert(m);
3032
3033 /* We can't really delete the group, since we are in it. But
3034 * let's trim it. */
3035 if (delete && m->cgroup_root && m->test_run_flags != MANAGER_TEST_RUN_MINIMAL)
3036 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
3037
3038 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
3039
3040 m->cgroup_control_inotify_wd_unit = hashmap_free(m->cgroup_control_inotify_wd_unit);
3041 m->cgroup_memory_inotify_wd_unit = hashmap_free(m->cgroup_memory_inotify_wd_unit);
3042
3043 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
3044 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
3045
3046 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
3047
3048 m->cgroup_root = mfree(m->cgroup_root);
3049 }
3050
3051 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
3052 char *p;
3053 Unit *u;
3054
3055 assert(m);
3056 assert(cgroup);
3057
3058 u = hashmap_get(m->cgroup_unit, cgroup);
3059 if (u)
3060 return u;
3061
3062 p = strdupa(cgroup);
3063 for (;;) {
3064 char *e;
3065
3066 e = strrchr(p, '/');
3067 if (!e || e == p)
3068 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
3069
3070 *e = 0;
3071
3072 u = hashmap_get(m->cgroup_unit, p);
3073 if (u)
3074 return u;
3075 }
3076 }
3077
3078 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
3079 _cleanup_free_ char *cgroup = NULL;
3080
3081 assert(m);
3082
3083 if (!pid_is_valid(pid))
3084 return NULL;
3085
3086 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup) < 0)
3087 return NULL;
3088
3089 return manager_get_unit_by_cgroup(m, cgroup);
3090 }
3091
3092 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
3093 Unit *u, **array;
3094
3095 assert(m);
3096
3097 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
3098 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
3099 * relevant one as children of the process will be assigned to that one, too, before all else. */
3100
3101 if (!pid_is_valid(pid))
3102 return NULL;
3103
3104 if (pid == getpid_cached())
3105 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
3106
3107 u = manager_get_unit_by_pid_cgroup(m, pid);
3108 if (u)
3109 return u;
3110
3111 u = hashmap_get(m->watch_pids, PID_TO_PTR(pid));
3112 if (u)
3113 return u;
3114
3115 array = hashmap_get(m->watch_pids, PID_TO_PTR(-pid));
3116 if (array)
3117 return array[0];
3118
3119 return NULL;
3120 }
3121
3122 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
3123 Unit *u;
3124
3125 assert(m);
3126 assert(cgroup);
3127
3128 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
3129 * or from the --system instance */
3130
3131 log_debug("Got cgroup empty notification for: %s", cgroup);
3132
3133 u = manager_get_unit_by_cgroup(m, cgroup);
3134 if (!u)
3135 return 0;
3136
3137 unit_add_to_cgroup_empty_queue(u);
3138 return 1;
3139 }
3140
3141 int unit_get_memory_current(Unit *u, uint64_t *ret) {
3142 int r;
3143
3144 assert(u);
3145 assert(ret);
3146
3147 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
3148 return -ENODATA;
3149
3150 if (!u->cgroup_path)
3151 return -ENODATA;
3152
3153 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3154 if (unit_has_host_root_cgroup(u))
3155 return procfs_memory_get_used(ret);
3156
3157 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
3158 return -ENODATA;
3159
3160 r = cg_all_unified();
3161 if (r < 0)
3162 return r;
3163
3164 return cg_get_attribute_as_uint64("memory", u->cgroup_path, r > 0 ? "memory.current" : "memory.usage_in_bytes", ret);
3165 }
3166
3167 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
3168 assert(u);
3169 assert(ret);
3170
3171 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
3172 return -ENODATA;
3173
3174 if (!u->cgroup_path)
3175 return -ENODATA;
3176
3177 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3178 if (unit_has_host_root_cgroup(u))
3179 return procfs_tasks_get_current(ret);
3180
3181 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
3182 return -ENODATA;
3183
3184 return cg_get_attribute_as_uint64("pids", u->cgroup_path, "pids.current", ret);
3185 }
3186
3187 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
3188 uint64_t ns;
3189 int r;
3190
3191 assert(u);
3192 assert(ret);
3193
3194 if (!u->cgroup_path)
3195 return -ENODATA;
3196
3197 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
3198 if (unit_has_host_root_cgroup(u))
3199 return procfs_cpu_get_usage(ret);
3200
3201 /* Requisite controllers for CPU accounting are not enabled */
3202 if ((get_cpu_accounting_mask() & ~u->cgroup_realized_mask) != 0)
3203 return -ENODATA;
3204
3205 r = cg_all_unified();
3206 if (r < 0)
3207 return r;
3208 if (r > 0) {
3209 _cleanup_free_ char *val = NULL;
3210 uint64_t us;
3211
3212 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
3213 if (IN_SET(r, -ENOENT, -ENXIO))
3214 return -ENODATA;
3215 if (r < 0)
3216 return r;
3217
3218 r = safe_atou64(val, &us);
3219 if (r < 0)
3220 return r;
3221
3222 ns = us * NSEC_PER_USEC;
3223 } else
3224 return cg_get_attribute_as_uint64("cpuacct", u->cgroup_path, "cpuacct.usage", ret);
3225
3226 *ret = ns;
3227 return 0;
3228 }
3229
3230 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
3231 nsec_t ns;
3232 int r;
3233
3234 assert(u);
3235
3236 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
3237 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
3238 * call this function with a NULL return value. */
3239
3240 if (!UNIT_CGROUP_BOOL(u, cpu_accounting))
3241 return -ENODATA;
3242
3243 r = unit_get_cpu_usage_raw(u, &ns);
3244 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
3245 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
3246 * cached value. */
3247
3248 if (ret)
3249 *ret = u->cpu_usage_last;
3250 return 0;
3251 }
3252 if (r < 0)
3253 return r;
3254
3255 if (ns > u->cpu_usage_base)
3256 ns -= u->cpu_usage_base;
3257 else
3258 ns = 0;
3259
3260 u->cpu_usage_last = ns;
3261 if (ret)
3262 *ret = ns;
3263
3264 return 0;
3265 }
3266
3267 int unit_get_ip_accounting(
3268 Unit *u,
3269 CGroupIPAccountingMetric metric,
3270 uint64_t *ret) {
3271
3272 uint64_t value;
3273 int fd, r;
3274
3275 assert(u);
3276 assert(metric >= 0);
3277 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
3278 assert(ret);
3279
3280 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
3281 return -ENODATA;
3282
3283 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
3284 u->ip_accounting_ingress_map_fd :
3285 u->ip_accounting_egress_map_fd;
3286 if (fd < 0)
3287 return -ENODATA;
3288
3289 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
3290 r = bpf_firewall_read_accounting(fd, &value, NULL);
3291 else
3292 r = bpf_firewall_read_accounting(fd, NULL, &value);
3293 if (r < 0)
3294 return r;
3295
3296 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
3297 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
3298 * ip_accounting_extra[] field, and add them in here transparently. */
3299
3300 *ret = value + u->ip_accounting_extra[metric];
3301
3302 return r;
3303 }
3304
3305 static int unit_get_io_accounting_raw(Unit *u, uint64_t ret[static _CGROUP_IO_ACCOUNTING_METRIC_MAX]) {
3306 static const char *const field_names[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3307 [CGROUP_IO_READ_BYTES] = "rbytes=",
3308 [CGROUP_IO_WRITE_BYTES] = "wbytes=",
3309 [CGROUP_IO_READ_OPERATIONS] = "rios=",
3310 [CGROUP_IO_WRITE_OPERATIONS] = "wios=",
3311 };
3312 uint64_t acc[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {};
3313 _cleanup_free_ char *path = NULL;
3314 _cleanup_fclose_ FILE *f = NULL;
3315 int r;
3316
3317 assert(u);
3318
3319 if (!u->cgroup_path)
3320 return -ENODATA;
3321
3322 if (unit_has_host_root_cgroup(u))
3323 return -ENODATA; /* TODO: return useful data for the top-level cgroup */
3324
3325 r = cg_all_unified();
3326 if (r < 0)
3327 return r;
3328 if (r == 0) /* TODO: support cgroupv1 */
3329 return -ENODATA;
3330
3331 if (!FLAGS_SET(u->cgroup_realized_mask, CGROUP_MASK_IO))
3332 return -ENODATA;
3333
3334 r = cg_get_path("io", u->cgroup_path, "io.stat", &path);
3335 if (r < 0)
3336 return r;
3337
3338 f = fopen(path, "re");
3339 if (!f)
3340 return -errno;
3341
3342 for (;;) {
3343 _cleanup_free_ char *line = NULL;
3344 const char *p;
3345
3346 r = read_line(f, LONG_LINE_MAX, &line);
3347 if (r < 0)
3348 return r;
3349 if (r == 0)
3350 break;
3351
3352 p = line;
3353 p += strcspn(p, WHITESPACE); /* Skip over device major/minor */
3354 p += strspn(p, WHITESPACE); /* Skip over following whitespace */
3355
3356 for (;;) {
3357 _cleanup_free_ char *word = NULL;
3358
3359 r = extract_first_word(&p, &word, NULL, EXTRACT_RETAIN_ESCAPE);
3360 if (r < 0)
3361 return r;
3362 if (r == 0)
3363 break;
3364
3365 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
3366 const char *x;
3367
3368 x = startswith(word, field_names[i]);
3369 if (x) {
3370 uint64_t w;
3371
3372 r = safe_atou64(x, &w);
3373 if (r < 0)
3374 return r;
3375
3376 /* Sum up the stats of all devices */
3377 acc[i] += w;
3378 break;
3379 }
3380 }
3381 }
3382 }
3383
3384 memcpy(ret, acc, sizeof(acc));
3385 return 0;
3386 }
3387
3388 int unit_get_io_accounting(
3389 Unit *u,
3390 CGroupIOAccountingMetric metric,
3391 bool allow_cache,
3392 uint64_t *ret) {
3393
3394 uint64_t raw[_CGROUP_IO_ACCOUNTING_METRIC_MAX];
3395 int r;
3396
3397 /* Retrieve an IO account parameter. This will subtract the counter when the unit was started. */
3398
3399 if (!UNIT_CGROUP_BOOL(u, io_accounting))
3400 return -ENODATA;
3401
3402 if (allow_cache && u->io_accounting_last[metric] != UINT64_MAX)
3403 goto done;
3404
3405 r = unit_get_io_accounting_raw(u, raw);
3406 if (r == -ENODATA && u->io_accounting_last[metric] != UINT64_MAX)
3407 goto done;
3408 if (r < 0)
3409 return r;
3410
3411 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++) {
3412 /* Saturated subtraction */
3413 if (raw[i] > u->io_accounting_base[i])
3414 u->io_accounting_last[i] = raw[i] - u->io_accounting_base[i];
3415 else
3416 u->io_accounting_last[i] = 0;
3417 }
3418
3419 done:
3420 if (ret)
3421 *ret = u->io_accounting_last[metric];
3422
3423 return 0;
3424 }
3425
3426 int unit_reset_cpu_accounting(Unit *u) {
3427 int r;
3428
3429 assert(u);
3430
3431 u->cpu_usage_last = NSEC_INFINITY;
3432
3433 r = unit_get_cpu_usage_raw(u, &u->cpu_usage_base);
3434 if (r < 0) {
3435 u->cpu_usage_base = 0;
3436 return r;
3437 }
3438
3439 return 0;
3440 }
3441
3442 int unit_reset_ip_accounting(Unit *u) {
3443 int r = 0, q = 0;
3444
3445 assert(u);
3446
3447 if (u->ip_accounting_ingress_map_fd >= 0)
3448 r = bpf_firewall_reset_accounting(u->ip_accounting_ingress_map_fd);
3449
3450 if (u->ip_accounting_egress_map_fd >= 0)
3451 q = bpf_firewall_reset_accounting(u->ip_accounting_egress_map_fd);
3452
3453 zero(u->ip_accounting_extra);
3454
3455 return r < 0 ? r : q;
3456 }
3457
3458 int unit_reset_io_accounting(Unit *u) {
3459 int r;
3460
3461 assert(u);
3462
3463 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++)
3464 u->io_accounting_last[i] = UINT64_MAX;
3465
3466 r = unit_get_io_accounting_raw(u, u->io_accounting_base);
3467 if (r < 0) {
3468 zero(u->io_accounting_base);
3469 return r;
3470 }
3471
3472 return 0;
3473 }
3474
3475 int unit_reset_accounting(Unit *u) {
3476 int r, q, v;
3477
3478 assert(u);
3479
3480 r = unit_reset_cpu_accounting(u);
3481 q = unit_reset_io_accounting(u);
3482 v = unit_reset_ip_accounting(u);
3483
3484 return r < 0 ? r : q < 0 ? q : v;
3485 }
3486
3487 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
3488 assert(u);
3489
3490 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3491 return;
3492
3493 if (m == 0)
3494 return;
3495
3496 /* always invalidate compat pairs together */
3497 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
3498 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
3499
3500 if (m & (CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT))
3501 m |= CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT;
3502
3503 if (FLAGS_SET(u->cgroup_invalidated_mask, m)) /* NOP? */
3504 return;
3505
3506 u->cgroup_invalidated_mask |= m;
3507 unit_add_to_cgroup_realize_queue(u);
3508 }
3509
3510 void unit_invalidate_cgroup_bpf(Unit *u) {
3511 assert(u);
3512
3513 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3514 return;
3515
3516 if (u->cgroup_invalidated_mask & CGROUP_MASK_BPF_FIREWALL) /* NOP? */
3517 return;
3518
3519 u->cgroup_invalidated_mask |= CGROUP_MASK_BPF_FIREWALL;
3520 unit_add_to_cgroup_realize_queue(u);
3521
3522 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
3523 * list of our children includes our own. */
3524 if (u->type == UNIT_SLICE) {
3525 Unit *member;
3526 void *v;
3527
3528 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE])
3529 if (UNIT_DEREF(member->slice) == u)
3530 unit_invalidate_cgroup_bpf(member);
3531 }
3532 }
3533
3534 bool unit_cgroup_delegate(Unit *u) {
3535 CGroupContext *c;
3536
3537 assert(u);
3538
3539 if (!UNIT_VTABLE(u)->can_delegate)
3540 return false;
3541
3542 c = unit_get_cgroup_context(u);
3543 if (!c)
3544 return false;
3545
3546 return c->delegate;
3547 }
3548
3549 void manager_invalidate_startup_units(Manager *m) {
3550 Unit *u;
3551
3552 assert(m);
3553
3554 SET_FOREACH(u, m->startup_units)
3555 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
3556 }
3557
3558 static int unit_get_nice(Unit *u) {
3559 ExecContext *ec;
3560
3561 ec = unit_get_exec_context(u);
3562 return ec ? ec->nice : 0;
3563 }
3564
3565 static uint64_t unit_get_cpu_weight(Unit *u) {
3566 ManagerState state = manager_state(u->manager);
3567 CGroupContext *cc;
3568
3569 cc = unit_get_cgroup_context(u);
3570 return cc ? cgroup_context_cpu_weight(cc, state) : CGROUP_WEIGHT_DEFAULT;
3571 }
3572
3573 int compare_job_priority(const void *a, const void *b) {
3574 const Job *x = a, *y = b;
3575 int nice_x, nice_y;
3576 uint64_t weight_x, weight_y;
3577 int ret;
3578
3579 if ((ret = CMP(x->unit->type, y->unit->type)) != 0)
3580 return -ret;
3581
3582 weight_x = unit_get_cpu_weight(x->unit);
3583 weight_y = unit_get_cpu_weight(y->unit);
3584
3585 if ((ret = CMP(weight_x, weight_y)) != 0)
3586 return -ret;
3587
3588 nice_x = unit_get_nice(x->unit);
3589 nice_y = unit_get_nice(y->unit);
3590
3591 if ((ret = CMP(nice_x, nice_y)) != 0)
3592 return ret;
3593
3594 return strcmp(x->unit->id, y->unit->id);
3595 }
3596
3597 int unit_cgroup_freezer_action(Unit *u, FreezerAction action) {
3598 _cleanup_free_ char *path = NULL;
3599 FreezerState target, kernel = _FREEZER_STATE_INVALID;
3600 int r;
3601
3602 assert(u);
3603 assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
3604
3605 if (!cg_freezer_supported())
3606 return 0;
3607
3608 if (!u->cgroup_realized)
3609 return -EBUSY;
3610
3611 target = action == FREEZER_FREEZE ? FREEZER_FROZEN : FREEZER_RUNNING;
3612
3613 r = unit_freezer_state_kernel(u, &kernel);
3614 if (r < 0)
3615 log_unit_debug_errno(u, r, "Failed to obtain cgroup freezer state: %m");
3616
3617 if (target == kernel) {
3618 u->freezer_state = target;
3619 return 0;
3620 }
3621
3622 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.freeze", &path);
3623 if (r < 0)
3624 return r;
3625
3626 log_unit_debug(u, "%s unit.", action == FREEZER_FREEZE ? "Freezing" : "Thawing");
3627
3628 if (action == FREEZER_FREEZE)
3629 u->freezer_state = FREEZER_FREEZING;
3630 else
3631 u->freezer_state = FREEZER_THAWING;
3632
3633 r = write_string_file(path, one_zero(action == FREEZER_FREEZE), WRITE_STRING_FILE_DISABLE_BUFFER);
3634 if (r < 0)
3635 return r;
3636
3637 return 1;
3638 }
3639
3640 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
3641 [CGROUP_DEVICE_POLICY_AUTO] = "auto",
3642 [CGROUP_DEVICE_POLICY_CLOSED] = "closed",
3643 [CGROUP_DEVICE_POLICY_STRICT] = "strict",
3644 };
3645
3646 int unit_get_cpuset(Unit *u, CPUSet *cpus, const char *name) {
3647 _cleanup_free_ char *v = NULL;
3648 int r;
3649
3650 assert(u);
3651 assert(cpus);
3652
3653 if (!u->cgroup_path)
3654 return -ENODATA;
3655
3656 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUSET) == 0)
3657 return -ENODATA;
3658
3659 r = cg_all_unified();
3660 if (r < 0)
3661 return r;
3662 if (r == 0)
3663 return -ENODATA;
3664
3665 r = cg_get_attribute("cpuset", u->cgroup_path, name, &v);
3666 if (r == -ENOENT)
3667 return -ENODATA;
3668 if (r < 0)
3669 return r;
3670
3671 return parse_cpu_set_full(v, cpus, false, NULL, NULL, 0, NULL);
3672 }
3673
3674 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);
3675
3676 static const char* const freezer_action_table[_FREEZER_ACTION_MAX] = {
3677 [FREEZER_FREEZE] = "freeze",
3678 [FREEZER_THAW] = "thaw",
3679 };
3680
3681 DEFINE_STRING_TABLE_LOOKUP(freezer_action, FreezerAction);