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