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