]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/cgroup.c
bd6248406f8dd5c7429c975ff610776db72b936f
[thirdparty/systemd.git] / src / core / cgroup.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2013 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <fcntl.h>
21 #include <fnmatch.h>
22
23 #include "alloc-util.h"
24 #include "cgroup-util.h"
25 #include "cgroup.h"
26 #include "fd-util.h"
27 #include "fileio.h"
28 #include "fs-util.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "process-util.h"
32 #include "special.h"
33 #include "string-table.h"
34 #include "string-util.h"
35 #include "stdio-util.h"
36
37 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
38
39 static void cgroup_compat_warn(void) {
40 static bool cgroup_compat_warned = false;
41
42 if (cgroup_compat_warned)
43 return;
44
45 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. See cgroup-compat debug messages for details.");
46 cgroup_compat_warned = true;
47 }
48
49 #define log_cgroup_compat(unit, fmt, ...) do { \
50 cgroup_compat_warn(); \
51 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
52 } while (false)
53
54 void cgroup_context_init(CGroupContext *c) {
55 assert(c);
56
57 /* Initialize everything to the kernel defaults, assuming the
58 * structure is preinitialized to 0 */
59
60 c->cpu_weight = CGROUP_WEIGHT_INVALID;
61 c->startup_cpu_weight = CGROUP_WEIGHT_INVALID;
62 c->cpu_quota_per_sec_usec = USEC_INFINITY;
63
64 c->cpu_shares = CGROUP_CPU_SHARES_INVALID;
65 c->startup_cpu_shares = CGROUP_CPU_SHARES_INVALID;
66
67 c->memory_high = CGROUP_LIMIT_MAX;
68 c->memory_max = CGROUP_LIMIT_MAX;
69 c->memory_swap_max = CGROUP_LIMIT_MAX;
70
71 c->memory_limit = CGROUP_LIMIT_MAX;
72
73 c->io_weight = CGROUP_WEIGHT_INVALID;
74 c->startup_io_weight = CGROUP_WEIGHT_INVALID;
75
76 c->blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
77 c->startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
78
79 c->tasks_max = (uint64_t) -1;
80 }
81
82 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
83 assert(c);
84 assert(a);
85
86 LIST_REMOVE(device_allow, c->device_allow, a);
87 free(a->path);
88 free(a);
89 }
90
91 void cgroup_context_free_io_device_weight(CGroupContext *c, CGroupIODeviceWeight *w) {
92 assert(c);
93 assert(w);
94
95 LIST_REMOVE(device_weights, c->io_device_weights, w);
96 free(w->path);
97 free(w);
98 }
99
100 void cgroup_context_free_io_device_limit(CGroupContext *c, CGroupIODeviceLimit *l) {
101 assert(c);
102 assert(l);
103
104 LIST_REMOVE(device_limits, c->io_device_limits, l);
105 free(l->path);
106 free(l);
107 }
108
109 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
110 assert(c);
111 assert(w);
112
113 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
114 free(w->path);
115 free(w);
116 }
117
118 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
119 assert(c);
120 assert(b);
121
122 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
123 free(b->path);
124 free(b);
125 }
126
127 void cgroup_context_done(CGroupContext *c) {
128 assert(c);
129
130 while (c->io_device_weights)
131 cgroup_context_free_io_device_weight(c, c->io_device_weights);
132
133 while (c->io_device_limits)
134 cgroup_context_free_io_device_limit(c, c->io_device_limits);
135
136 while (c->blockio_device_weights)
137 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
138
139 while (c->blockio_device_bandwidths)
140 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
141
142 while (c->device_allow)
143 cgroup_context_free_device_allow(c, c->device_allow);
144 }
145
146 void cgroup_context_dump(CGroupContext *c, FILE* f, const char *prefix) {
147 CGroupIODeviceLimit *il;
148 CGroupIODeviceWeight *iw;
149 CGroupBlockIODeviceBandwidth *b;
150 CGroupBlockIODeviceWeight *w;
151 CGroupDeviceAllow *a;
152 char u[FORMAT_TIMESPAN_MAX];
153
154 assert(c);
155 assert(f);
156
157 prefix = strempty(prefix);
158
159 fprintf(f,
160 "%sCPUAccounting=%s\n"
161 "%sIOAccounting=%s\n"
162 "%sBlockIOAccounting=%s\n"
163 "%sMemoryAccounting=%s\n"
164 "%sTasksAccounting=%s\n"
165 "%sCPUWeight=%" PRIu64 "\n"
166 "%sStartupCPUWeight=%" PRIu64 "\n"
167 "%sCPUShares=%" PRIu64 "\n"
168 "%sStartupCPUShares=%" PRIu64 "\n"
169 "%sCPUQuotaPerSecSec=%s\n"
170 "%sIOWeight=%" PRIu64 "\n"
171 "%sStartupIOWeight=%" PRIu64 "\n"
172 "%sBlockIOWeight=%" PRIu64 "\n"
173 "%sStartupBlockIOWeight=%" PRIu64 "\n"
174 "%sMemoryLow=%" PRIu64 "\n"
175 "%sMemoryHigh=%" PRIu64 "\n"
176 "%sMemoryMax=%" PRIu64 "\n"
177 "%sMemorySwapMax=%" PRIu64 "\n"
178 "%sMemoryLimit=%" PRIu64 "\n"
179 "%sTasksMax=%" PRIu64 "\n"
180 "%sDevicePolicy=%s\n"
181 "%sDelegate=%s\n",
182 prefix, yes_no(c->cpu_accounting),
183 prefix, yes_no(c->io_accounting),
184 prefix, yes_no(c->blockio_accounting),
185 prefix, yes_no(c->memory_accounting),
186 prefix, yes_no(c->tasks_accounting),
187 prefix, c->cpu_weight,
188 prefix, c->startup_cpu_weight,
189 prefix, c->cpu_shares,
190 prefix, c->startup_cpu_shares,
191 prefix, format_timespan(u, sizeof(u), c->cpu_quota_per_sec_usec, 1),
192 prefix, c->io_weight,
193 prefix, c->startup_io_weight,
194 prefix, c->blockio_weight,
195 prefix, c->startup_blockio_weight,
196 prefix, c->memory_low,
197 prefix, c->memory_high,
198 prefix, c->memory_max,
199 prefix, c->memory_swap_max,
200 prefix, c->memory_limit,
201 prefix, c->tasks_max,
202 prefix, cgroup_device_policy_to_string(c->device_policy),
203 prefix, yes_no(c->delegate));
204
205 LIST_FOREACH(device_allow, a, c->device_allow)
206 fprintf(f,
207 "%sDeviceAllow=%s %s%s%s\n",
208 prefix,
209 a->path,
210 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
211
212 LIST_FOREACH(device_weights, iw, c->io_device_weights)
213 fprintf(f,
214 "%sIODeviceWeight=%s %" PRIu64,
215 prefix,
216 iw->path,
217 iw->weight);
218
219 LIST_FOREACH(device_limits, il, c->io_device_limits) {
220 char buf[FORMAT_BYTES_MAX];
221 CGroupIOLimitType type;
222
223 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
224 if (il->limits[type] != cgroup_io_limit_defaults[type])
225 fprintf(f,
226 "%s%s=%s %s\n",
227 prefix,
228 cgroup_io_limit_type_to_string(type),
229 il->path,
230 format_bytes(buf, sizeof(buf), il->limits[type]));
231 }
232
233 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
234 fprintf(f,
235 "%sBlockIODeviceWeight=%s %" PRIu64,
236 prefix,
237 w->path,
238 w->weight);
239
240 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
241 char buf[FORMAT_BYTES_MAX];
242
243 if (b->rbps != CGROUP_LIMIT_MAX)
244 fprintf(f,
245 "%sBlockIOReadBandwidth=%s %s\n",
246 prefix,
247 b->path,
248 format_bytes(buf, sizeof(buf), b->rbps));
249 if (b->wbps != CGROUP_LIMIT_MAX)
250 fprintf(f,
251 "%sBlockIOWriteBandwidth=%s %s\n",
252 prefix,
253 b->path,
254 format_bytes(buf, sizeof(buf), b->wbps));
255 }
256 }
257
258 static int lookup_block_device(const char *p, dev_t *dev) {
259 struct stat st;
260 int r;
261
262 assert(p);
263 assert(dev);
264
265 r = stat(p, &st);
266 if (r < 0)
267 return log_warning_errno(errno, "Couldn't stat device %s: %m", p);
268
269 if (S_ISBLK(st.st_mode))
270 *dev = st.st_rdev;
271 else if (major(st.st_dev) != 0) {
272 /* If this is not a device node then find the block
273 * device this file is stored on */
274 *dev = st.st_dev;
275
276 /* If this is a partition, try to get the originating
277 * block device */
278 block_get_whole_disk(*dev, dev);
279 } else {
280 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p);
281 return -ENODEV;
282 }
283
284 return 0;
285 }
286
287 static int whitelist_device(const char *path, const char *node, const char *acc) {
288 char buf[2+DECIMAL_STR_MAX(dev_t)*2+2+4];
289 struct stat st;
290 int r;
291
292 assert(path);
293 assert(acc);
294
295 if (stat(node, &st) < 0) {
296 log_warning("Couldn't stat device %s", node);
297 return -errno;
298 }
299
300 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
301 log_warning("%s is not a device.", node);
302 return -ENODEV;
303 }
304
305 sprintf(buf,
306 "%c %u:%u %s",
307 S_ISCHR(st.st_mode) ? 'c' : 'b',
308 major(st.st_rdev), minor(st.st_rdev),
309 acc);
310
311 r = cg_set_attribute("devices", path, "devices.allow", buf);
312 if (r < 0)
313 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
314 "Failed to set devices.allow on %s: %m", path);
315
316 return r;
317 }
318
319 static int whitelist_major(const char *path, const char *name, char type, const char *acc) {
320 _cleanup_fclose_ FILE *f = NULL;
321 char line[LINE_MAX];
322 bool good = false;
323 int r;
324
325 assert(path);
326 assert(acc);
327 assert(type == 'b' || type == 'c');
328
329 f = fopen("/proc/devices", "re");
330 if (!f)
331 return log_warning_errno(errno, "Cannot open /proc/devices to resolve %s (%c): %m", name, type);
332
333 FOREACH_LINE(line, f, goto fail) {
334 char buf[2+DECIMAL_STR_MAX(unsigned)+3+4], *p, *w;
335 unsigned maj;
336
337 truncate_nl(line);
338
339 if (type == 'c' && streq(line, "Character devices:")) {
340 good = true;
341 continue;
342 }
343
344 if (type == 'b' && streq(line, "Block devices:")) {
345 good = true;
346 continue;
347 }
348
349 if (isempty(line)) {
350 good = false;
351 continue;
352 }
353
354 if (!good)
355 continue;
356
357 p = strstrip(line);
358
359 w = strpbrk(p, WHITESPACE);
360 if (!w)
361 continue;
362 *w = 0;
363
364 r = safe_atou(p, &maj);
365 if (r < 0)
366 continue;
367 if (maj <= 0)
368 continue;
369
370 w++;
371 w += strspn(w, WHITESPACE);
372
373 if (fnmatch(name, w, 0) != 0)
374 continue;
375
376 sprintf(buf,
377 "%c %u:* %s",
378 type,
379 maj,
380 acc);
381
382 r = cg_set_attribute("devices", path, "devices.allow", buf);
383 if (r < 0)
384 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
385 "Failed to set devices.allow on %s: %m", path);
386 }
387
388 return 0;
389
390 fail:
391 log_warning_errno(errno, "Failed to read /proc/devices: %m");
392 return -errno;
393 }
394
395 static bool cgroup_context_has_cpu_weight(CGroupContext *c) {
396 return c->cpu_weight != CGROUP_WEIGHT_INVALID ||
397 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID;
398 }
399
400 static bool cgroup_context_has_cpu_shares(CGroupContext *c) {
401 return c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
402 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID;
403 }
404
405 static uint64_t cgroup_context_cpu_weight(CGroupContext *c, ManagerState state) {
406 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
407 c->startup_cpu_weight != CGROUP_WEIGHT_INVALID)
408 return c->startup_cpu_weight;
409 else if (c->cpu_weight != CGROUP_WEIGHT_INVALID)
410 return c->cpu_weight;
411 else
412 return CGROUP_WEIGHT_DEFAULT;
413 }
414
415 static uint64_t cgroup_context_cpu_shares(CGroupContext *c, ManagerState state) {
416 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
417 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID)
418 return c->startup_cpu_shares;
419 else if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID)
420 return c->cpu_shares;
421 else
422 return CGROUP_CPU_SHARES_DEFAULT;
423 }
424
425 static void cgroup_apply_unified_cpu_config(Unit *u, uint64_t weight, uint64_t quota) {
426 char buf[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t) + 1) * 2)];
427 int r;
428
429 xsprintf(buf, "%" PRIu64 "\n", weight);
430 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.weight", buf);
431 if (r < 0)
432 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
433 "Failed to set cpu.weight: %m");
434
435 if (quota != USEC_INFINITY)
436 xsprintf(buf, USEC_FMT " " USEC_FMT "\n",
437 quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC, CGROUP_CPU_QUOTA_PERIOD_USEC);
438 else
439 xsprintf(buf, "max " USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
440
441 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.max", buf);
442
443 if (r < 0)
444 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
445 "Failed to set cpu.max: %m");
446 }
447
448 static void cgroup_apply_legacy_cpu_config(Unit *u, uint64_t shares, uint64_t quota) {
449 char buf[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t)) + 1];
450 int r;
451
452 xsprintf(buf, "%" PRIu64 "\n", shares);
453 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.shares", buf);
454 if (r < 0)
455 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
456 "Failed to set cpu.shares: %m");
457
458 xsprintf(buf, USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
459 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_period_us", buf);
460 if (r < 0)
461 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
462 "Failed to set cpu.cfs_period_us: %m");
463
464 if (quota != USEC_INFINITY) {
465 xsprintf(buf, USEC_FMT "\n", quota * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC);
466 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", buf);
467 } else
468 r = cg_set_attribute("cpu", u->cgroup_path, "cpu.cfs_quota_us", "-1");
469 if (r < 0)
470 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
471 "Failed to set cpu.cfs_quota_us: %m");
472 }
473
474 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares) {
475 return CLAMP(shares * CGROUP_WEIGHT_DEFAULT / CGROUP_CPU_SHARES_DEFAULT,
476 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
477 }
478
479 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight) {
480 return CLAMP(weight * CGROUP_CPU_SHARES_DEFAULT / CGROUP_WEIGHT_DEFAULT,
481 CGROUP_CPU_SHARES_MIN, CGROUP_CPU_SHARES_MAX);
482 }
483
484 static bool cgroup_context_has_io_config(CGroupContext *c) {
485 return c->io_accounting ||
486 c->io_weight != CGROUP_WEIGHT_INVALID ||
487 c->startup_io_weight != CGROUP_WEIGHT_INVALID ||
488 c->io_device_weights ||
489 c->io_device_limits;
490 }
491
492 static bool cgroup_context_has_blockio_config(CGroupContext *c) {
493 return c->blockio_accounting ||
494 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
495 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
496 c->blockio_device_weights ||
497 c->blockio_device_bandwidths;
498 }
499
500 static uint64_t cgroup_context_io_weight(CGroupContext *c, ManagerState state) {
501 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
502 c->startup_io_weight != CGROUP_WEIGHT_INVALID)
503 return c->startup_io_weight;
504 else if (c->io_weight != CGROUP_WEIGHT_INVALID)
505 return c->io_weight;
506 else
507 return CGROUP_WEIGHT_DEFAULT;
508 }
509
510 static uint64_t cgroup_context_blkio_weight(CGroupContext *c, ManagerState state) {
511 if (IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) &&
512 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
513 return c->startup_blockio_weight;
514 else if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID)
515 return c->blockio_weight;
516 else
517 return CGROUP_BLKIO_WEIGHT_DEFAULT;
518 }
519
520 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight) {
521 return CLAMP(blkio_weight * CGROUP_WEIGHT_DEFAULT / CGROUP_BLKIO_WEIGHT_DEFAULT,
522 CGROUP_WEIGHT_MIN, CGROUP_WEIGHT_MAX);
523 }
524
525 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight) {
526 return CLAMP(io_weight * CGROUP_BLKIO_WEIGHT_DEFAULT / CGROUP_WEIGHT_DEFAULT,
527 CGROUP_BLKIO_WEIGHT_MIN, CGROUP_BLKIO_WEIGHT_MAX);
528 }
529
530 static void cgroup_apply_io_device_weight(Unit *u, const char *dev_path, uint64_t io_weight) {
531 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
532 dev_t dev;
533 int r;
534
535 r = lookup_block_device(dev_path, &dev);
536 if (r < 0)
537 return;
538
539 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), io_weight);
540 r = cg_set_attribute("io", u->cgroup_path, "io.weight", buf);
541 if (r < 0)
542 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
543 "Failed to set io.weight: %m");
544 }
545
546 static void cgroup_apply_blkio_device_weight(Unit *u, const char *dev_path, uint64_t blkio_weight) {
547 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
548 dev_t dev;
549 int r;
550
551 r = lookup_block_device(dev_path, &dev);
552 if (r < 0)
553 return;
554
555 xsprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), blkio_weight);
556 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.weight_device", buf);
557 if (r < 0)
558 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
559 "Failed to set blkio.weight_device: %m");
560 }
561
562 static unsigned cgroup_apply_io_device_limit(Unit *u, const char *dev_path, uint64_t *limits) {
563 char limit_bufs[_CGROUP_IO_LIMIT_TYPE_MAX][DECIMAL_STR_MAX(uint64_t)];
564 char buf[DECIMAL_STR_MAX(dev_t)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
565 CGroupIOLimitType type;
566 dev_t dev;
567 unsigned n = 0;
568 int r;
569
570 r = lookup_block_device(dev_path, &dev);
571 if (r < 0)
572 return 0;
573
574 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++) {
575 if (limits[type] != cgroup_io_limit_defaults[type]) {
576 xsprintf(limit_bufs[type], "%" PRIu64, limits[type]);
577 n++;
578 } else {
579 xsprintf(limit_bufs[type], "%s", limits[type] == CGROUP_LIMIT_MAX ? "max" : "0");
580 }
581 }
582
583 xsprintf(buf, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev), minor(dev),
584 limit_bufs[CGROUP_IO_RBPS_MAX], limit_bufs[CGROUP_IO_WBPS_MAX],
585 limit_bufs[CGROUP_IO_RIOPS_MAX], limit_bufs[CGROUP_IO_WIOPS_MAX]);
586 r = cg_set_attribute("io", u->cgroup_path, "io.max", buf);
587 if (r < 0)
588 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
589 "Failed to set io.max: %m");
590 return n;
591 }
592
593 static unsigned cgroup_apply_blkio_device_limit(Unit *u, const char *dev_path, uint64_t rbps, uint64_t wbps) {
594 char buf[DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
595 dev_t dev;
596 unsigned n = 0;
597 int r;
598
599 r = lookup_block_device(dev_path, &dev);
600 if (r < 0)
601 return 0;
602
603 if (rbps != CGROUP_LIMIT_MAX)
604 n++;
605 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), rbps);
606 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.read_bps_device", buf);
607 if (r < 0)
608 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
609 "Failed to set blkio.throttle.read_bps_device: %m");
610
611 if (wbps != CGROUP_LIMIT_MAX)
612 n++;
613 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), wbps);
614 r = cg_set_attribute("blkio", u->cgroup_path, "blkio.throttle.write_bps_device", buf);
615 if (r < 0)
616 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
617 "Failed to set blkio.throttle.write_bps_device: %m");
618
619 return n;
620 }
621
622 static bool cgroup_context_has_unified_memory_config(CGroupContext *c) {
623 return c->memory_low > 0 || c->memory_high != CGROUP_LIMIT_MAX || c->memory_max != CGROUP_LIMIT_MAX || c->memory_swap_max != CGROUP_LIMIT_MAX;
624 }
625
626 static void cgroup_apply_unified_memory_limit(Unit *u, const char *file, uint64_t v) {
627 char buf[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
628 int r;
629
630 if (v != CGROUP_LIMIT_MAX)
631 xsprintf(buf, "%" PRIu64 "\n", v);
632
633 r = cg_set_attribute("memory", u->cgroup_path, file, buf);
634 if (r < 0)
635 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
636 "Failed to set %s: %m", file);
637 }
638
639 static void cgroup_context_apply(Unit *u, CGroupMask mask, ManagerState state) {
640 const char *path;
641 CGroupContext *c;
642 bool is_root;
643 int r;
644
645 assert(u);
646
647 c = unit_get_cgroup_context(u);
648 path = u->cgroup_path;
649
650 assert(c);
651 assert(path);
652
653 if (mask == 0)
654 return;
655
656 /* Some cgroup attributes are not supported on the root cgroup,
657 * hence silently ignore */
658 is_root = isempty(path) || path_equal(path, "/");
659 if (is_root)
660 /* Make sure we don't try to display messages with an empty path. */
661 path = "/";
662
663 /* We generally ignore errors caused by read-only mounted
664 * cgroup trees (assuming we are running in a container then),
665 * and missing cgroups, i.e. EROFS and ENOENT. */
666
667 if ((mask & CGROUP_MASK_CPU) && !is_root) {
668 bool has_weight = cgroup_context_has_cpu_weight(c);
669 bool has_shares = cgroup_context_has_cpu_shares(c);
670
671 if (cg_all_unified() > 0) {
672 uint64_t weight;
673
674 if (has_weight)
675 weight = cgroup_context_cpu_weight(c, state);
676 else if (has_shares) {
677 uint64_t shares = cgroup_context_cpu_shares(c, state);
678
679 weight = cgroup_cpu_shares_to_weight(shares);
680
681 log_cgroup_compat(u, "Applying [Startup]CpuShares %" PRIu64 " as [Startup]CpuWeight %" PRIu64 " on %s",
682 shares, weight, path);
683 } else
684 weight = CGROUP_WEIGHT_DEFAULT;
685
686 cgroup_apply_unified_cpu_config(u, weight, c->cpu_quota_per_sec_usec);
687 } else {
688 uint64_t shares;
689
690 if (has_weight) {
691 uint64_t weight = cgroup_context_cpu_weight(c, state);
692
693 shares = cgroup_cpu_weight_to_shares(weight);
694
695 log_cgroup_compat(u, "Applying [Startup]CpuWeight %" PRIu64 " as [Startup]CpuShares %" PRIu64 " on %s",
696 weight, shares, path);
697 } else if (has_shares)
698 shares = cgroup_context_cpu_shares(c, state);
699 else
700 shares = CGROUP_CPU_SHARES_DEFAULT;
701
702 cgroup_apply_legacy_cpu_config(u, shares, c->cpu_quota_per_sec_usec);
703 }
704 }
705
706 if (mask & CGROUP_MASK_IO) {
707 bool has_io = cgroup_context_has_io_config(c);
708 bool has_blockio = cgroup_context_has_blockio_config(c);
709
710 if (!is_root) {
711 char buf[8+DECIMAL_STR_MAX(uint64_t)+1];
712 uint64_t weight;
713
714 if (has_io)
715 weight = cgroup_context_io_weight(c, state);
716 else if (has_blockio) {
717 uint64_t blkio_weight = cgroup_context_blkio_weight(c, state);
718
719 weight = cgroup_weight_blkio_to_io(blkio_weight);
720
721 log_cgroup_compat(u, "Applying [Startup]BlockIOWeight %" PRIu64 " as [Startup]IOWeight %" PRIu64,
722 blkio_weight, weight);
723 } else
724 weight = CGROUP_WEIGHT_DEFAULT;
725
726 xsprintf(buf, "default %" PRIu64 "\n", weight);
727 r = cg_set_attribute("io", path, "io.weight", buf);
728 if (r < 0)
729 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
730 "Failed to set io.weight: %m");
731
732 if (has_io) {
733 CGroupIODeviceWeight *w;
734
735 /* FIXME: no way to reset this list */
736 LIST_FOREACH(device_weights, w, c->io_device_weights)
737 cgroup_apply_io_device_weight(u, w->path, w->weight);
738 } else if (has_blockio) {
739 CGroupBlockIODeviceWeight *w;
740
741 /* FIXME: no way to reset this list */
742 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
743 weight = cgroup_weight_blkio_to_io(w->weight);
744
745 log_cgroup_compat(u, "Applying BlockIODeviceWeight %" PRIu64 " as IODeviceWeight %" PRIu64 " for %s",
746 w->weight, weight, w->path);
747
748 cgroup_apply_io_device_weight(u, w->path, weight);
749 }
750 }
751 }
752
753 /* Apply limits and free ones without config. */
754 if (has_io) {
755 CGroupIODeviceLimit *l, *next;
756
757 LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
758 if (!cgroup_apply_io_device_limit(u, l->path, l->limits))
759 cgroup_context_free_io_device_limit(c, l);
760 }
761 } else if (has_blockio) {
762 CGroupBlockIODeviceBandwidth *b, *next;
763
764 LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths) {
765 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
766 CGroupIOLimitType type;
767
768 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
769 limits[type] = cgroup_io_limit_defaults[type];
770
771 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
772 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
773
774 log_cgroup_compat(u, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as IO{Read|Write}BandwidthMax for %s",
775 b->rbps, b->wbps, b->path);
776
777 if (!cgroup_apply_io_device_limit(u, b->path, limits))
778 cgroup_context_free_blockio_device_bandwidth(c, b);
779 }
780 }
781 }
782
783 if (mask & CGROUP_MASK_BLKIO) {
784 bool has_io = cgroup_context_has_io_config(c);
785 bool has_blockio = cgroup_context_has_blockio_config(c);
786
787 if (!is_root) {
788 char buf[DECIMAL_STR_MAX(uint64_t)+1];
789 uint64_t weight;
790
791 if (has_io) {
792 uint64_t io_weight = cgroup_context_io_weight(c, state);
793
794 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
795
796 log_cgroup_compat(u, "Applying [Startup]IOWeight %" PRIu64 " as [Startup]BlockIOWeight %" PRIu64,
797 io_weight, weight);
798 } else if (has_blockio)
799 weight = cgroup_context_blkio_weight(c, state);
800 else
801 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
802
803 xsprintf(buf, "%" PRIu64 "\n", weight);
804 r = cg_set_attribute("blkio", path, "blkio.weight", buf);
805 if (r < 0)
806 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
807 "Failed to set blkio.weight: %m");
808
809 if (has_io) {
810 CGroupIODeviceWeight *w;
811
812 /* FIXME: no way to reset this list */
813 LIST_FOREACH(device_weights, w, c->io_device_weights) {
814 weight = cgroup_weight_io_to_blkio(w->weight);
815
816 log_cgroup_compat(u, "Applying IODeviceWeight %" PRIu64 " as BlockIODeviceWeight %" PRIu64 " for %s",
817 w->weight, weight, w->path);
818
819 cgroup_apply_blkio_device_weight(u, w->path, weight);
820 }
821 } else if (has_blockio) {
822 CGroupBlockIODeviceWeight *w;
823
824 /* FIXME: no way to reset this list */
825 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
826 cgroup_apply_blkio_device_weight(u, w->path, w->weight);
827 }
828 }
829
830 /* Apply limits and free ones without config. */
831 if (has_io) {
832 CGroupIODeviceLimit *l, *next;
833
834 LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
835 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax for %s",
836 l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
837
838 if (!cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]))
839 cgroup_context_free_io_device_limit(c, l);
840 }
841 } else if (has_blockio) {
842 CGroupBlockIODeviceBandwidth *b, *next;
843
844 LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths)
845 if (!cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps))
846 cgroup_context_free_blockio_device_bandwidth(c, b);
847 }
848 }
849
850 if ((mask & CGROUP_MASK_MEMORY) && !is_root) {
851 if (cg_all_unified() > 0) {
852 uint64_t max;
853 uint64_t swap_max = CGROUP_LIMIT_MAX;
854
855 if (cgroup_context_has_unified_memory_config(c)) {
856 max = c->memory_max;
857 swap_max = c->memory_swap_max;
858 } else {
859 max = c->memory_limit;
860
861 if (max != CGROUP_LIMIT_MAX)
862 log_cgroup_compat(u, "Applying MemoryLimit %" PRIu64 " as MemoryMax", max);
863 }
864
865 cgroup_apply_unified_memory_limit(u, "memory.low", c->memory_low);
866 cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
867 cgroup_apply_unified_memory_limit(u, "memory.max", max);
868 cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
869 } else {
870 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
871 uint64_t val;
872
873 if (cgroup_context_has_unified_memory_config(c)) {
874 val = c->memory_max;
875 log_cgroup_compat(u, "Applying MemoryMax %" PRIi64 " as MemoryLimit", val);
876 } else
877 val = c->memory_limit;
878
879 if (val == CGROUP_LIMIT_MAX)
880 strncpy(buf, "-1\n", sizeof(buf));
881 else
882 xsprintf(buf, "%" PRIu64 "\n", val);
883
884 r = cg_set_attribute("memory", path, "memory.limit_in_bytes", 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 memory.limit_in_bytes: %m");
888 }
889 }
890
891 if ((mask & CGROUP_MASK_DEVICES) && !is_root) {
892 CGroupDeviceAllow *a;
893
894 /* Changing the devices list of a populated cgroup
895 * might result in EINVAL, hence ignore EINVAL
896 * here. */
897
898 if (c->device_allow || c->device_policy != CGROUP_AUTO)
899 r = cg_set_attribute("devices", path, "devices.deny", "a");
900 else
901 r = cg_set_attribute("devices", path, "devices.allow", "a");
902 if (r < 0)
903 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
904 "Failed to reset devices.list: %m");
905
906 if (c->device_policy == CGROUP_CLOSED ||
907 (c->device_policy == CGROUP_AUTO && c->device_allow)) {
908 static const char auto_devices[] =
909 "/dev/null\0" "rwm\0"
910 "/dev/zero\0" "rwm\0"
911 "/dev/full\0" "rwm\0"
912 "/dev/random\0" "rwm\0"
913 "/dev/urandom\0" "rwm\0"
914 "/dev/tty\0" "rwm\0"
915 "/dev/pts/ptmx\0" "rw\0" /* /dev/pts/ptmx may not be duplicated, but accessed */
916 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
917 "/run/systemd/inaccessible/chr\0" "rwm\0"
918 "/run/systemd/inaccessible/blk\0" "rwm\0";
919
920 const char *x, *y;
921
922 NULSTR_FOREACH_PAIR(x, y, auto_devices)
923 whitelist_device(path, x, y);
924
925 whitelist_major(path, "pts", 'c', "rw");
926 whitelist_major(path, "kdbus", 'c', "rw");
927 whitelist_major(path, "kdbus/*", 'c', "rw");
928 }
929
930 LIST_FOREACH(device_allow, a, c->device_allow) {
931 char acc[4], *val;
932 unsigned k = 0;
933
934 if (a->r)
935 acc[k++] = 'r';
936 if (a->w)
937 acc[k++] = 'w';
938 if (a->m)
939 acc[k++] = 'm';
940
941 if (k == 0)
942 continue;
943
944 acc[k++] = 0;
945
946 if (startswith(a->path, "/dev/"))
947 whitelist_device(path, a->path, acc);
948 else if ((val = startswith(a->path, "block-")))
949 whitelist_major(path, val, 'b', acc);
950 else if ((val = startswith(a->path, "char-")))
951 whitelist_major(path, val, 'c', acc);
952 else
953 log_unit_debug(u, "Ignoring device %s while writing cgroup attribute.", a->path);
954 }
955 }
956
957 if ((mask & CGROUP_MASK_PIDS) && !is_root) {
958
959 if (c->tasks_max != CGROUP_LIMIT_MAX) {
960 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
961
962 sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
963 r = cg_set_attribute("pids", path, "pids.max", buf);
964 } else
965 r = cg_set_attribute("pids", path, "pids.max", "max");
966
967 if (r < 0)
968 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
969 "Failed to set pids.max: %m");
970 }
971 }
972
973 CGroupMask cgroup_context_get_mask(CGroupContext *c) {
974 CGroupMask mask = 0;
975
976 /* Figure out which controllers we need */
977
978 if (c->cpu_accounting ||
979 cgroup_context_has_cpu_weight(c) ||
980 cgroup_context_has_cpu_shares(c) ||
981 c->cpu_quota_per_sec_usec != USEC_INFINITY)
982 mask |= CGROUP_MASK_CPUACCT | CGROUP_MASK_CPU;
983
984 if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
985 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
986
987 if (c->memory_accounting ||
988 c->memory_limit != CGROUP_LIMIT_MAX ||
989 cgroup_context_has_unified_memory_config(c))
990 mask |= CGROUP_MASK_MEMORY;
991
992 if (c->device_allow ||
993 c->device_policy != CGROUP_AUTO)
994 mask |= CGROUP_MASK_DEVICES;
995
996 if (c->tasks_accounting ||
997 c->tasks_max != (uint64_t) -1)
998 mask |= CGROUP_MASK_PIDS;
999
1000 return mask;
1001 }
1002
1003 CGroupMask unit_get_own_mask(Unit *u) {
1004 CGroupContext *c;
1005
1006 /* Returns the mask of controllers the unit needs for itself */
1007
1008 c = unit_get_cgroup_context(u);
1009 if (!c)
1010 return 0;
1011
1012 /* If delegation is turned on, then turn on all cgroups,
1013 * unless we are on the legacy hierarchy and the process we
1014 * fork into it is known to drop privileges, and hence
1015 * shouldn't get access to the controllers.
1016 *
1017 * Note that on the unified hierarchy it is safe to delegate
1018 * controllers to unprivileged services. */
1019
1020 if (c->delegate) {
1021 ExecContext *e;
1022
1023 e = unit_get_exec_context(u);
1024 if (!e ||
1025 exec_context_maintains_privileges(e) ||
1026 cg_all_unified() > 0)
1027 return _CGROUP_MASK_ALL;
1028 }
1029
1030 return cgroup_context_get_mask(c);
1031 }
1032
1033 CGroupMask unit_get_members_mask(Unit *u) {
1034 assert(u);
1035
1036 /* Returns the mask of controllers all of the unit's children
1037 * require, merged */
1038
1039 if (u->cgroup_members_mask_valid)
1040 return u->cgroup_members_mask;
1041
1042 u->cgroup_members_mask = 0;
1043
1044 if (u->type == UNIT_SLICE) {
1045 Unit *member;
1046 Iterator i;
1047
1048 SET_FOREACH(member, u->dependencies[UNIT_BEFORE], i) {
1049
1050 if (member == u)
1051 continue;
1052
1053 if (UNIT_DEREF(member->slice) != u)
1054 continue;
1055
1056 u->cgroup_members_mask |=
1057 unit_get_own_mask(member) |
1058 unit_get_members_mask(member);
1059 }
1060 }
1061
1062 u->cgroup_members_mask_valid = true;
1063 return u->cgroup_members_mask;
1064 }
1065
1066 CGroupMask unit_get_siblings_mask(Unit *u) {
1067 assert(u);
1068
1069 /* Returns the mask of controllers all of the unit's siblings
1070 * require, i.e. the members mask of the unit's parent slice
1071 * if there is one. */
1072
1073 if (UNIT_ISSET(u->slice))
1074 return unit_get_members_mask(UNIT_DEREF(u->slice));
1075
1076 return unit_get_own_mask(u) | unit_get_members_mask(u);
1077 }
1078
1079 CGroupMask unit_get_subtree_mask(Unit *u) {
1080
1081 /* Returns the mask of this subtree, meaning of the group
1082 * itself and its children. */
1083
1084 return unit_get_own_mask(u) | unit_get_members_mask(u);
1085 }
1086
1087 CGroupMask unit_get_target_mask(Unit *u) {
1088 CGroupMask mask;
1089
1090 /* This returns the cgroup mask of all controllers to enable
1091 * for a specific cgroup, i.e. everything it needs itself,
1092 * plus all that its children need, plus all that its siblings
1093 * need. This is primarily useful on the legacy cgroup
1094 * hierarchy, where we need to duplicate each cgroup in each
1095 * hierarchy that shall be enabled for it. */
1096
1097 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
1098 mask &= u->manager->cgroup_supported;
1099
1100 return mask;
1101 }
1102
1103 CGroupMask unit_get_enable_mask(Unit *u) {
1104 CGroupMask mask;
1105
1106 /* This returns the cgroup mask of all controllers to enable
1107 * for the children of a specific cgroup. This is primarily
1108 * useful for the unified cgroup hierarchy, where each cgroup
1109 * controls which controllers are enabled for its children. */
1110
1111 mask = unit_get_members_mask(u);
1112 mask &= u->manager->cgroup_supported;
1113
1114 return mask;
1115 }
1116
1117 /* Recurse from a unit up through its containing slices, propagating
1118 * mask bits upward. A unit is also member of itself. */
1119 void unit_update_cgroup_members_masks(Unit *u) {
1120 CGroupMask m;
1121 bool more;
1122
1123 assert(u);
1124
1125 /* Calculate subtree mask */
1126 m = unit_get_subtree_mask(u);
1127
1128 /* See if anything changed from the previous invocation. If
1129 * not, we're done. */
1130 if (u->cgroup_subtree_mask_valid && m == u->cgroup_subtree_mask)
1131 return;
1132
1133 more =
1134 u->cgroup_subtree_mask_valid &&
1135 ((m & ~u->cgroup_subtree_mask) != 0) &&
1136 ((~m & u->cgroup_subtree_mask) == 0);
1137
1138 u->cgroup_subtree_mask = m;
1139 u->cgroup_subtree_mask_valid = true;
1140
1141 if (UNIT_ISSET(u->slice)) {
1142 Unit *s = UNIT_DEREF(u->slice);
1143
1144 if (more)
1145 /* There's more set now than before. We
1146 * propagate the new mask to the parent's mask
1147 * (not caring if it actually was valid or
1148 * not). */
1149
1150 s->cgroup_members_mask |= m;
1151
1152 else
1153 /* There's less set now than before (or we
1154 * don't know), we need to recalculate
1155 * everything, so let's invalidate the
1156 * parent's members mask */
1157
1158 s->cgroup_members_mask_valid = false;
1159
1160 /* And now make sure that this change also hits our
1161 * grandparents */
1162 unit_update_cgroup_members_masks(s);
1163 }
1164 }
1165
1166 static const char *migrate_callback(CGroupMask mask, void *userdata) {
1167 Unit *u = userdata;
1168
1169 assert(mask != 0);
1170 assert(u);
1171
1172 while (u) {
1173 if (u->cgroup_path &&
1174 u->cgroup_realized &&
1175 (u->cgroup_realized_mask & mask) == mask)
1176 return u->cgroup_path;
1177
1178 u = UNIT_DEREF(u->slice);
1179 }
1180
1181 return NULL;
1182 }
1183
1184 char *unit_default_cgroup_path(Unit *u) {
1185 _cleanup_free_ char *escaped = NULL, *slice = NULL;
1186 int r;
1187
1188 assert(u);
1189
1190 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1191 return strdup(u->manager->cgroup_root);
1192
1193 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1194 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1195 if (r < 0)
1196 return NULL;
1197 }
1198
1199 escaped = cg_escape(u->id);
1200 if (!escaped)
1201 return NULL;
1202
1203 if (slice)
1204 return strjoin(u->manager->cgroup_root, "/", slice, "/",
1205 escaped);
1206 else
1207 return strjoin(u->manager->cgroup_root, "/", escaped);
1208 }
1209
1210 int unit_set_cgroup_path(Unit *u, const char *path) {
1211 _cleanup_free_ char *p = NULL;
1212 int r;
1213
1214 assert(u);
1215
1216 if (path) {
1217 p = strdup(path);
1218 if (!p)
1219 return -ENOMEM;
1220 } else
1221 p = NULL;
1222
1223 if (streq_ptr(u->cgroup_path, p))
1224 return 0;
1225
1226 if (p) {
1227 r = hashmap_put(u->manager->cgroup_unit, p, u);
1228 if (r < 0)
1229 return r;
1230 }
1231
1232 unit_release_cgroup(u);
1233
1234 u->cgroup_path = p;
1235 p = NULL;
1236
1237 return 1;
1238 }
1239
1240 int unit_watch_cgroup(Unit *u) {
1241 _cleanup_free_ char *events = NULL;
1242 int r;
1243
1244 assert(u);
1245
1246 if (!u->cgroup_path)
1247 return 0;
1248
1249 if (u->cgroup_inotify_wd >= 0)
1250 return 0;
1251
1252 /* Only applies to the unified hierarchy */
1253 r = cg_unified(SYSTEMD_CGROUP_CONTROLLER);
1254 if (r < 0)
1255 return log_unit_error_errno(u, r, "Failed detect whether the unified hierarchy is used: %m");
1256 if (r == 0)
1257 return 0;
1258
1259 /* Don't watch the root slice, it's pointless. */
1260 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1261 return 0;
1262
1263 r = hashmap_ensure_allocated(&u->manager->cgroup_inotify_wd_unit, &trivial_hash_ops);
1264 if (r < 0)
1265 return log_oom();
1266
1267 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1268 if (r < 0)
1269 return log_oom();
1270
1271 u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1272 if (u->cgroup_inotify_wd < 0) {
1273
1274 if (errno == ENOENT) /* If the directory is already
1275 * gone we don't need to track
1276 * it, so this is not an error */
1277 return 0;
1278
1279 return log_unit_error_errno(u, errno, "Failed to add inotify watch descriptor for control group %s: %m", u->cgroup_path);
1280 }
1281
1282 r = hashmap_put(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd), u);
1283 if (r < 0)
1284 return log_unit_error_errno(u, r, "Failed to add inotify watch descriptor to hash map: %m");
1285
1286 return 0;
1287 }
1288
1289 static int unit_create_cgroup(
1290 Unit *u,
1291 CGroupMask target_mask,
1292 CGroupMask enable_mask) {
1293
1294 CGroupContext *c;
1295 int r;
1296
1297 assert(u);
1298
1299 c = unit_get_cgroup_context(u);
1300 if (!c)
1301 return 0;
1302
1303 if (!u->cgroup_path) {
1304 _cleanup_free_ char *path = NULL;
1305
1306 path = unit_default_cgroup_path(u);
1307 if (!path)
1308 return log_oom();
1309
1310 r = unit_set_cgroup_path(u, path);
1311 if (r == -EEXIST)
1312 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1313 if (r < 0)
1314 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1315 }
1316
1317 /* First, create our own group */
1318 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1319 if (r < 0)
1320 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1321
1322 /* Start watching it */
1323 (void) unit_watch_cgroup(u);
1324
1325 /* Enable all controllers we need */
1326 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path);
1327 if (r < 0)
1328 log_unit_warning_errno(u, r, "Failed to enable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
1329
1330 /* Keep track that this is now realized */
1331 u->cgroup_realized = true;
1332 u->cgroup_realized_mask = target_mask;
1333 u->cgroup_enabled_mask = enable_mask;
1334
1335 if (u->type != UNIT_SLICE && !c->delegate) {
1336
1337 /* Then, possibly move things over, but not if
1338 * subgroups may contain processes, which is the case
1339 * for slice and delegation units. */
1340 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1341 if (r < 0)
1342 log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
1343 }
1344
1345 return 0;
1346 }
1347
1348 int unit_attach_pids_to_cgroup(Unit *u) {
1349 int r;
1350 assert(u);
1351
1352 r = unit_realize_cgroup(u);
1353 if (r < 0)
1354 return r;
1355
1356 r = cg_attach_many_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->pids, migrate_callback, u);
1357 if (r < 0)
1358 return r;
1359
1360 return 0;
1361 }
1362
1363 static void cgroup_xattr_apply(Unit *u) {
1364 char ids[SD_ID128_STRING_MAX];
1365 int r;
1366
1367 assert(u);
1368
1369 if (!MANAGER_IS_SYSTEM(u->manager))
1370 return;
1371
1372 if (sd_id128_is_null(u->invocation_id))
1373 return;
1374
1375 r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
1376 "trusted.invocation_id",
1377 sd_id128_to_string(u->invocation_id, ids), 32,
1378 0);
1379 if (r < 0)
1380 log_unit_warning_errno(u, r, "Failed to set invocation ID on control group %s, ignoring: %m", u->cgroup_path);
1381 }
1382
1383 static bool unit_has_mask_realized(Unit *u, CGroupMask target_mask, CGroupMask enable_mask) {
1384 assert(u);
1385
1386 return u->cgroup_realized && u->cgroup_realized_mask == target_mask && u->cgroup_enabled_mask == enable_mask;
1387 }
1388
1389 /* Check if necessary controllers and attributes for a unit are in place.
1390 *
1391 * If so, do nothing.
1392 * If not, create paths, move processes over, and set attributes.
1393 *
1394 * Returns 0 on success and < 0 on failure. */
1395 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
1396 CGroupMask target_mask, enable_mask;
1397 int r;
1398
1399 assert(u);
1400
1401 if (u->in_cgroup_queue) {
1402 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
1403 u->in_cgroup_queue = false;
1404 }
1405
1406 target_mask = unit_get_target_mask(u);
1407 enable_mask = unit_get_enable_mask(u);
1408
1409 if (unit_has_mask_realized(u, target_mask, enable_mask))
1410 return 0;
1411
1412 /* First, realize parents */
1413 if (UNIT_ISSET(u->slice)) {
1414 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
1415 if (r < 0)
1416 return r;
1417 }
1418
1419 /* And then do the real work */
1420 r = unit_create_cgroup(u, target_mask, enable_mask);
1421 if (r < 0)
1422 return r;
1423
1424 /* Finally, apply the necessary attributes. */
1425 cgroup_context_apply(u, target_mask, state);
1426 cgroup_xattr_apply(u);
1427
1428 return 0;
1429 }
1430
1431 static void unit_add_to_cgroup_queue(Unit *u) {
1432
1433 if (u->in_cgroup_queue)
1434 return;
1435
1436 LIST_PREPEND(cgroup_queue, u->manager->cgroup_queue, u);
1437 u->in_cgroup_queue = true;
1438 }
1439
1440 unsigned manager_dispatch_cgroup_queue(Manager *m) {
1441 ManagerState state;
1442 unsigned n = 0;
1443 Unit *i;
1444 int r;
1445
1446 state = manager_state(m);
1447
1448 while ((i = m->cgroup_queue)) {
1449 assert(i->in_cgroup_queue);
1450
1451 r = unit_realize_cgroup_now(i, state);
1452 if (r < 0)
1453 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
1454
1455 n++;
1456 }
1457
1458 return n;
1459 }
1460
1461 static void unit_queue_siblings(Unit *u) {
1462 Unit *slice;
1463
1464 /* This adds the siblings of the specified unit and the
1465 * siblings of all parent units to the cgroup queue. (But
1466 * neither the specified unit itself nor the parents.) */
1467
1468 while ((slice = UNIT_DEREF(u->slice))) {
1469 Iterator i;
1470 Unit *m;
1471
1472 SET_FOREACH(m, slice->dependencies[UNIT_BEFORE], i) {
1473 if (m == u)
1474 continue;
1475
1476 /* Skip units that have a dependency on the slice
1477 * but aren't actually in it. */
1478 if (UNIT_DEREF(m->slice) != slice)
1479 continue;
1480
1481 /* No point in doing cgroup application for units
1482 * without active processes. */
1483 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
1484 continue;
1485
1486 /* If the unit doesn't need any new controllers
1487 * and has current ones realized, it doesn't need
1488 * any changes. */
1489 if (unit_has_mask_realized(m, unit_get_target_mask(m), unit_get_enable_mask(m)))
1490 continue;
1491
1492 unit_add_to_cgroup_queue(m);
1493 }
1494
1495 u = slice;
1496 }
1497 }
1498
1499 int unit_realize_cgroup(Unit *u) {
1500 assert(u);
1501
1502 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1503 return 0;
1504
1505 /* So, here's the deal: when realizing the cgroups for this
1506 * unit, we need to first create all parents, but there's more
1507 * actually: for the weight-based controllers we also need to
1508 * make sure that all our siblings (i.e. units that are in the
1509 * same slice as we are) have cgroups, too. Otherwise, things
1510 * would become very uneven as each of their processes would
1511 * get as much resources as all our group together. This call
1512 * will synchronously create the parent cgroups, but will
1513 * defer work on the siblings to the next event loop
1514 * iteration. */
1515
1516 /* Add all sibling slices to the cgroup queue. */
1517 unit_queue_siblings(u);
1518
1519 /* And realize this one now (and apply the values) */
1520 return unit_realize_cgroup_now(u, manager_state(u->manager));
1521 }
1522
1523 void unit_release_cgroup(Unit *u) {
1524 assert(u);
1525
1526 /* Forgets all cgroup details for this cgroup */
1527
1528 if (u->cgroup_path) {
1529 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1530 u->cgroup_path = mfree(u->cgroup_path);
1531 }
1532
1533 if (u->cgroup_inotify_wd >= 0) {
1534 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1535 log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1536
1537 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1538 u->cgroup_inotify_wd = -1;
1539 }
1540 }
1541
1542 void unit_prune_cgroup(Unit *u) {
1543 int r;
1544 bool is_root_slice;
1545
1546 assert(u);
1547
1548 /* Removes the cgroup, if empty and possible, and stops watching it. */
1549
1550 if (!u->cgroup_path)
1551 return;
1552
1553 (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
1554
1555 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1556
1557 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
1558 if (r < 0) {
1559 log_unit_debug_errno(u, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
1560 return;
1561 }
1562
1563 if (is_root_slice)
1564 return;
1565
1566 unit_release_cgroup(u);
1567
1568 u->cgroup_realized = false;
1569 u->cgroup_realized_mask = 0;
1570 u->cgroup_enabled_mask = 0;
1571 }
1572
1573 int unit_search_main_pid(Unit *u, pid_t *ret) {
1574 _cleanup_fclose_ FILE *f = NULL;
1575 pid_t pid = 0, npid, mypid;
1576 int r;
1577
1578 assert(u);
1579 assert(ret);
1580
1581 if (!u->cgroup_path)
1582 return -ENXIO;
1583
1584 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1585 if (r < 0)
1586 return r;
1587
1588 mypid = getpid();
1589 while (cg_read_pid(f, &npid) > 0) {
1590 pid_t ppid;
1591
1592 if (npid == pid)
1593 continue;
1594
1595 /* Ignore processes that aren't our kids */
1596 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
1597 continue;
1598
1599 if (pid != 0)
1600 /* Dang, there's more than one daemonized PID
1601 in this group, so we don't know what process
1602 is the main process. */
1603
1604 return -ENODATA;
1605
1606 pid = npid;
1607 }
1608
1609 *ret = pid;
1610 return 0;
1611 }
1612
1613 static int unit_watch_pids_in_path(Unit *u, const char *path) {
1614 _cleanup_closedir_ DIR *d = NULL;
1615 _cleanup_fclose_ FILE *f = NULL;
1616 int ret = 0, r;
1617
1618 assert(u);
1619 assert(path);
1620
1621 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1622 if (r < 0)
1623 ret = r;
1624 else {
1625 pid_t pid;
1626
1627 while ((r = cg_read_pid(f, &pid)) > 0) {
1628 r = unit_watch_pid(u, pid);
1629 if (r < 0 && ret >= 0)
1630 ret = r;
1631 }
1632
1633 if (r < 0 && ret >= 0)
1634 ret = r;
1635 }
1636
1637 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1638 if (r < 0) {
1639 if (ret >= 0)
1640 ret = r;
1641 } else {
1642 char *fn;
1643
1644 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1645 _cleanup_free_ char *p = NULL;
1646
1647 p = strjoin(path, "/", fn);
1648 free(fn);
1649
1650 if (!p)
1651 return -ENOMEM;
1652
1653 r = unit_watch_pids_in_path(u, p);
1654 if (r < 0 && ret >= 0)
1655 ret = r;
1656 }
1657
1658 if (r < 0 && ret >= 0)
1659 ret = r;
1660 }
1661
1662 return ret;
1663 }
1664
1665 int unit_watch_all_pids(Unit *u) {
1666 assert(u);
1667
1668 /* Adds all PIDs from our cgroup to the set of PIDs we
1669 * watch. This is a fallback logic for cases where we do not
1670 * get reliable cgroup empty notifications: we try to use
1671 * SIGCHLD as replacement. */
1672
1673 if (!u->cgroup_path)
1674 return -ENOENT;
1675
1676 if (cg_unified(SYSTEMD_CGROUP_CONTROLLER) > 0) /* On unified we can use proper notifications */
1677 return 0;
1678
1679 return unit_watch_pids_in_path(u, u->cgroup_path);
1680 }
1681
1682 int unit_notify_cgroup_empty(Unit *u) {
1683 int r;
1684
1685 assert(u);
1686
1687 if (!u->cgroup_path)
1688 return 0;
1689
1690 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
1691 if (r <= 0)
1692 return r;
1693
1694 unit_add_to_gc_queue(u);
1695
1696 if (UNIT_VTABLE(u)->notify_cgroup_empty)
1697 UNIT_VTABLE(u)->notify_cgroup_empty(u);
1698
1699 return 0;
1700 }
1701
1702 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1703 Manager *m = userdata;
1704
1705 assert(s);
1706 assert(fd >= 0);
1707 assert(m);
1708
1709 for (;;) {
1710 union inotify_event_buffer buffer;
1711 struct inotify_event *e;
1712 ssize_t l;
1713
1714 l = read(fd, &buffer, sizeof(buffer));
1715 if (l < 0) {
1716 if (errno == EINTR || errno == EAGAIN)
1717 return 0;
1718
1719 return log_error_errno(errno, "Failed to read control group inotify events: %m");
1720 }
1721
1722 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1723 Unit *u;
1724
1725 if (e->wd < 0)
1726 /* Queue overflow has no watch descriptor */
1727 continue;
1728
1729 if (e->mask & IN_IGNORED)
1730 /* The watch was just removed */
1731 continue;
1732
1733 u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
1734 if (!u) /* Not that inotify might deliver
1735 * events for a watch even after it
1736 * was removed, because it was queued
1737 * before the removal. Let's ignore
1738 * this here safely. */
1739 continue;
1740
1741 (void) unit_notify_cgroup_empty(u);
1742 }
1743 }
1744 }
1745
1746 int manager_setup_cgroup(Manager *m) {
1747 _cleanup_free_ char *path = NULL;
1748 CGroupController c;
1749 int r, all_unified, systemd_unified;
1750 char *e;
1751
1752 assert(m);
1753
1754 /* 1. Determine hierarchy */
1755 m->cgroup_root = mfree(m->cgroup_root);
1756 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
1757 if (r < 0)
1758 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
1759
1760 /* Chop off the init scope, if we are already located in it */
1761 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1762
1763 /* LEGACY: Also chop off the system slice if we are in
1764 * it. This is to support live upgrades from older systemd
1765 * versions where PID 1 was moved there. Also see
1766 * cg_get_root_path(). */
1767 if (!e && MANAGER_IS_SYSTEM(m)) {
1768 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
1769 if (!e)
1770 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
1771 }
1772 if (e)
1773 *e = 0;
1774
1775 /* And make sure to store away the root value without trailing
1776 * slash, even for the root dir, so that we can easily prepend
1777 * it everywhere. */
1778 while ((e = endswith(m->cgroup_root, "/")))
1779 *e = 0;
1780
1781 /* 2. Show data */
1782 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
1783 if (r < 0)
1784 return log_error_errno(r, "Cannot find cgroup mount point: %m");
1785
1786 all_unified = cg_all_unified();
1787 systemd_unified = cg_unified(SYSTEMD_CGROUP_CONTROLLER);
1788
1789 if (all_unified < 0 || systemd_unified < 0)
1790 return log_error_errno(all_unified < 0 ? all_unified : systemd_unified,
1791 "Couldn't determine if we are running in the unified hierarchy: %m");
1792
1793 if (all_unified > 0)
1794 log_debug("Unified cgroup hierarchy is located at %s.", path);
1795 else if (systemd_unified > 0)
1796 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
1797 else
1798 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER ". File system hierarchy is at %s.", path);
1799
1800 if (!m->test_run) {
1801 const char *scope_path;
1802
1803 /* 3. Install agent */
1804 if (systemd_unified) {
1805
1806 /* In the unified hierarchy we can get
1807 * cgroup empty notifications via inotify. */
1808
1809 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1810 safe_close(m->cgroup_inotify_fd);
1811
1812 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1813 if (m->cgroup_inotify_fd < 0)
1814 return log_error_errno(errno, "Failed to create control group inotify object: %m");
1815
1816 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
1817 if (r < 0)
1818 return log_error_errno(r, "Failed to watch control group inotify object: %m");
1819
1820 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
1821 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
1822 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-5);
1823 if (r < 0)
1824 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
1825
1826 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
1827
1828 } else if (MANAGER_IS_SYSTEM(m)) {
1829
1830 /* On the legacy hierarchy we only get
1831 * notifications via cgroup agents. (Which
1832 * isn't really reliable, since it does not
1833 * generate events when control groups with
1834 * children run empty. */
1835
1836 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
1837 if (r < 0)
1838 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
1839 else if (r > 0)
1840 log_debug("Installed release agent.");
1841 else if (r == 0)
1842 log_debug("Release agent already installed.");
1843 }
1844
1845 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1846 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1847 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1848 if (r < 0)
1849 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
1850
1851 /* also, move all other userspace processes remaining
1852 * in the root cgroup into that scope. */
1853 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1854 if (r < 0)
1855 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
1856
1857 /* 5. And pin it, so that it cannot be unmounted */
1858 safe_close(m->pin_cgroupfs_fd);
1859 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
1860 if (m->pin_cgroupfs_fd < 0)
1861 return log_error_errno(errno, "Failed to open pin file: %m");
1862
1863 /* 6. Always enable hierarchical support if it exists... */
1864 if (!all_unified)
1865 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
1866 }
1867
1868 /* 7. Figure out which controllers are supported */
1869 r = cg_mask_supported(&m->cgroup_supported);
1870 if (r < 0)
1871 return log_error_errno(r, "Failed to determine supported controllers: %m");
1872
1873 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
1874 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
1875
1876 return 0;
1877 }
1878
1879 void manager_shutdown_cgroup(Manager *m, bool delete) {
1880 assert(m);
1881
1882 /* We can't really delete the group, since we are in it. But
1883 * let's trim it. */
1884 if (delete && m->cgroup_root)
1885 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
1886
1887 m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
1888
1889 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1890 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
1891
1892 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
1893
1894 m->cgroup_root = mfree(m->cgroup_root);
1895 }
1896
1897 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
1898 char *p;
1899 Unit *u;
1900
1901 assert(m);
1902 assert(cgroup);
1903
1904 u = hashmap_get(m->cgroup_unit, cgroup);
1905 if (u)
1906 return u;
1907
1908 p = strdupa(cgroup);
1909 for (;;) {
1910 char *e;
1911
1912 e = strrchr(p, '/');
1913 if (!e || e == p)
1914 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
1915
1916 *e = 0;
1917
1918 u = hashmap_get(m->cgroup_unit, p);
1919 if (u)
1920 return u;
1921 }
1922 }
1923
1924 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
1925 _cleanup_free_ char *cgroup = NULL;
1926 int r;
1927
1928 assert(m);
1929
1930 if (pid <= 0)
1931 return NULL;
1932
1933 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
1934 if (r < 0)
1935 return NULL;
1936
1937 return manager_get_unit_by_cgroup(m, cgroup);
1938 }
1939
1940 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
1941 Unit *u;
1942
1943 assert(m);
1944
1945 if (pid <= 0)
1946 return NULL;
1947
1948 if (pid == 1)
1949 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
1950
1951 u = hashmap_get(m->watch_pids1, PID_TO_PTR(pid));
1952 if (u)
1953 return u;
1954
1955 u = hashmap_get(m->watch_pids2, PID_TO_PTR(pid));
1956 if (u)
1957 return u;
1958
1959 return manager_get_unit_by_pid_cgroup(m, pid);
1960 }
1961
1962 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
1963 Unit *u;
1964
1965 assert(m);
1966 assert(cgroup);
1967
1968 log_debug("Got cgroup empty notification for: %s", cgroup);
1969
1970 u = manager_get_unit_by_cgroup(m, cgroup);
1971 if (!u)
1972 return 0;
1973
1974 return unit_notify_cgroup_empty(u);
1975 }
1976
1977 int unit_get_memory_current(Unit *u, uint64_t *ret) {
1978 _cleanup_free_ char *v = NULL;
1979 int r;
1980
1981 assert(u);
1982 assert(ret);
1983
1984 if (!u->cgroup_path)
1985 return -ENODATA;
1986
1987 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
1988 return -ENODATA;
1989
1990 if (cg_all_unified() <= 0)
1991 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
1992 else
1993 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
1994 if (r == -ENOENT)
1995 return -ENODATA;
1996 if (r < 0)
1997 return r;
1998
1999 return safe_atou64(v, ret);
2000 }
2001
2002 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
2003 _cleanup_free_ char *v = NULL;
2004 int r;
2005
2006 assert(u);
2007 assert(ret);
2008
2009 if (!u->cgroup_path)
2010 return -ENODATA;
2011
2012 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
2013 return -ENODATA;
2014
2015 r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
2016 if (r == -ENOENT)
2017 return -ENODATA;
2018 if (r < 0)
2019 return r;
2020
2021 return safe_atou64(v, ret);
2022 }
2023
2024 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
2025 _cleanup_free_ char *v = NULL;
2026 uint64_t ns;
2027 int r;
2028
2029 assert(u);
2030 assert(ret);
2031
2032 if (!u->cgroup_path)
2033 return -ENODATA;
2034
2035 if (cg_all_unified() > 0) {
2036 const char *keys[] = { "usage_usec", NULL };
2037 _cleanup_free_ char *val = NULL;
2038 uint64_t us;
2039
2040 if ((u->cgroup_realized_mask & CGROUP_MASK_CPU) == 0)
2041 return -ENODATA;
2042
2043 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", keys, &val);
2044 if (r < 0)
2045 return r;
2046
2047 r = safe_atou64(val, &us);
2048 if (r < 0)
2049 return r;
2050
2051 ns = us * NSEC_PER_USEC;
2052 } else {
2053 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
2054 return -ENODATA;
2055
2056 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
2057 if (r == -ENOENT)
2058 return -ENODATA;
2059 if (r < 0)
2060 return r;
2061
2062 r = safe_atou64(v, &ns);
2063 if (r < 0)
2064 return r;
2065 }
2066
2067 *ret = ns;
2068 return 0;
2069 }
2070
2071 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
2072 nsec_t ns;
2073 int r;
2074
2075 assert(u);
2076
2077 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2078 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2079 * call this function with a NULL return value. */
2080
2081 r = unit_get_cpu_usage_raw(u, &ns);
2082 if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
2083 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2084 * cached value. */
2085
2086 if (ret)
2087 *ret = u->cpu_usage_last;
2088 return 0;
2089 }
2090 if (r < 0)
2091 return r;
2092
2093 if (ns > u->cpu_usage_base)
2094 ns -= u->cpu_usage_base;
2095 else
2096 ns = 0;
2097
2098 u->cpu_usage_last = ns;
2099 if (ret)
2100 *ret = ns;
2101
2102 return 0;
2103 }
2104
2105 int unit_reset_cpu_usage(Unit *u) {
2106 nsec_t ns;
2107 int r;
2108
2109 assert(u);
2110
2111 u->cpu_usage_last = NSEC_INFINITY;
2112
2113 r = unit_get_cpu_usage_raw(u, &ns);
2114 if (r < 0) {
2115 u->cpu_usage_base = 0;
2116 return r;
2117 }
2118
2119 u->cpu_usage_base = ns;
2120 return 0;
2121 }
2122
2123 bool unit_cgroup_delegate(Unit *u) {
2124 CGroupContext *c;
2125
2126 assert(u);
2127
2128 c = unit_get_cgroup_context(u);
2129 if (!c)
2130 return false;
2131
2132 return c->delegate;
2133 }
2134
2135 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
2136 assert(u);
2137
2138 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2139 return;
2140
2141 if (m == 0)
2142 return;
2143
2144 /* always invalidate compat pairs together */
2145 if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
2146 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
2147
2148 if ((u->cgroup_realized_mask & m) == 0)
2149 return;
2150
2151 u->cgroup_realized_mask &= ~m;
2152 unit_add_to_cgroup_queue(u);
2153 }
2154
2155 void manager_invalidate_startup_units(Manager *m) {
2156 Iterator i;
2157 Unit *u;
2158
2159 assert(m);
2160
2161 SET_FOREACH(u, m->startup_units, i)
2162 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
2163 }
2164
2165 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
2166 [CGROUP_AUTO] = "auto",
2167 [CGROUP_CLOSED] = "closed",
2168 [CGROUP_STRICT] = "strict",
2169 };
2170
2171 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);