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