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