]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/cgroup.c
6a5995bc0d4c10f3e0c923e855a712943a628ff2
[thirdparty/systemd.git] / src / core / cgroup.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright 2013 Lennart Poettering
4 ***/
5
6 #include <fcntl.h>
7 #include <fnmatch.h>
8
9 #include "alloc-util.h"
10 #include "blockdev-util.h"
11 #include "bpf-firewall.h"
12 #include "btrfs-util.h"
13 #include "bus-error.h"
14 #include "cgroup-util.h"
15 #include "cgroup.h"
16 #include "fd-util.h"
17 #include "fileio.h"
18 #include "fs-util.h"
19 #include "parse-util.h"
20 #include "path-util.h"
21 #include "process-util.h"
22 #include "procfs-util.h"
23 #include "special.h"
24 #include "stdio-util.h"
25 #include "string-table.h"
26 #include "string-util.h"
27 #include "virt.h"
28
29 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
30
31 bool manager_owns_root_cgroup(Manager *m) {
32 assert(m);
33
34 /* Returns true if we are managing the root cgroup. Note that it isn't sufficient to just check whether the
35 * group root path equals "/" since that will also be the case if CLONE_NEWCGROUP is in the mix. Since there's
36 * appears to be no nice way to detect whether we are in a CLONE_NEWCGROUP namespace we instead just check if
37 * we run in any kind of container virtualization. */
38
39 if (detect_container() > 0)
40 return false;
41
42 return empty_or_root(m->cgroup_root);
43 }
44
45 bool unit_has_root_cgroup(Unit *u) {
46 assert(u);
47
48 /* Returns whether this unit manages the root cgroup. This will return true if this unit is the root slice and
49 * the manager manages the root cgroup. */
50
51 if (!manager_owns_root_cgroup(u->manager))
52 return false;
53
54 return unit_has_name(u, SPECIAL_ROOT_SLICE);
55 }
56
57 static void cgroup_compat_warn(void) {
58 static bool cgroup_compat_warned = false;
59
60 if (cgroup_compat_warned)
61 return;
62
63 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. "
64 "See cgroup-compat debug messages for details.");
65
66 cgroup_compat_warned = true;
67 }
68
69 #define log_cgroup_compat(unit, fmt, ...) do { \
70 cgroup_compat_warn(); \
71 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
72 } while (false)
73
74 void cgroup_context_init(CGroupContext *c) {
75 assert(c);
76
77 /* Initialize everything to the kernel defaults, assuming the
78 * structure is preinitialized to 0 */
79
80 c->cpu_weight = CGROUP_WEIGHT_INVALID;
81 c->startup_cpu_weight = CGROUP_WEIGHT_INVALID;
82 c->cpu_quota_per_sec_usec = USEC_INFINITY;
83
84 c->cpu_shares = CGROUP_CPU_SHARES_INVALID;
85 c->startup_cpu_shares = CGROUP_CPU_SHARES_INVALID;
86
87 c->memory_high = CGROUP_LIMIT_MAX;
88 c->memory_max = CGROUP_LIMIT_MAX;
89 c->memory_swap_max = CGROUP_LIMIT_MAX;
90
91 c->memory_limit = CGROUP_LIMIT_MAX;
92
93 c->io_weight = CGROUP_WEIGHT_INVALID;
94 c->startup_io_weight = CGROUP_WEIGHT_INVALID;
95
96 c->blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
97 c->startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
98
99 c->tasks_max = (uint64_t) -1;
100 }
101
102 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
103 assert(c);
104 assert(a);
105
106 LIST_REMOVE(device_allow, c->device_allow, a);
107 free(a->path);
108 free(a);
109 }
110
111 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
112 assert(c);
113 assert(w);
114
115 LIST_REMOVE(device_weights, c->io_device_weights, w);
116 free(w->path);
117 free(w);
118 }
119
120 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
121 assert(c);
122 assert(l);
123
124 LIST_REMOVE(device_limits, c->io_device_limits, l);
125 free(l->path);
126 free(l);
127 }
128
129 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
130 assert(c);
131 assert(w);
132
133 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
134 free(w->path);
135 free(w);
136 }
137
138 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
139 assert(c);
140 assert(b);
141
142 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
143 free(b->path);
144 free(b);
145 }
146
147 void cgroup_context_done(CGroupContext *c) {
148 assert(c);
149
150 while (c->io_device_weights)
151 cgroup_context_free_io_device_weight(c, c->io_device_weights);
152
153 while (c->io_device_limits)
154 cgroup_context_free_io_device_limit(c, c->io_device_limits);
155
156 while (c->blockio_device_weights)
157 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
158
159 while (c->blockio_device_bandwidths)
160 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
161
162 while (c->device_allow)
163 cgroup_context_free_device_allow(c, c->device_allow);
164
165 c->ip_address_allow = ip_address_access_free_all(c->ip_address_allow);
166 c->ip_address_deny = ip_address_access_free_all(c->ip_address_deny);
167 }
168
169 void cgroup_context_dump(CGroupContext *c, FILE* f, const char *prefix) {
170 CGroupIODeviceLimit *il;
171 CGroupIODeviceWeight *iw;
172 CGroupBlockIODeviceBandwidth *b;
173 CGroupBlockIODeviceWeight *w;
174 CGroupDeviceAllow *a;
175 IPAddressAccessItem *iaai;
176 char u[FORMAT_TIMESPAN_MAX];
177
178 assert(c);
179 assert(f);
180
181 prefix = strempty(prefix);
182
183 fprintf(f,
184 "%sCPUAccounting=%s\n"
185 "%sIOAccounting=%s\n"
186 "%sBlockIOAccounting=%s\n"
187 "%sMemoryAccounting=%s\n"
188 "%sTasksAccounting=%s\n"
189 "%sIPAccounting=%s\n"
190 "%sCPUWeight=%" PRIu64 "\n"
191 "%sStartupCPUWeight=%" PRIu64 "\n"
192 "%sCPUShares=%" PRIu64 "\n"
193 "%sStartupCPUShares=%" PRIu64 "\n"
194 "%sCPUQuotaPerSecSec=%s\n"
195 "%sIOWeight=%" PRIu64 "\n"
196 "%sStartupIOWeight=%" PRIu64 "\n"
197 "%sBlockIOWeight=%" PRIu64 "\n"
198 "%sStartupBlockIOWeight=%" PRIu64 "\n"
199 "%sMemoryLow=%" PRIu64 "\n"
200 "%sMemoryHigh=%" PRIu64 "\n"
201 "%sMemoryMax=%" PRIu64 "\n"
202 "%sMemorySwapMax=%" PRIu64 "\n"
203 "%sMemoryLimit=%" PRIu64 "\n"
204 "%sTasksMax=%" PRIu64 "\n"
205 "%sDevicePolicy=%s\n"
206 "%sDelegate=%s\n",
207 prefix, yes_no(c->cpu_accounting),
208 prefix, yes_no(c->io_accounting),
209 prefix, yes_no(c->blockio_accounting),
210 prefix, yes_no(c->memory_accounting),
211 prefix, yes_no(c->tasks_accounting),
212 prefix, yes_no(c->ip_accounting),
213 prefix, c->cpu_weight,
214 prefix, c->startup_cpu_weight,
215 prefix, c->cpu_shares,
216 prefix, c->startup_cpu_shares,
217 prefix, format_timespan(u, sizeof(u), c->cpu_quota_per_sec_usec, 1),
218 prefix, c->io_weight,
219 prefix, c->startup_io_weight,
220 prefix, c->blockio_weight,
221 prefix, c->startup_blockio_weight,
222 prefix, c->memory_low,
223 prefix, c->memory_high,
224 prefix, c->memory_max,
225 prefix, c->memory_swap_max,
226 prefix, c->memory_limit,
227 prefix, c->tasks_max,
228 prefix, cgroup_device_policy_to_string(c->device_policy),
229 prefix, yes_no(c->delegate));
230
231 if (c->delegate) {
232 _cleanup_free_ char *t = NULL;
233
234 (void) cg_mask_to_string(c->delegate_controllers, &t);
235
236 fprintf(f, "%sDelegateControllers=%s\n",
237 prefix,
238 strempty(t));
239 }
240
241 LIST_FOREACH(device_allow, a, c->device_allow)
242 fprintf(f,
243 "%sDeviceAllow=%s %s%s%s\n",
244 prefix,
245 a->path,
246 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
247
248 LIST_FOREACH(device_weights, iw, c->io_device_weights)
249 fprintf(f,
250 "%sIODeviceWeight=%s %" PRIu64,
251 prefix,
252 iw->path,
253 iw->weight);
254
255 LIST_FOREACH(device_limits, il, c->io_device_limits) {
256 char buf[FORMAT_BYTES_MAX];
257 CGroupIOLimitType type;
258
259 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
260 if (il->limits[type] != cgroup_io_limit_defaults[type])
261 fprintf(f,
262 "%s%s=%s %s\n",
263 prefix,
264 cgroup_io_limit_type_to_string(type),
265 il->path,
266 format_bytes(buf, sizeof(buf), il->limits[type]));
267 }
268
269 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
270 fprintf(f,
271 "%sBlockIODeviceWeight=%s %" PRIu64,
272 prefix,
273 w->path,
274 w->weight);
275
276 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
277 char buf[FORMAT_BYTES_MAX];
278
279 if (b->rbps != CGROUP_LIMIT_MAX)
280 fprintf(f,
281 "%sBlockIOReadBandwidth=%s %s\n",
282 prefix,
283 b->path,
284 format_bytes(buf, sizeof(buf), b->rbps));
285 if (b->wbps != CGROUP_LIMIT_MAX)
286 fprintf(f,
287 "%sBlockIOWriteBandwidth=%s %s\n",
288 prefix,
289 b->path,
290 format_bytes(buf, sizeof(buf), b->wbps));
291 }
292
293 LIST_FOREACH(items, iaai, c->ip_address_allow) {
294 _cleanup_free_ char *k = NULL;
295
296 (void) in_addr_to_string(iaai->family, &iaai->address, &k);
297 fprintf(f, "%sIPAddressAllow=%s/%u\n", prefix, strnull(k), iaai->prefixlen);
298 }
299
300 LIST_FOREACH(items, iaai, c->ip_address_deny) {
301 _cleanup_free_ char *k = NULL;
302
303 (void) in_addr_to_string(iaai->family, &iaai->address, &k);
304 fprintf(f, "%sIPAddressDeny=%s/%u\n", prefix, strnull(k), iaai->prefixlen);
305 }
306 }
307
308 static int lookup_block_device(const char *p, dev_t *ret) {
309 struct stat st;
310 int r;
311
312 assert(p);
313 assert(ret);
314
315 if (stat(p, &st) < 0)
316 return log_warning_errno(errno, "Couldn't stat device '%s': %m", p);
317
318 if (S_ISBLK(st.st_mode))
319 *ret = st.st_rdev;
320 else if (major(st.st_dev) != 0)
321 *ret = st.st_dev; /* If this is not a device node then use the block device this file is stored on */
322 else {
323 /* If this is btrfs, getting the backing block device is a bit harder */
324 r = btrfs_get_block_device(p, ret);
325 if (r < 0 && r != -ENOTTY)
326 return log_warning_errno(r, "Failed to determine block device backing btrfs file system '%s': %m", p);
327 if (r == -ENOTTY) {
328 log_warning("'%s' is not a block device node, and file system block device cannot be determined or is not local.", p);
329 return -ENODEV;
330 }
331 }
332
333 /* If this is a LUKS device, try to get the originating block device */
334 (void) block_get_originating(*ret, ret);
335
336 /* If this is a partition, try to get the originating block device */
337 (void) block_get_whole_disk(*ret, ret);
338 return 0;
339 }
340
341 static int whitelist_device(const char *path, const char *node, const char *acc) {
342 char buf[2+DECIMAL_STR_MAX(dev_t)*2+2+4];
343 struct stat st;
344 bool ignore_notfound;
345 int r;
346
347 assert(path);
348 assert(acc);
349
350 if (node[0] == '-') {
351 /* Non-existent paths starting with "-" must be silently ignored */
352 node++;
353 ignore_notfound = true;
354 } else
355 ignore_notfound = false;
356
357 if (stat(node, &st) < 0) {
358 if (errno == ENOENT && ignore_notfound)
359 return 0;
360
361 return log_warning_errno(errno, "Couldn't stat device %s: %m", node);
362 }
363
364 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
365 log_warning("%s is not a device.", node);
366 return -ENODEV;
367 }
368
369 sprintf(buf,
370 "%c %u:%u %s",
371 S_ISCHR(st.st_mode) ? 'c' : 'b',
372 major(st.st_rdev), minor(st.st_rdev),
373 acc);
374
375 r = cg_set_attribute("devices", path, "devices.allow", buf);
376 if (r < 0)
377 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
378 "Failed to set devices.allow on %s: %m", path);
379
380 return r;
381 }
382
383 static int whitelist_major(const char *path, const char *name, char type, const char *acc) {
384 _cleanup_fclose_ FILE *f = NULL;
385 char line[LINE_MAX];
386 bool good = false;
387 int r;
388
389 assert(path);
390 assert(acc);
391 assert(IN_SET(type, 'b', 'c'));
392
393 f = fopen("/proc/devices", "re");
394 if (!f)
395 return log_warning_errno(errno, "Cannot open /proc/devices to resolve %s (%c): %m", name, type);
396
397 FOREACH_LINE(line, f, goto fail) {
398 char buf[2+DECIMAL_STR_MAX(unsigned)+3+4], *p, *w;
399 unsigned maj;
400
401 truncate_nl(line);
402
403 if (type == 'c' && streq(line, "Character devices:")) {
404 good = true;
405 continue;
406 }
407
408 if (type == 'b' && streq(line, "Block devices:")) {
409 good = true;
410 continue;
411 }
412
413 if (isempty(line)) {
414 good = false;
415 continue;
416 }
417
418 if (!good)
419 continue;
420
421 p = strstrip(line);
422
423 w = strpbrk(p, WHITESPACE);
424 if (!w)
425 continue;
426 *w = 0;
427
428 r = safe_atou(p, &maj);
429 if (r < 0)
430 continue;
431 if (maj <= 0)
432 continue;
433
434 w++;
435 w += strspn(w, WHITESPACE);
436
437 if (fnmatch(name, w, 0) != 0)
438 continue;
439
440 sprintf(buf,
441 "%c %u:* %s",
442 type,
443 maj,
444 acc);
445
446 r = cg_set_attribute("devices", path, "devices.allow", buf);
447 if (r < 0)
448 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
449 "Failed to set devices.allow on %s: %m", path);
450 }
451
452 return 0;
453
454 fail:
455 return log_warning_errno(errno, "Failed to read /proc/devices: %m");
456 }
457
458 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
459 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
460 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
461 }
462
463 static bool cgroup_context_has_cpu_shares(CGroupContext *c) {
464 return c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
465 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID;
466 }
467
468 static uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
469 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
470 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
471 return c->startup_cpu_weight;
472 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
473 return c->cpu_weight;
474 else
475 return CGROUP_WEIGHT_DEFAULT;
476 }
477
478 static uint64_t cgroup_context_cpu_shares(CGroupContext *c, ManagerState state) {
479 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
480 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID)
481 return c->startup_cpu_shares;
482 else if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID)
483 return c->cpu_shares;
484 else
485 return CGROUP_CPU_SHARES_DEFAULT;
486 }
487
488 static void cgroup_apply_unified_cpu_config(Unit *u, uint64_t weight, uint64_t quota) {
489 char buf[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t) + 1) * 2)];
490 int r;
491
492 xsprintf(buf, "%" PRIu64 "\n", weight);
493 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.weight", buf);
494 if (r < 0)
495 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
496 "Failed to set cpu.weight: %m");
497
498 if (quota != USEC_INFINITY)
499 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
500 quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC, CGROUP_CPU_QUOTA_PERIOD_USEC);
501 else
502 xsprintf(buf, "max " USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
503
504 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.max", buf);
505
506 if (r < 0)
507 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
508 "Failed to set cpu.max: %m");
509 }
510
511 static void cgroup_apply_legacy_cpu_config(Unit *u, uint64_t shares, uint64_t quota) {
512 char buf[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t)) + 1];
513 int r;
514
515 xsprintf(buf, "%" PRIu64 "\n", shares);
516 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.shares", buf);
517 if (r < 0)
518 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
519 "Failed to set cpu.shares: %m");
520
521 xsprintf(buf, USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
522 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_period_us", buf);
523 if (r < 0)
524 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
525 "Failed to set cpu.cfs_period_us: %m");
526
527 if (quota != USEC_INFINITY) {
528 xsprintf(buf, USEC_FMT "\n", quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC);
529 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", buf);
530 } else
531 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", "-1");
532 if (r < 0)
533 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
534 "Failed to set cpu.cfs_quota_us: %m");
535 }
536
537 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares) {
538 return CLAMP(shares * CGROUP_WEIGHT_DEFAULT / CGROUP_CPU_SHARES_DEFAULT,
539 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
540 }
541
542 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight) {
543 return CLAMP(weight * CGROUP_CPU_SHARES_DEFAULT / CGROUP_WEIGHT_DEFAULT,
544 CGROUP_CPU_SHARES_MIN, CGROUP_CPU_SHARES_MAX);
545 }
546
547 static bool cgroup_context_has_io_config(CGroupContext *c) {
548 return c->io_accounting ||
549 c->io_weight != CGROUP_WEIGHT_INVALID ||
550 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
551 c->io_device_weights ||
552 c->io_device_limits;
553 }
554
555 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
556 return c->blockio_accounting ||
557 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
558 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
559 c->blockio_device_weights ||
560 c->blockio_device_bandwidths;
561 }
562
563 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
564 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
565 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
566 return c->startup_io_weight;
567 else if (c->io_weight != CGROUP_WEIGHT_INVALID)
568 return c->io_weight;
569 else
570 return CGROUP_WEIGHT_DEFAULT;
571 }
572
573 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
574 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
575 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
576 return c->startup_blockio_weight;
577 else if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
578 return c->blockio_weight;
579 else
580 return CGROUP_BLKIO_WEIGHT_DEFAULT;
581 }
582
583 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
584 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
585 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
586 }
587
588 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
589 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
590 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
591 }
592
593 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
594 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
595 dev_t dev;
596 int r;
597
598 r = lookup_block_device(dev_path, &dev);
599 if (r < 0)
600 return;
601
602 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), io_weight);
603 r = cg_set_attribute("io", u->cgroup_path, "io.weight", buf);
604 if (r < 0)
605 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
606 "Failed to set io.weight: %m");
607 }
608
609 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
610 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
611 dev_t dev;
612 int r;
613
614 r = lookup_block_device(dev_path, &dev);
615 if (r < 0)
616 return;
617
618 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), blkio_weight);
619 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.weight_device", buf);
620 if (r < 0)
621 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
622 "Failed to set blkio.weight_device: %m");
623 }
624
625 static void cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
626 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)];
627 char buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
628 CGroupIOLimitType type;
629 dev_t dev;
630 int r;
631
632 r = lookup_block_device(dev_path, &dev);
633 if (r < 0)
634 return;
635
636 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
637 if (limits[type] != cgroup_io_limit_defaults[type])
638 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
639 else
640 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
641
642 xsprintf(buf, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev), minor(dev),
643 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
644 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
645 r = cg_set_attribute("io", u->cgroup_path, "io.max", buf);
646 if (r < 0)
647 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
648 "Failed to set io.max: %m");
649 }
650
651 static void cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
652 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
653 dev_t dev;
654 int r;
655
656 r = lookup_block_device(dev_path, &dev);
657 if (r < 0)
658 return;
659
660 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), rbps);
661 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.read_bps_device", buf);
662 if (r < 0)
663 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
664 "Failed to set blkio.throttle.read_bps_device: %m");
665
666 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), wbps);
667 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.write_bps_device", buf);
668 if (r < 0)
669 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
670 "Failed to set blkio.throttle.write_bps_device: %m");
671 }
672
673 static bool cgroup_context_has_unified_memory_config(CGroupContext *c) {
674 return c->memory_low > 0 || c->memory_high != CGROUP_LIMIT_MAX || c->memory_max != CGROUP_LIMIT_MAX || c->memory_swap_max != CGROUP_LIMIT_MAX;
675 }
676
677 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
678 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
679 int r;
680
681 if (v != CGROUP_LIMIT_MAX)
682 xsprintf(buf, "%" PRIu64 "\n", v);
683
684 r = cg_set_attribute("memory", u->cgroup_path, file, buf);
685 if (r < 0)
686 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
687 "Failed to set %s: %m", file);
688 }
689
690 static void cgroup_apply_firewall(Unit *u) {
691 assert(u);
692
693 /* Best-effort: let's apply IP firewalling and/or accounting if that's enabled */
694
695 if (bpf_firewall_compile(u) < 0)
696 return;
697
698 (void) bpf_firewall_install(u);
699 }
700
701 static void cgroup_context_apply(
702 Unit *u,
703 CGroupMask apply_mask,
704 bool apply_bpf,
705 ManagerState state) {
706
707 const char *path;
708 CGroupContext *c;
709 bool is_root;
710 int r;
711
712 assert(u);
713
714 /* Nothing to do? Exit early! */
715 if (apply_mask == 0 && !apply_bpf)
716 return;
717
718 /* Some cgroup attributes are not supported on the root cgroup, hence silently ignore */
719 is_root = unit_has_root_cgroup(u);
720
721 assert_se(c = unit_get_cgroup_context(u));
722 assert_se(path = u->cgroup_path);
723
724 if (is_root) /* Make sure we don't try to display messages with an empty path. */
725 path = "/";
726
727 /* We generally ignore errors caused by read-only mounted
728 * cgroup trees (assuming we are running in a container then),
729 * and missing cgroups, i.e. EROFS and ENOENT. */
730
731 if ((apply_mask & CGROUP_MASK_CPU) && !is_root) {
732 bool has_weight, has_shares;
733
734 has_weight = cgroup_context_has_cpu_weight(c);
735 has_shares = cgroup_context_has_cpu_shares(c);
736
737 if (cg_all_unified() > 0) {
738 uint64_t weight;
739
740 if (has_weight)
741 weight = cgroup_context_cpu_weight(c, state);
742 else if (has_shares) {
743 uint64_t shares = cgroup_context_cpu_shares(c, state);
744
745 weight = cgroup_cpu_shares_to_weight(shares);
746
747 log_cgroup_compat(u, "Applying [Startup]CpuShares %" PRIu64 " as [Startup]CpuWeight %" PRIu64 " on %s",
748 shares, weight, path);
749 } else
750 weight = CGROUP_WEIGHT_DEFAULT;
751
752 cgroup_apply_unified_cpu_config(u, weight, c->cpu_quota_per_sec_usec);
753 } else {
754 uint64_t shares;
755
756 if (has_weight) {
757 uint64_t weight = cgroup_context_cpu_weight(c, state);
758
759 shares = cgroup_cpu_weight_to_shares(weight);
760
761 log_cgroup_compat(u, "Applying [Startup]CpuWeight %" PRIu64 " as [Startup]CpuShares %" PRIu64 " on %s",
762 weight, shares, path);
763 } else if (has_shares)
764 shares = cgroup_context_cpu_shares(c, state);
765 else
766 shares = CGROUP_CPU_SHARES_DEFAULT;
767
768 cgroup_apply_legacy_cpu_config(u, shares, c->cpu_quota_per_sec_usec);
769 }
770 }
771
772 if (apply_mask & CGROUP_MASK_IO) {
773 bool has_io = cgroup_context_has_io_config(c);
774 bool has_blockio = cgroup_context_has_blockio_config(c);
775
776 if (!is_root) {
777 char buf[8+DECIMAL_STR_MAX(uint64_t)+1];
778 uint64_t weight;
779
780 if (has_io)
781 weight = cgroup_context_io_weight(c, state);
782 else if (has_blockio) {
783 uint64_t blkio_weight = cgroup_context_blkio_weight(c, state);
784
785 weight = cgroup_weight_blkio_to_io(blkio_weight);
786
787 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight %" PRIu64 " as [Startup]IOWeight %" PRIu64,
788 blkio_weight, weight);
789 } else
790 weight = CGROUP_WEIGHT_DEFAULT;
791
792 xsprintf(buf, "default %" PRIu64 "\n", weight);
793 r = cg_set_attribute("io", path, "io.weight", buf);
794 if (r < 0)
795 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
796 "Failed to set io.weight: %m");
797
798 if (has_io) {
799 CGroupIODeviceWeight *w;
800
801 /* FIXME: no way to reset this list */
802 LIST_FOREACH(device_weights, w, c->io_device_weights)
803 cgroup_apply_io_device_weight(u, w->path, w->weight);
804 } else if (has_blockio) {
805 CGroupBlockIODeviceWeight *w;
806
807 /* FIXME: no way to reset this list */
808 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
809 weight = cgroup_weight_blkio_to_io(w->weight);
810
811 log_cgroup_compat(u, "Applying BlockIODeviceWeight %" PRIu64 " as IODeviceWeight %" PRIu64 " for %s",
812 w->weight, weight, w->path);
813
814 cgroup_apply_io_device_weight(u, w->path, weight);
815 }
816 }
817 }
818
819 /* Apply limits and free ones without config. */
820 if (has_io) {
821 CGroupIODeviceLimit *l;
822
823 LIST_FOREACH(device_limits, l, c->io_device_limits)
824 cgroup_apply_io_device_limit(u, l->path, l->limits);
825
826 } else if (has_blockio) {
827 CGroupBlockIODeviceBandwidth *b;
828
829 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
830 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
831 CGroupIOLimitType type;
832
833 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
834 limits[type] = cgroup_io_limit_defaults[type];
835
836 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
837 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
838
839 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax for %s",
840 b->rbps, b->wbps, b->path);
841
842 cgroup_apply_io_device_limit(u, b->path, limits);
843 }
844 }
845 }
846
847 if (apply_mask & CGROUP_MASK_BLKIO) {
848 bool has_io = cgroup_context_has_io_config(c);
849 bool has_blockio = cgroup_context_has_blockio_config(c);
850
851 if (!is_root) {
852 char buf[DECIMAL_STR_MAX(uint64_t)+1];
853 uint64_t weight;
854
855 if (has_io) {
856 uint64_t io_weight = cgroup_context_io_weight(c, state);
857
858 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
859
860 log_cgroup_compat(u, "Applying [Startup]IOWeight %" PRIu64 " as [Startup]BlockIOWeight %" PRIu64,
861 io_weight, weight);
862 } else if (has_blockio)
863 weight = cgroup_context_blkio_weight(c, state);
864 else
865 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
866
867 xsprintf(buf, "%" PRIu64 "\n", weight);
868 r = cg_set_attribute("blkio", path, "blkio.weight", buf);
869 if (r < 0)
870 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
871 "Failed to set blkio.weight: %m");
872
873 if (has_io) {
874 CGroupIODeviceWeight *w;
875
876 /* FIXME: no way to reset this list */
877 LIST_FOREACH(device_weights, w, c->io_device_weights) {
878 weight = cgroup_weight_io_to_blkio(w->weight);
879
880 log_cgroup_compat(u, "Applying IODeviceWeight %" PRIu64 " as BlockIODeviceWeight %" PRIu64 " for %s",
881 w->weight, weight, w->path);
882
883 cgroup_apply_blkio_device_weight(u, w->path, weight);
884 }
885 } else if (has_blockio) {
886 CGroupBlockIODeviceWeight *w;
887
888 /* FIXME: no way to reset this list */
889 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
890 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
891 }
892 }
893
894 /* Apply limits and free ones without config. */
895 if (has_io) {
896 CGroupIODeviceLimit *l;
897
898 LIST_FOREACH(device_limits, l, c->io_device_limits) {
899 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax for %s",
900 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
901
902 cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]);
903 }
904 } else if (has_blockio) {
905 CGroupBlockIODeviceBandwidth *b;
906
907 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
908 cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps);
909 }
910 }
911
912 if ((apply_mask & CGROUP_MASK_MEMORY) && !is_root) {
913 if (cg_all_unified() > 0) {
914 uint64_t max, swap_max = CGROUP_LIMIT_MAX;
915
916 if (cgroup_context_has_unified_memory_config(c)) {
917 max = c->memory_max;
918 swap_max = c->memory_swap_max;
919 } else {
920 max = c->memory_limit;
921
922 if (max != CGROUP_LIMIT_MAX)
923 log_cgroup_compat(u, "Applying MemoryLimit %" PRIu64 " as MemoryMax", max);
924 }
925
926 cgroup_apply_unified_memory_limit(u, "memory.low", c->memory_low);
927 cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
928 cgroup_apply_unified_memory_limit(u, "memory.max", max);
929 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
930 } else {
931 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
932 uint64_t val;
933
934 if (cgroup_context_has_unified_memory_config(c)) {
935 val = c->memory_max;
936 log_cgroup_compat(u, "Applying MemoryMax %" PRIi64 " as MemoryLimit", val);
937 } else
938 val = c->memory_limit;
939
940 if (val == CGROUP_LIMIT_MAX)
941 strncpy(buf, "-1\n", sizeof(buf));
942 else
943 xsprintf(buf, "%" PRIu64 "\n", val);
944
945 r = cg_set_attribute("memory", path, "memory.limit_in_bytes", buf);
946 if (r < 0)
947 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
948 "Failed to set memory.limit_in_bytes: %m");
949 }
950 }
951
952 if ((apply_mask & CGROUP_MASK_DEVICES) && !is_root) {
953 CGroupDeviceAllow *a;
954
955 /* Changing the devices list of a populated cgroup
956 * might result in EINVAL, hence ignore EINVAL
957 * here. */
958
959 if (c->device_allow || c->device_policy != CGROUP_AUTO)
960 r = cg_set_attribute("devices", path, "devices.deny", "a");
961 else
962 r = cg_set_attribute("devices", path, "devices.allow", "a");
963 if (r < 0)
964 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
965 "Failed to reset devices.list: %m");
966
967 if (c->device_policy == CGROUP_CLOSED ||
968 (c->device_policy == CGROUP_AUTO && c->device_allow)) {
969 static const char auto_devices[] =
970 "/dev/null\0" "rwm\0"
971 "/dev/zero\0" "rwm\0"
972 "/dev/full\0" "rwm\0"
973 "/dev/random\0" "rwm\0"
974 "/dev/urandom\0" "rwm\0"
975 "/dev/tty\0" "rwm\0"
976 "/dev/ptmx\0" "rwm\0"
977 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
978 "-/run/systemd/inaccessible/chr\0" "rwm\0"
979 "-/run/systemd/inaccessible/blk\0" "rwm\0";
980
981 const char *x, *y;
982
983 NULSTR_FOREACH_PAIR(x, y, auto_devices)
984 whitelist_device(path, x, y);
985
986 /* PTS (/dev/pts) devices may not be duplicated, but accessed */
987 whitelist_major(path, "pts", 'c', "rw");
988 }
989
990 LIST_FOREACH(device_allow, a, c->device_allow) {
991 char acc[4], *val;
992 unsigned k = 0;
993
994 if (a->r)
995 acc[k++] = 'r';
996 if (a->w)
997 acc[k++] = 'w';
998 if (a->m)
999 acc[k++] = 'm';
1000
1001 if (k == 0)
1002 continue;
1003
1004 acc[k++] = 0;
1005
1006 if (path_startswith(a->path, "/dev/"))
1007 whitelist_device(path, a->path, acc);
1008 else if ((val = startswith(a->path, "block-")))
1009 whitelist_major(path, val, 'b', acc);
1010 else if ((val = startswith(a->path, "char-")))
1011 whitelist_major(path, val, 'c', acc);
1012 else
1013 log_unit_debug(u, "Ignoring device %s while writing cgroup attribute.", a->path);
1014 }
1015 }
1016
1017 if (apply_mask & CGROUP_MASK_PIDS) {
1018
1019 if (is_root) {
1020 /* So, the "pids" controller does not expose anything on the root cgroup, in order not to
1021 * replicate knobs exposed elsewhere needlessly. We abstract this away here however, and when
1022 * the knobs of the root cgroup are modified propagate this to the relevant sysctls. There's a
1023 * non-obvious asymmetry however: unlike the cgroup properties we don't really want to take
1024 * exclusive ownership of the sysctls, but we still want to honour things if the user sets
1025 * limits. Hence we employ sort of a one-way strategy: when the user sets a bounded limit
1026 * through us it counts. When the user afterwards unsets it again (i.e. sets it to unbounded)
1027 * it also counts. But if the user never set a limit through us (i.e. we are the default of
1028 * "unbounded") we leave things unmodified. For this we manage a global boolean that we turn on
1029 * the first time we set a limit. Note that this boolean is flushed out on manager reload,
1030 * which is desirable so that there's an offical way to release control of the sysctl from
1031 * systemd: set the limit to unbounded and reload. */
1032
1033 if (c->tasks_max != CGROUP_LIMIT_MAX) {
1034 u->manager->sysctl_pid_max_changed = true;
1035 r = procfs_tasks_set_limit(c->tasks_max);
1036 } else if (u->manager->sysctl_pid_max_changed)
1037 r = procfs_tasks_set_limit(TASKS_MAX);
1038 else
1039 r = 0;
1040
1041 if (r < 0)
1042 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1043 "Failed to write to tasks limit sysctls: %m");
1044
1045 } else {
1046 if (c->tasks_max != CGROUP_LIMIT_MAX) {
1047 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
1048
1049 sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
1050 r = cg_set_attribute("pids", path, "pids.max", buf);
1051 } else
1052 r = cg_set_attribute("pids", path, "pids.max", "max");
1053 if (r < 0)
1054 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1055 "Failed to set pids.max: %m");
1056 }
1057 }
1058
1059 if (apply_bpf)
1060 cgroup_apply_firewall(u);
1061 }
1062
1063 CGroupMask cgroup_context_get_mask(CGroupContext *c) {
1064 CGroupMask mask = 0;
1065
1066 /* Figure out which controllers we need */
1067
1068 if (c->cpu_accounting ||
1069 cgroup_context_has_cpu_weight(c) ||
1070 cgroup_context_has_cpu_shares(c) ||
1071 c->cpu_quota_per_sec_usec != USEC_INFINITY)
1072 mask |= CGROUP_MASK_CPUACCT | CGROUP_MASK_CPU;
1073
1074 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
1075 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
1076
1077 if (c->memory_accounting ||
1078 c->memory_limit != CGROUP_LIMIT_MAX ||
1079 cgroup_context_has_unified_memory_config(c))
1080 mask |= CGROUP_MASK_MEMORY;
1081
1082 if (c->device_allow ||
1083 c->device_policy != CGROUP_AUTO)
1084 mask |= CGROUP_MASK_DEVICES;
1085
1086 if (c->tasks_accounting ||
1087 c->tasks_max != CGROUP_LIMIT_MAX)
1088 mask |= CGROUP_MASK_PIDS;
1089
1090 return mask;
1091 }
1092
1093 CGroupMask unit_get_own_mask(Unit *u) {
1094 CGroupContext *c;
1095
1096 /* Returns the mask of controllers the unit needs for itself */
1097
1098 c = unit_get_cgroup_context(u);
1099 if (!c)
1100 return 0;
1101
1102 return cgroup_context_get_mask(c) | unit_get_delegate_mask(u);
1103 }
1104
1105 CGroupMask unit_get_delegate_mask(Unit *u) {
1106 CGroupContext *c;
1107
1108 /* If delegation is turned on, then turn on selected controllers, unless we are on the legacy hierarchy and the
1109 * process we fork into is known to drop privileges, and hence shouldn't get access to the controllers.
1110 *
1111 * Note that on the unified hierarchy it is safe to delegate controllers to unprivileged services. */
1112
1113 if (!unit_cgroup_delegate(u))
1114 return 0;
1115
1116 if (cg_all_unified() <= 0) {
1117 ExecContext *e;
1118
1119 e = unit_get_exec_context(u);
1120 if (e && !exec_context_maintains_privileges(e))
1121 return 0;
1122 }
1123
1124 assert_se(c = unit_get_cgroup_context(u));
1125 return c->delegate_controllers;
1126 }
1127
1128 CGroupMask unit_get_members_mask(Unit *u) {
1129 assert(u);
1130
1131 /* Returns the mask of controllers all of the unit's children require, merged */
1132
1133 if (u->cgroup_members_mask_valid)
1134 return u->cgroup_members_mask;
1135
1136 u->cgroup_members_mask = 0;
1137
1138 if (u->type == UNIT_SLICE) {
1139 void *v;
1140 Unit *member;
1141 Iterator i;
1142
1143 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE], i) {
1144
1145 if (member == u)
1146 continue;
1147
1148 if (UNIT_DEREF(member->slice) != u)
1149 continue;
1150
1151 u->cgroup_members_mask |= unit_get_subtree_mask(member); /* note that this calls ourselves again, for the children */
1152 }
1153 }
1154
1155 u->cgroup_members_mask_valid = true;
1156 return u->cgroup_members_mask;
1157 }
1158
1159 CGroupMask unit_get_siblings_mask(Unit *u) {
1160 assert(u);
1161
1162 /* Returns the mask of controllers all of the unit's siblings
1163 * require, i.e. the members mask of the unit's parent slice
1164 * if there is one. */
1165
1166 if (UNIT_ISSET(u->slice))
1167 return unit_get_members_mask(UNIT_DEREF(u->slice));
1168
1169 return unit_get_subtree_mask(u); /* we are the top-level slice */
1170 }
1171
1172 CGroupMask unit_get_subtree_mask(Unit *u) {
1173
1174 /* Returns the mask of this subtree, meaning of the group
1175 * itself and its children. */
1176
1177 return unit_get_own_mask(u) | unit_get_members_mask(u);
1178 }
1179
1180 CGroupMask unit_get_target_mask(Unit *u) {
1181 CGroupMask mask;
1182
1183 /* This returns the cgroup mask of all controllers to enable
1184 * for a specific cgroup, i.e. everything it needs itself,
1185 * plus all that its children need, plus all that its siblings
1186 * need. This is primarily useful on the legacy cgroup
1187 * hierarchy, where we need to duplicate each cgroup in each
1188 * hierarchy that shall be enabled for it. */
1189
1190 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
1191 mask &= u->manager->cgroup_supported;
1192
1193 return mask;
1194 }
1195
1196 CGroupMask unit_get_enable_mask(Unit *u) {
1197 CGroupMask mask;
1198
1199 /* This returns the cgroup mask of all controllers to enable
1200 * for the children of a specific cgroup. This is primarily
1201 * useful for the unified cgroup hierarchy, where each cgroup
1202 * controls which controllers are enabled for its children. */
1203
1204 mask = unit_get_members_mask(u);
1205 mask &= u->manager->cgroup_supported;
1206
1207 return mask;
1208 }
1209
1210 bool unit_get_needs_bpf(Unit *u) {
1211 CGroupContext *c;
1212 Unit *p;
1213 assert(u);
1214
1215 c = unit_get_cgroup_context(u);
1216 if (!c)
1217 return false;
1218
1219 if (c->ip_accounting ||
1220 c->ip_address_allow ||
1221 c->ip_address_deny)
1222 return true;
1223
1224 /* If any parent slice has an IP access list defined, it applies too */
1225 for (p = UNIT_DEREF(u->slice); p; p = UNIT_DEREF(p->slice)) {
1226 c = unit_get_cgroup_context(p);
1227 if (!c)
1228 return false;
1229
1230 if (c->ip_address_allow ||
1231 c->ip_address_deny)
1232 return true;
1233 }
1234
1235 return false;
1236 }
1237
1238 /* Recurse from a unit up through its containing slices, propagating
1239 * mask bits upward. A unit is also member of itself. */
1240 void unit_update_cgroup_members_masks(Unit *u) {
1241 CGroupMask m;
1242 bool more;
1243
1244 assert(u);
1245
1246 /* Calculate subtree mask */
1247 m = unit_get_subtree_mask(u);
1248
1249 /* See if anything changed from the previous invocation. If
1250 * not, we're done. */
1251 if (u->cgroup_subtree_mask_valid && m == u->cgroup_subtree_mask)
1252 return;
1253
1254 more =
1255 u->cgroup_subtree_mask_valid &&
1256 ((m & ~u->cgroup_subtree_mask) != 0) &&
1257 ((~m & u->cgroup_subtree_mask) == 0);
1258
1259 u->cgroup_subtree_mask = m;
1260 u->cgroup_subtree_mask_valid = true;
1261
1262 if (UNIT_ISSET(u->slice)) {
1263 Unit *s = UNIT_DEREF(u->slice);
1264
1265 if (more)
1266 /* There's more set now than before. We
1267 * propagate the new mask to the parent's mask
1268 * (not caring if it actually was valid or
1269 * not). */
1270
1271 s->cgroup_members_mask |= m;
1272
1273 else
1274 /* There's less set now than before (or we
1275 * don't know), we need to recalculate
1276 * everything, so let's invalidate the
1277 * parent's members mask */
1278
1279 s->cgroup_members_mask_valid = false;
1280
1281 /* And now make sure that this change also hits our
1282 * grandparents */
1283 unit_update_cgroup_members_masks(s);
1284 }
1285 }
1286
1287 const char *unit_get_realized_cgroup_path(Unit *u, CGroupMask mask) {
1288
1289 /* Returns the realized cgroup path of the specified unit where all specified controllers are available. */
1290
1291 while (u) {
1292
1293 if (u->cgroup_path &&
1294 u->cgroup_realized &&
1295 FLAGS_SET(u->cgroup_realized_mask, mask))
1296 return u->cgroup_path;
1297
1298 u = UNIT_DEREF(u->slice);
1299 }
1300
1301 return NULL;
1302 }
1303
1304 static const char *migrate_callback(CGroupMask mask, void *userdata) {
1305 return unit_get_realized_cgroup_path(userdata, mask);
1306 }
1307
1308 char *unit_default_cgroup_path(Unit *u) {
1309 _cleanup_free_ char *escaped = NULL, *slice = NULL;
1310 int r;
1311
1312 assert(u);
1313
1314 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1315 return strdup(u->manager->cgroup_root);
1316
1317 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1318 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1319 if (r < 0)
1320 return NULL;
1321 }
1322
1323 escaped = cg_escape(u->id);
1324 if (!escaped)
1325 return NULL;
1326
1327 if (slice)
1328 return strjoin(u->manager->cgroup_root, "/", slice, "/",
1329 escaped);
1330 else
1331 return strjoin(u->manager->cgroup_root, "/", escaped);
1332 }
1333
1334 int unit_set_cgroup_path(Unit *u, const char *path) {
1335 _cleanup_free_ char *p = NULL;
1336 int r;
1337
1338 assert(u);
1339
1340 if (path) {
1341 p = strdup(path);
1342 if (!p)
1343 return -ENOMEM;
1344 } else
1345 p = NULL;
1346
1347 if (streq_ptr(u->cgroup_path, p))
1348 return 0;
1349
1350 if (p) {
1351 r = hashmap_put(u->manager->cgroup_unit, p, u);
1352 if (r < 0)
1353 return r;
1354 }
1355
1356 unit_release_cgroup(u);
1357
1358 u->cgroup_path = TAKE_PTR(p);
1359
1360 return 1;
1361 }
1362
1363 int unit_watch_cgroup(Unit *u) {
1364 _cleanup_free_ char *events = NULL;
1365 int r;
1366
1367 assert(u);
1368
1369 if (!u->cgroup_path)
1370 return 0;
1371
1372 if (u->cgroup_inotify_wd >= 0)
1373 return 0;
1374
1375 /* Only applies to the unified hierarchy */
1376 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1377 if (r < 0)
1378 return log_error_errno(r, "Failed to determine whether the name=systemd hierarchy is unified: %m");
1379 if (r == 0)
1380 return 0;
1381
1382 /* Don't watch the root slice, it's pointless. */
1383 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1384 return 0;
1385
1386 r = hashmap_ensure_allocated(&u->manager->cgroup_inotify_wd_unit, &trivial_hash_ops);
1387 if (r < 0)
1388 return log_oom();
1389
1390 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1391 if (r < 0)
1392 return log_oom();
1393
1394 u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1395 if (u->cgroup_inotify_wd < 0) {
1396
1397 if (errno == ENOENT) /* If the directory is already
1398 * gone we don't need to track
1399 * it, so this is not an error */
1400 return 0;
1401
1402 return log_unit_error_errno(u, errno, "Failed to add inotify watch descriptor for control group %s: %m", u->cgroup_path);
1403 }
1404
1405 r = hashmap_put(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd), u);
1406 if (r < 0)
1407 return log_unit_error_errno(u, r, "Failed to add inotify watch descriptor to hash map: %m");
1408
1409 return 0;
1410 }
1411
1412 int unit_pick_cgroup_path(Unit *u) {
1413 _cleanup_free_ char *path = NULL;
1414 int r;
1415
1416 assert(u);
1417
1418 if (u->cgroup_path)
1419 return 0;
1420
1421 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1422 return -EINVAL;
1423
1424 path = unit_default_cgroup_path(u);
1425 if (!path)
1426 return log_oom();
1427
1428 r = unit_set_cgroup_path(u, path);
1429 if (r == -EEXIST)
1430 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1431 if (r < 0)
1432 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1433
1434 return 0;
1435 }
1436
1437 static int unit_create_cgroup(
1438 Unit *u,
1439 CGroupMask target_mask,
1440 CGroupMask enable_mask,
1441 bool needs_bpf) {
1442
1443 CGroupContext *c;
1444 int r;
1445 bool created;
1446
1447 assert(u);
1448
1449 c = unit_get_cgroup_context(u);
1450 if (!c)
1451 return 0;
1452
1453 /* Figure out our cgroup path */
1454 r = unit_pick_cgroup_path(u);
1455 if (r < 0)
1456 return r;
1457
1458 /* First, create our own group */
1459 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1460 if (r < 0)
1461 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1462 created = !!r;
1463
1464 /* Start watching it */
1465 (void) unit_watch_cgroup(u);
1466
1467 /* Preserve enabled controllers in delegated units, adjust others. */
1468 if (created || !unit_cgroup_delegate(u)) {
1469
1470 /* Enable all controllers we need */
1471 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path);
1472 if (r < 0)
1473 log_unit_warning_errno(u, r, "Failed to enable controllers on cgroup %s, ignoring: %m",
1474 u->cgroup_path);
1475 }
1476
1477 /* Keep track that this is now realized */
1478 u->cgroup_realized = true;
1479 u->cgroup_realized_mask = target_mask;
1480 u->cgroup_enabled_mask = enable_mask;
1481 u->cgroup_bpf_state = needs_bpf ? UNIT_CGROUP_BPF_ON : UNIT_CGROUP_BPF_OFF;
1482
1483 if (u->type != UNIT_SLICE && !unit_cgroup_delegate(u)) {
1484
1485 /* Then, possibly move things over, but not if
1486 * subgroups may contain processes, which is the case
1487 * for slice and delegation units. */
1488 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1489 if (r < 0)
1490 log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
1491 }
1492
1493 return 0;
1494 }
1495
1496 static int unit_attach_pid_to_cgroup_via_bus(Unit *u, pid_t pid, const char *suffix_path) {
1497 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1498 char *pp;
1499 int r;
1500
1501 assert(u);
1502
1503 if (MANAGER_IS_SYSTEM(u->manager))
1504 return -EINVAL;
1505
1506 if (!u->manager->system_bus)
1507 return -EIO;
1508
1509 if (!u->cgroup_path)
1510 return -EINVAL;
1511
1512 /* Determine this unit's cgroup path relative to our cgroup root */
1513 pp = path_startswith(u->cgroup_path, u->manager->cgroup_root);
1514 if (!pp)
1515 return -EINVAL;
1516
1517 pp = strjoina("/", pp, suffix_path);
1518 path_simplify(pp, false);
1519
1520 r = sd_bus_call_method(u->manager->system_bus,
1521 "org.freedesktop.systemd1",
1522 "/org/freedesktop/systemd1",
1523 "org.freedesktop.systemd1.Manager",
1524 "AttachProcessesToUnit",
1525 &error, NULL,
1526 "ssau",
1527 NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
1528 if (r < 0)
1529 return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
1530
1531 return 0;
1532 }
1533
1534 int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
1535 CGroupMask delegated_mask;
1536 const char *p;
1537 Iterator i;
1538 void *pidp;
1539 int r, q;
1540
1541 assert(u);
1542
1543 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1544 return -EINVAL;
1545
1546 if (set_isempty(pids))
1547 return 0;
1548
1549 r = unit_realize_cgroup(u);
1550 if (r < 0)
1551 return r;
1552
1553 if (isempty(suffix_path))
1554 p = u->cgroup_path;
1555 else
1556 p = strjoina(u->cgroup_path, "/", suffix_path);
1557
1558 delegated_mask = unit_get_delegate_mask(u);
1559
1560 r = 0;
1561 SET_FOREACH(pidp, pids, i) {
1562 pid_t pid = PTR_TO_PID(pidp);
1563 CGroupController c;
1564
1565 /* First, attach the PID to the main cgroup hierarchy */
1566 q = cg_attach(SYSTEMD_CGROUP_CONTROLLER, p, pid);
1567 if (q < 0) {
1568 log_unit_debug_errno(u, q, "Couldn't move process " PID_FMT " to requested cgroup '%s': %m", pid, p);
1569
1570 if (MANAGER_IS_USER(u->manager) && IN_SET(q, -EPERM, -EACCES)) {
1571 int z;
1572
1573 /* If we are in a user instance, and we can't move the process ourselves due to
1574 * permission problems, let's ask the system instance about it instead. Since it's more
1575 * privileged it might be able to move the process across the leaves of a subtree who's
1576 * top node is not owned by us. */
1577
1578 z = unit_attach_pid_to_cgroup_via_bus(u, pid, suffix_path);
1579 if (z < 0)
1580 log_unit_debug_errno(u, z, "Couldn't move process " PID_FMT " to requested cgroup '%s' via the system bus either: %m", pid, p);
1581 else
1582 continue; /* When the bus thing worked via the bus we are fully done for this PID. */
1583 }
1584
1585 if (r >= 0)
1586 r = q; /* Remember first error */
1587
1588 continue;
1589 }
1590
1591 q = cg_all_unified();
1592 if (q < 0)
1593 return q;
1594 if (q > 0)
1595 continue;
1596
1597 /* In the legacy hierarchy, attach the process to the request cgroup if possible, and if not to the
1598 * innermost realized one */
1599
1600 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1601 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1602 const char *realized;
1603
1604 if (!(u->manager->cgroup_supported & bit))
1605 continue;
1606
1607 /* If this controller is delegated and realized, honour the caller's request for the cgroup suffix. */
1608 if (delegated_mask & u->cgroup_realized_mask & bit) {
1609 q = cg_attach(cgroup_controller_to_string(c), p, pid);
1610 if (q >= 0)
1611 continue; /* Success! */
1612
1613 log_unit_debug_errno(u, q, "Failed to attach PID " PID_FMT " to requested cgroup %s in controller %s, falling back to unit's cgroup: %m",
1614 pid, p, cgroup_controller_to_string(c));
1615 }
1616
1617 /* So this controller is either not delegate or realized, or something else weird happened. In
1618 * that case let's attach the PID at least to the closest cgroup up the tree that is
1619 * realized. */
1620 realized = unit_get_realized_cgroup_path(u, bit);
1621 if (!realized)
1622 continue; /* Not even realized in the root slice? Then let's not bother */
1623
1624 q = cg_attach(cgroup_controller_to_string(c), realized, pid);
1625 if (q < 0)
1626 log_unit_debug_errno(u, q, "Failed to attach PID " PID_FMT " to realized cgroup %s in controller %s, ignoring: %m",
1627 pid, realized, cgroup_controller_to_string(c));
1628 }
1629 }
1630
1631 return r;
1632 }
1633
1634 static void cgroup_xattr_apply(Unit *u) {
1635 char ids[SD_ID128_STRING_MAX];
1636 int r;
1637
1638 assert(u);
1639
1640 if (!MANAGER_IS_SYSTEM(u->manager))
1641 return;
1642
1643 if (sd_id128_is_null(u->invocation_id))
1644 return;
1645
1646 r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
1647 "trusted.invocation_id",
1648 sd_id128_to_string(u->invocation_id, ids), 32,
1649 0);
1650 if (r < 0)
1651 log_unit_debug_errno(u, r, "Failed to set invocation ID on control group %s, ignoring: %m", u->cgroup_path);
1652 }
1653
1654 static bool unit_has_mask_realized(
1655 Unit *u,
1656 CGroupMask target_mask,
1657 CGroupMask enable_mask,
1658 bool needs_bpf) {
1659
1660 assert(u);
1661
1662 return u->cgroup_realized &&
1663 u->cgroup_realized_mask == target_mask &&
1664 u->cgroup_enabled_mask == enable_mask &&
1665 ((needs_bpf && u->cgroup_bpf_state == UNIT_CGROUP_BPF_ON) ||
1666 (!needs_bpf && u->cgroup_bpf_state == UNIT_CGROUP_BPF_OFF));
1667 }
1668
1669 static void unit_add_to_cgroup_realize_queue(Unit *u) {
1670 assert(u);
1671
1672 if (u->in_cgroup_realize_queue)
1673 return;
1674
1675 LIST_PREPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
1676 u->in_cgroup_realize_queue = true;
1677 }
1678
1679 static void unit_remove_from_cgroup_realize_queue(Unit *u) {
1680 assert(u);
1681
1682 if (!u->in_cgroup_realize_queue)
1683 return;
1684
1685 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
1686 u->in_cgroup_realize_queue = false;
1687 }
1688
1689 /* Check if necessary controllers and attributes for a unit are in place.
1690 *
1691 * If so, do nothing.
1692 * If not, create paths, move processes over, and set attributes.
1693 *
1694 * Returns 0 on success and < 0 on failure. */
1695 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
1696 CGroupMask target_mask, enable_mask;
1697 bool needs_bpf, apply_bpf;
1698 int r;
1699
1700 assert(u);
1701
1702 unit_remove_from_cgroup_realize_queue(u);
1703
1704 target_mask = unit_get_target_mask(u);
1705 enable_mask = unit_get_enable_mask(u);
1706 needs_bpf = unit_get_needs_bpf(u);
1707
1708 if (unit_has_mask_realized(u, target_mask, enable_mask, needs_bpf))
1709 return 0;
1710
1711 /* Make sure we apply the BPF filters either when one is configured, or if none is configured but previously
1712 * the state was anything but off. This way, if a unit with a BPF filter applied is reconfigured to lose it
1713 * this will trickle down properly to cgroupfs. */
1714 apply_bpf = needs_bpf || u->cgroup_bpf_state != UNIT_CGROUP_BPF_OFF;
1715
1716 /* First, realize parents */
1717 if (UNIT_ISSET(u->slice)) {
1718 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
1719 if (r < 0)
1720 return r;
1721 }
1722
1723 /* And then do the real work */
1724 r = unit_create_cgroup(u, target_mask, enable_mask, needs_bpf);
1725 if (r < 0)
1726 return r;
1727
1728 /* Finally, apply the necessary attributes. */
1729 cgroup_context_apply(u, target_mask, apply_bpf, state);
1730 cgroup_xattr_apply(u);
1731
1732 return 0;
1733 }
1734
1735 unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
1736 ManagerState state;
1737 unsigned n = 0;
1738 Unit *i;
1739 int r;
1740
1741 assert(m);
1742
1743 state = manager_state(m);
1744
1745 while ((i = m->cgroup_realize_queue)) {
1746 assert(i->in_cgroup_realize_queue);
1747
1748 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
1749 /* Maybe things changed, and the unit is not actually active anymore? */
1750 unit_remove_from_cgroup_realize_queue(i);
1751 continue;
1752 }
1753
1754 r = unit_realize_cgroup_now(i, state);
1755 if (r < 0)
1756 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
1757
1758 n++;
1759 }
1760
1761 return n;
1762 }
1763
1764 static void unit_add_siblings_to_cgroup_realize_queue(Unit *u) {
1765 Unit *slice;
1766
1767 /* This adds the siblings of the specified unit and the
1768 * siblings of all parent units to the cgroup queue. (But
1769 * neither the specified unit itself nor the parents.) */
1770
1771 while ((slice = UNIT_DEREF(u->slice))) {
1772 Iterator i;
1773 Unit *m;
1774 void *v;
1775
1776 HASHMAP_FOREACH_KEY(v, m, u->dependencies[UNIT_BEFORE], i) {
1777 if (m == u)
1778 continue;
1779
1780 /* Skip units that have a dependency on the slice
1781 * but aren't actually in it. */
1782 if (UNIT_DEREF(m->slice) != slice)
1783 continue;
1784
1785 /* No point in doing cgroup application for units
1786 * without active processes. */
1787 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
1788 continue;
1789
1790 /* If the unit doesn't need any new controllers
1791 * and has current ones realized, it doesn't need
1792 * any changes. */
1793 if (unit_has_mask_realized(m,
1794 unit_get_target_mask(m),
1795 unit_get_enable_mask(m),
1796 unit_get_needs_bpf(m)))
1797 continue;
1798
1799 unit_add_to_cgroup_realize_queue(m);
1800 }
1801
1802 u = slice;
1803 }
1804 }
1805
1806 int unit_realize_cgroup(Unit *u) {
1807 assert(u);
1808
1809 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1810 return 0;
1811
1812 /* So, here's the deal: when realizing the cgroups for this
1813 * unit, we need to first create all parents, but there's more
1814 * actually: for the weight-based controllers we also need to
1815 * make sure that all our siblings (i.e. units that are in the
1816 * same slice as we are) have cgroups, too. Otherwise, things
1817 * would become very uneven as each of their processes would
1818 * get as much resources as all our group together. This call
1819 * will synchronously create the parent cgroups, but will
1820 * defer work on the siblings to the next event loop
1821 * iteration. */
1822
1823 /* Add all sibling slices to the cgroup queue. */
1824 unit_add_siblings_to_cgroup_realize_queue(u);
1825
1826 /* And realize this one now (and apply the values) */
1827 return unit_realize_cgroup_now(u, manager_state(u->manager));
1828 }
1829
1830 void unit_release_cgroup(Unit *u) {
1831 assert(u);
1832
1833 /* Forgets all cgroup details for this cgroup */
1834
1835 if (u->cgroup_path) {
1836 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1837 u->cgroup_path = mfree(u->cgroup_path);
1838 }
1839
1840 if (u->cgroup_inotify_wd >= 0) {
1841 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1842 log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1843
1844 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1845 u->cgroup_inotify_wd = -1;
1846 }
1847 }
1848
1849 void unit_prune_cgroup(Unit *u) {
1850 int r;
1851 bool is_root_slice;
1852
1853 assert(u);
1854
1855 /* Removes the cgroup, if empty and possible, and stops watching it. */
1856
1857 if (!u->cgroup_path)
1858 return;
1859
1860 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
1861
1862 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1863
1864 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
1865 if (r < 0) {
1866 log_unit_debug_errno(u, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
1867 return;
1868 }
1869
1870 if (is_root_slice)
1871 return;
1872
1873 unit_release_cgroup(u);
1874
1875 u->cgroup_realized = false;
1876 u->cgroup_realized_mask = 0;
1877 u->cgroup_enabled_mask = 0;
1878 }
1879
1880 int unit_search_main_pid(Unit *u, pid_t *ret) {
1881 _cleanup_fclose_ FILE *f = NULL;
1882 pid_t pid = 0, npid, mypid;
1883 int r;
1884
1885 assert(u);
1886 assert(ret);
1887
1888 if (!u->cgroup_path)
1889 return -ENXIO;
1890
1891 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1892 if (r < 0)
1893 return r;
1894
1895 mypid = getpid_cached();
1896 while (cg_read_pid(f, &npid) > 0) {
1897 pid_t ppid;
1898
1899 if (npid == pid)
1900 continue;
1901
1902 /* Ignore processes that aren't our kids */
1903 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
1904 continue;
1905
1906 if (pid != 0)
1907 /* Dang, there's more than one daemonized PID
1908 in this group, so we don't know what process
1909 is the main process. */
1910
1911 return -ENODATA;
1912
1913 pid = npid;
1914 }
1915
1916 *ret = pid;
1917 return 0;
1918 }
1919
1920 static int unit_watch_pids_in_path(Unit *u, const char *path) {
1921 _cleanup_closedir_ DIR *d = NULL;
1922 _cleanup_fclose_ FILE *f = NULL;
1923 int ret = 0, r;
1924
1925 assert(u);
1926 assert(path);
1927
1928 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1929 if (r < 0)
1930 ret = r;
1931 else {
1932 pid_t pid;
1933
1934 while ((r = cg_read_pid(f, &pid)) > 0) {
1935 r = unit_watch_pid(u, pid);
1936 if (r < 0 && ret >= 0)
1937 ret = r;
1938 }
1939
1940 if (r < 0 && ret >= 0)
1941 ret = r;
1942 }
1943
1944 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1945 if (r < 0) {
1946 if (ret >= 0)
1947 ret = r;
1948 } else {
1949 char *fn;
1950
1951 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1952 _cleanup_free_ char *p = NULL;
1953
1954 p = strjoin(path, "/", fn);
1955 free(fn);
1956
1957 if (!p)
1958 return -ENOMEM;
1959
1960 r = unit_watch_pids_in_path(u, p);
1961 if (r < 0 && ret >= 0)
1962 ret = r;
1963 }
1964
1965 if (r < 0 && ret >= 0)
1966 ret = r;
1967 }
1968
1969 return ret;
1970 }
1971
1972 int unit_synthesize_cgroup_empty_event(Unit *u) {
1973 int r;
1974
1975 assert(u);
1976
1977 /* Enqueue a synthetic cgroup empty event if this unit doesn't watch any PIDs anymore. This is compatibility
1978 * support for non-unified systems where notifications aren't reliable, and hence need to take whatever we can
1979 * get as notification source as soon as we stopped having any useful PIDs to watch for. */
1980
1981 if (!u->cgroup_path)
1982 return -ENOENT;
1983
1984 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
1985 if (r < 0)
1986 return r;
1987 if (r > 0) /* On unified we have reliable notifications, and don't need this */
1988 return 0;
1989
1990 if (!set_isempty(u->pids))
1991 return 0;
1992
1993 unit_add_to_cgroup_empty_queue(u);
1994 return 0;
1995 }
1996
1997 int unit_watch_all_pids(Unit *u) {
1998 int r;
1999
2000 assert(u);
2001
2002 /* Adds all PIDs from our cgroup to the set of PIDs we
2003 * watch. This is a fallback logic for cases where we do not
2004 * get reliable cgroup empty notifications: we try to use
2005 * SIGCHLD as replacement. */
2006
2007 if (!u->cgroup_path)
2008 return -ENOENT;
2009
2010 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2011 if (r < 0)
2012 return r;
2013 if (r > 0) /* On unified we can use proper notifications */
2014 return 0;
2015
2016 return unit_watch_pids_in_path(u, u->cgroup_path);
2017 }
2018
2019 static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
2020 Manager *m = userdata;
2021 Unit *u;
2022 int r;
2023
2024 assert(s);
2025 assert(m);
2026
2027 u = m->cgroup_empty_queue;
2028 if (!u)
2029 return 0;
2030
2031 assert(u->in_cgroup_empty_queue);
2032 u->in_cgroup_empty_queue = false;
2033 LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
2034
2035 if (m->cgroup_empty_queue) {
2036 /* More stuff queued, let's make sure we remain enabled */
2037 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
2038 if (r < 0)
2039 log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
2040 }
2041
2042 unit_add_to_gc_queue(u);
2043
2044 if (UNIT_VTABLE(u)->notify_cgroup_empty)
2045 UNIT_VTABLE(u)->notify_cgroup_empty(u);
2046
2047 return 0;
2048 }
2049
2050 void unit_add_to_cgroup_empty_queue(Unit *u) {
2051 int r;
2052
2053 assert(u);
2054
2055 /* Note that there are four different ways how cgroup empty events reach us:
2056 *
2057 * 1. On the unified hierarchy we get an inotify event on the cgroup
2058 *
2059 * 2. On the legacy hierarchy, when running in system mode, we get a datagram on the cgroup agent socket
2060 *
2061 * 3. On the legacy hierarchy, when running in user mode, we get a D-Bus signal on the system bus
2062 *
2063 * 4. On the legacy hierarchy, in service units we start watching all processes of the cgroup for SIGCHLD as
2064 * soon as we get one SIGCHLD, to deal with unreliable cgroup notifications.
2065 *
2066 * Regardless which way we got the notification, we'll verify it here, and then add it to a separate
2067 * queue. This queue will be dispatched at a lower priority than the SIGCHLD handler, so that we always use
2068 * SIGCHLD if we can get it first, and only use the cgroup empty notifications if there's no SIGCHLD pending
2069 * (which might happen if the cgroup doesn't contain processes that are our own child, which is typically the
2070 * case for scope units). */
2071
2072 if (u->in_cgroup_empty_queue)
2073 return;
2074
2075 /* Let's verify that the cgroup is really empty */
2076 if (!u->cgroup_path)
2077 return;
2078 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
2079 if (r < 0) {
2080 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", u->cgroup_path);
2081 return;
2082 }
2083 if (r == 0)
2084 return;
2085
2086 LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
2087 u->in_cgroup_empty_queue = true;
2088
2089 /* Trigger the defer event */
2090 r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
2091 if (r < 0)
2092 log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
2093 }
2094
2095 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2096 Manager *m = userdata;
2097
2098 assert(s);
2099 assert(fd >= 0);
2100 assert(m);
2101
2102 for (;;) {
2103 union inotify_event_buffer buffer;
2104 struct inotify_event *e;
2105 ssize_t l;
2106
2107 l = read(fd, &buffer, sizeof(buffer));
2108 if (l < 0) {
2109 if (IN_SET(errno, EINTR, EAGAIN))
2110 return 0;
2111
2112 return log_error_errno(errno, "Failed to read control group inotify events: %m");
2113 }
2114
2115 FOREACH_INOTIFY_EVENT(e, buffer, l) {
2116 Unit *u;
2117
2118 if (e->wd < 0)
2119 /* Queue overflow has no watch descriptor */
2120 continue;
2121
2122 if (e->mask & IN_IGNORED)
2123 /* The watch was just removed */
2124 continue;
2125
2126 u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
2127 if (!u) /* Not that inotify might deliver
2128 * events for a watch even after it
2129 * was removed, because it was queued
2130 * before the removal. Let's ignore
2131 * this here safely. */
2132 continue;
2133
2134 unit_add_to_cgroup_empty_queue(u);
2135 }
2136 }
2137 }
2138
2139 int manager_setup_cgroup(Manager *m) {
2140 _cleanup_free_ char *path = NULL;
2141 const char *scope_path;
2142 CGroupController c;
2143 int r, all_unified;
2144 char *e;
2145
2146 assert(m);
2147
2148 /* 1. Determine hierarchy */
2149 m->cgroup_root = mfree(m->cgroup_root);
2150 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
2151 if (r < 0)
2152 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
2153
2154 /* Chop off the init scope, if we are already located in it */
2155 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2156
2157 /* LEGACY: Also chop off the system slice if we are in
2158 * it. This is to support live upgrades from older systemd
2159 * versions where PID 1 was moved there. Also see
2160 * cg_get_root_path(). */
2161 if (!e && MANAGER_IS_SYSTEM(m)) {
2162 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
2163 if (!e)
2164 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
2165 }
2166 if (e)
2167 *e = 0;
2168
2169 /* And make sure to store away the root value without trailing slash, even for the root dir, so that we can
2170 * easily prepend it everywhere. */
2171 delete_trailing_chars(m->cgroup_root, "/");
2172
2173 /* 2. Show data */
2174 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
2175 if (r < 0)
2176 return log_error_errno(r, "Cannot find cgroup mount point: %m");
2177
2178 r = cg_unified_flush();
2179 if (r < 0)
2180 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
2181
2182 all_unified = cg_all_unified();
2183 if (all_unified < 0)
2184 return log_error_errno(all_unified, "Couldn't determine whether we are in all unified mode: %m");
2185 if (all_unified > 0)
2186 log_debug("Unified cgroup hierarchy is located at %s.", path);
2187 else {
2188 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2189 if (r < 0)
2190 return log_error_errno(r, "Failed to determine whether systemd's own controller is in unified mode: %m");
2191 if (r > 0)
2192 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
2193 else
2194 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER_LEGACY ". File system hierarchy is at %s.", path);
2195 }
2196
2197 /* 3. Allocate cgroup empty defer event source */
2198 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2199 r = sd_event_add_defer(m->event, &m->cgroup_empty_event_source, on_cgroup_empty_event, m);
2200 if (r < 0)
2201 return log_error_errno(r, "Failed to create cgroup empty event source: %m");
2202
2203 r = sd_event_source_set_priority(m->cgroup_empty_event_source, SD_EVENT_PRIORITY_NORMAL-5);
2204 if (r < 0)
2205 return log_error_errno(r, "Failed to set priority of cgroup empty event source: %m");
2206
2207 r = sd_event_source_set_enabled(m->cgroup_empty_event_source, SD_EVENT_OFF);
2208 if (r < 0)
2209 return log_error_errno(r, "Failed to disable cgroup empty event source: %m");
2210
2211 (void) sd_event_source_set_description(m->cgroup_empty_event_source, "cgroup-empty");
2212
2213 /* 4. Install notifier inotify object, or agent */
2214 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0) {
2215
2216 /* In the unified hierarchy we can get cgroup empty notifications via inotify. */
2217
2218 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2219 safe_close(m->cgroup_inotify_fd);
2220
2221 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
2222 if (m->cgroup_inotify_fd < 0)
2223 return log_error_errno(errno, "Failed to create control group inotify object: %m");
2224
2225 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
2226 if (r < 0)
2227 return log_error_errno(r, "Failed to watch control group inotify object: %m");
2228
2229 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
2230 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
2231 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-4);
2232 if (r < 0)
2233 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
2234
2235 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
2236
2237 } else if (MANAGER_IS_SYSTEM(m) && m->test_run_flags == 0) {
2238
2239 /* On the legacy hierarchy we only get notifications via cgroup agents. (Which isn't really reliable,
2240 * since it does not generate events when control groups with children run empty. */
2241
2242 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
2243 if (r < 0)
2244 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
2245 else if (r > 0)
2246 log_debug("Installed release agent.");
2247 else if (r == 0)
2248 log_debug("Release agent already installed.");
2249 }
2250
2251 /* 5. Make sure we are in the special "init.scope" unit in the root slice. */
2252 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
2253 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2254 if (r >= 0) {
2255 /* Also, move all other userspace processes remaining in the root cgroup into that scope. */
2256 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
2257 if (r < 0)
2258 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
2259
2260 /* 6. And pin it, so that it cannot be unmounted */
2261 safe_close(m->pin_cgroupfs_fd);
2262 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
2263 if (m->pin_cgroupfs_fd < 0)
2264 return log_error_errno(errno, "Failed to open pin file: %m");
2265
2266 } else if (r < 0 && !m->test_run_flags)
2267 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
2268
2269 /* 7. Always enable hierarchical support if it exists... */
2270 if (!all_unified && m->test_run_flags == 0)
2271 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
2272
2273 /* 8. Figure out which controllers are supported, and log about it */
2274 r = cg_mask_supported(&m->cgroup_supported);
2275 if (r < 0)
2276 return log_error_errno(r, "Failed to determine supported controllers: %m");
2277 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
2278 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
2279
2280 return 0;
2281 }
2282
2283 void manager_shutdown_cgroup(Manager *m, bool delete) {
2284 assert(m);
2285
2286 /* We can't really delete the group, since we are in it. But
2287 * let's trim it. */
2288 if (delete && m->cgroup_root && m->test_run_flags != MANAGER_TEST_RUN_MINIMAL)
2289 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
2290
2291 m->cgroup_empty_event_source = sd_event_source_unref(m->cgroup_empty_event_source);
2292
2293 m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
2294
2295 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
2296 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
2297
2298 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
2299
2300 m->cgroup_root = mfree(m->cgroup_root);
2301 }
2302
2303 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
2304 char *p;
2305 Unit *u;
2306
2307 assert(m);
2308 assert(cgroup);
2309
2310 u = hashmap_get(m->cgroup_unit, cgroup);
2311 if (u)
2312 return u;
2313
2314 p = strdupa(cgroup);
2315 for (;;) {
2316 char *e;
2317
2318 e = strrchr(p, '/');
2319 if (!e || e == p)
2320 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
2321
2322 *e = 0;
2323
2324 u = hashmap_get(m->cgroup_unit, p);
2325 if (u)
2326 return u;
2327 }
2328 }
2329
2330 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
2331 _cleanup_free_ char *cgroup = NULL;
2332
2333 assert(m);
2334
2335 if (!pid_is_valid(pid))
2336 return NULL;
2337
2338 if (cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup) < 0)
2339 return NULL;
2340
2341 return manager_get_unit_by_cgroup(m, cgroup);
2342 }
2343
2344 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
2345 Unit *u, **array;
2346
2347 assert(m);
2348
2349 /* Note that a process might be owned by multiple units, we return only one here, which is good enough for most
2350 * cases, though not strictly correct. We prefer the one reported by cgroup membership, as that's the most
2351 * relevant one as children of the process will be assigned to that one, too, before all else. */
2352
2353 if (!pid_is_valid(pid))
2354 return NULL;
2355
2356 if (pid == getpid_cached())
2357 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
2358
2359 u = manager_get_unit_by_pid_cgroup(m, pid);
2360 if (u)
2361 return u;
2362
2363 u = hashmap_get(m->watch_pids, PID_TO_PTR(pid));
2364 if (u)
2365 return u;
2366
2367 array = hashmap_get(m->watch_pids, PID_TO_PTR(-pid));
2368 if (array)
2369 return array[0];
2370
2371 return NULL;
2372 }
2373
2374 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
2375 Unit *u;
2376
2377 assert(m);
2378 assert(cgroup);
2379
2380 /* Called on the legacy hierarchy whenever we get an explicit cgroup notification from the cgroup agent process
2381 * or from the --system instance */
2382
2383 log_debug("Got cgroup empty notification for: %s", cgroup);
2384
2385 u = manager_get_unit_by_cgroup(m, cgroup);
2386 if (!u)
2387 return 0;
2388
2389 unit_add_to_cgroup_empty_queue(u);
2390 return 1;
2391 }
2392
2393 int unit_get_memory_current(Unit *u, uint64_t *ret) {
2394 _cleanup_free_ char *v = NULL;
2395 int r;
2396
2397 assert(u);
2398 assert(ret);
2399
2400 if (!UNIT_CGROUP_BOOL(u, memory_accounting))
2401 return -ENODATA;
2402
2403 if (!u->cgroup_path)
2404 return -ENODATA;
2405
2406 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2407 if (unit_has_root_cgroup(u))
2408 return procfs_memory_get_current(ret);
2409
2410 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
2411 return -ENODATA;
2412
2413 r = cg_all_unified();
2414 if (r < 0)
2415 return r;
2416 if (r > 0)
2417 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
2418 else
2419 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
2420 if (r == -ENOENT)
2421 return -ENODATA;
2422 if (r < 0)
2423 return r;
2424
2425 return safe_atou64(v, ret);
2426 }
2427
2428 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
2429 _cleanup_free_ char *v = NULL;
2430 int r;
2431
2432 assert(u);
2433 assert(ret);
2434
2435 if (!UNIT_CGROUP_BOOL(u, tasks_accounting))
2436 return -ENODATA;
2437
2438 if (!u->cgroup_path)
2439 return -ENODATA;
2440
2441 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2442 if (unit_has_root_cgroup(u))
2443 return procfs_tasks_get_current(ret);
2444
2445 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
2446 return -ENODATA;
2447
2448 r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
2449 if (r == -ENOENT)
2450 return -ENODATA;
2451 if (r < 0)
2452 return r;
2453
2454 return safe_atou64(v, ret);
2455 }
2456
2457 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
2458 _cleanup_free_ char *v = NULL;
2459 uint64_t ns;
2460 int r;
2461
2462 assert(u);
2463 assert(ret);
2464
2465 if (!u->cgroup_path)
2466 return -ENODATA;
2467
2468 /* The root cgroup doesn't expose this information, let's get it from /proc instead */
2469 if (unit_has_root_cgroup(u))
2470 return procfs_cpu_get_usage(ret);
2471
2472 r = cg_all_unified();
2473 if (r < 0)
2474 return r;
2475 if (r > 0) {
2476 _cleanup_free_ char *val = NULL;
2477 uint64_t us;
2478
2479 if ((u->cgroup_realized_mask & CGROUP_MASK_CPU) == 0)
2480 return -ENODATA;
2481
2482 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
2483 if (r < 0)
2484 return r;
2485 if (IN_SET(r, -ENOENT, -ENXIO))
2486 return -ENODATA;
2487
2488 r = safe_atou64(val, &us);
2489 if (r < 0)
2490 return r;
2491
2492 ns = us * NSEC_PER_USEC;
2493 } else {
2494 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
2495 return -ENODATA;
2496
2497 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
2498 if (r == -ENOENT)
2499 return -ENODATA;
2500 if (r < 0)
2501 return r;
2502
2503 r = safe_atou64(v, &ns);
2504 if (r < 0)
2505 return r;
2506 }
2507
2508 *ret = ns;
2509 return 0;
2510 }
2511
2512 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
2513 nsec_t ns;
2514 int r;
2515
2516 assert(u);
2517
2518 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2519 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2520 * call this function with a NULL return value. */
2521
2522 if (!UNIT_CGROUP_BOOL(u, cpu_accounting))
2523 return -ENODATA;
2524
2525 r = unit_get_cpu_usage_raw(u, &ns);
2526 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
2527 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2528 * cached value. */
2529
2530 if (ret)
2531 *ret = u->cpu_usage_last;
2532 return 0;
2533 }
2534 if (r < 0)
2535 return r;
2536
2537 if (ns > u->cpu_usage_base)
2538 ns -= u->cpu_usage_base;
2539 else
2540 ns = 0;
2541
2542 u->cpu_usage_last = ns;
2543 if (ret)
2544 *ret = ns;
2545
2546 return 0;
2547 }
2548
2549 int unit_get_ip_accounting(
2550 Unit *u,
2551 CGroupIPAccountingMetric metric,
2552 uint64_t *ret) {
2553
2554 uint64_t value;
2555 int fd, r;
2556
2557 assert(u);
2558 assert(metric >= 0);
2559 assert(metric < _CGROUP_IP_ACCOUNTING_METRIC_MAX);
2560 assert(ret);
2561
2562 if (!UNIT_CGROUP_BOOL(u, ip_accounting))
2563 return -ENODATA;
2564
2565 fd = IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_INGRESS_PACKETS) ?
2566 u->ip_accounting_ingress_map_fd :
2567 u->ip_accounting_egress_map_fd;
2568 if (fd < 0)
2569 return -ENODATA;
2570
2571 if (IN_SET(metric, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
2572 r = bpf_firewall_read_accounting(fd, &value, NULL);
2573 else
2574 r = bpf_firewall_read_accounting(fd, NULL, &value);
2575 if (r < 0)
2576 return r;
2577
2578 /* Add in additional metrics from a previous runtime. Note that when reexecing/reloading the daemon we compile
2579 * all BPF programs and maps anew, but serialize the old counters. When deserializing we store them in the
2580 * ip_accounting_extra[] field, and add them in here transparently. */
2581
2582 *ret = value + u->ip_accounting_extra[metric];
2583
2584 return r;
2585 }
2586
2587 int unit_reset_cpu_accounting(Unit *u) {
2588 nsec_t ns;
2589 int r;
2590
2591 assert(u);
2592
2593 u->cpu_usage_last = NSEC_INFINITY;
2594
2595 r = unit_get_cpu_usage_raw(u, &ns);
2596 if (r < 0) {
2597 u->cpu_usage_base = 0;
2598 return r;
2599 }
2600
2601 u->cpu_usage_base = ns;
2602 return 0;
2603 }
2604
2605 int unit_reset_ip_accounting(Unit *u) {
2606 int r = 0, q = 0;
2607
2608 assert(u);
2609
2610 if (u->ip_accounting_ingress_map_fd >= 0)
2611 r = bpf_firewall_reset_accounting(u->ip_accounting_ingress_map_fd);
2612
2613 if (u->ip_accounting_egress_map_fd >= 0)
2614 q = bpf_firewall_reset_accounting(u->ip_accounting_egress_map_fd);
2615
2616 zero(u->ip_accounting_extra);
2617
2618 return r < 0 ? r : q;
2619 }
2620
2621 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
2622 assert(u);
2623
2624 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2625 return;
2626
2627 if (m == 0)
2628 return;
2629
2630 /* always invalidate compat pairs together */
2631 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
2632 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
2633
2634 if (m & (CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT))
2635 m |= CGROUP_MASK_CPU | CGROUP_MASK_CPUACCT;
2636
2637 if ((u->cgroup_realized_mask & m) == 0) /* NOP? */
2638 return;
2639
2640 u->cgroup_realized_mask &= ~m;
2641 unit_add_to_cgroup_realize_queue(u);
2642 }
2643
2644 void unit_invalidate_cgroup_bpf(Unit *u) {
2645 assert(u);
2646
2647 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2648 return;
2649
2650 if (u->cgroup_bpf_state == UNIT_CGROUP_BPF_INVALIDATED) /* NOP? */
2651 return;
2652
2653 u->cgroup_bpf_state = UNIT_CGROUP_BPF_INVALIDATED;
2654 unit_add_to_cgroup_realize_queue(u);
2655
2656 /* If we are a slice unit, we also need to put compile a new BPF program for all our children, as the IP access
2657 * list of our children includes our own. */
2658 if (u->type == UNIT_SLICE) {
2659 Unit *member;
2660 Iterator i;
2661 void *v;
2662
2663 HASHMAP_FOREACH_KEY(v, member, u->dependencies[UNIT_BEFORE], i) {
2664 if (member == u)
2665 continue;
2666
2667 if (UNIT_DEREF(member->slice) != u)
2668 continue;
2669
2670 unit_invalidate_cgroup_bpf(member);
2671 }
2672 }
2673 }
2674
2675 bool unit_cgroup_delegate(Unit *u) {
2676 CGroupContext *c;
2677
2678 assert(u);
2679
2680 if (!UNIT_VTABLE(u)->can_delegate)
2681 return false;
2682
2683 c = unit_get_cgroup_context(u);
2684 if (!c)
2685 return false;
2686
2687 return c->delegate;
2688 }
2689
2690 void manager_invalidate_startup_units(Manager *m) {
2691 Iterator i;
2692 Unit *u;
2693
2694 assert(m);
2695
2696 SET_FOREACH(u, m->startup_units, i)
2697 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
2698 }
2699
2700 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
2701 [CGROUP_AUTO] = "auto",
2702 [CGROUP_CLOSED] = "closed",
2703 [CGROUP_STRICT] = "strict",
2704 };
2705
2706 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);