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