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