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