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