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