]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/cgroup.c
cgroup2: use new fstype for unified hierarchy
[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"
8e274523 35
9a054909
LP
36#define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
37
4ad49000
LP
38void cgroup_context_init(CGroupContext *c) {
39 assert(c);
40
41 /* Initialize everything to the kernel defaults, assuming the
42 * structure is preinitialized to 0 */
43
d53d9474
LP
44 c->cpu_shares = CGROUP_CPU_SHARES_INVALID;
45 c->startup_cpu_shares = CGROUP_CPU_SHARES_INVALID;
46 c->cpu_quota_per_sec_usec = USEC_INFINITY;
47
ddca82ac 48 c->memory_limit = (uint64_t) -1;
b2f8b02e 49
d53d9474
LP
50 c->blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
51 c->startup_blockio_weight = CGROUP_BLKIO_WEIGHT_INVALID;
52
53 c->tasks_max = (uint64_t) -1;
4ad49000 54}
8e274523 55
4ad49000
LP
56void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
57 assert(c);
58 assert(a);
59
71fda00f 60 LIST_REMOVE(device_allow, c->device_allow, a);
4ad49000
LP
61 free(a->path);
62 free(a);
63}
64
65void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
66 assert(c);
67 assert(w);
68
71fda00f 69 LIST_REMOVE(device_weights, c->blockio_device_weights, w);
4ad49000
LP
70 free(w->path);
71 free(w);
72}
73
74void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
75 assert(c);
8e274523 76 assert(b);
8e274523 77
71fda00f 78 LIST_REMOVE(device_bandwidths, c->blockio_device_bandwidths, b);
4ad49000
LP
79 free(b->path);
80 free(b);
81}
82
83void cgroup_context_done(CGroupContext *c) {
84 assert(c);
85
86 while (c->blockio_device_weights)
87 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
88
89 while (c->blockio_device_bandwidths)
90 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
91
92 while (c->device_allow)
93 cgroup_context_free_device_allow(c, c->device_allow);
94}
95
96void cgroup_context_dump(CGroupContext *c, FILE* f, const char *prefix) {
97 CGroupBlockIODeviceBandwidth *b;
98 CGroupBlockIODeviceWeight *w;
99 CGroupDeviceAllow *a;
9a054909 100 char u[FORMAT_TIMESPAN_MAX];
4ad49000
LP
101
102 assert(c);
103 assert(f);
104
105 prefix = strempty(prefix);
106
107 fprintf(f,
108 "%sCPUAccounting=%s\n"
109 "%sBlockIOAccounting=%s\n"
110 "%sMemoryAccounting=%s\n"
d53d9474
LP
111 "%sTasksAccounting=%s\n"
112 "%sCPUShares=%" PRIu64 "\n"
113 "%sStartupCPUShares=%" PRIu64 "\n"
b2f8b02e 114 "%sCPUQuotaPerSecSec=%s\n"
d53d9474
LP
115 "%sBlockIOWeight=%" PRIu64 "\n"
116 "%sStartupBlockIOWeight=%" PRIu64 "\n"
4ad49000 117 "%sMemoryLimit=%" PRIu64 "\n"
03a7b521 118 "%sTasksMax=%" PRIu64 "\n"
a931ad47
LP
119 "%sDevicePolicy=%s\n"
120 "%sDelegate=%s\n",
4ad49000
LP
121 prefix, yes_no(c->cpu_accounting),
122 prefix, yes_no(c->blockio_accounting),
123 prefix, yes_no(c->memory_accounting),
d53d9474 124 prefix, yes_no(c->tasks_accounting),
4ad49000 125 prefix, c->cpu_shares,
95ae05c0 126 prefix, c->startup_cpu_shares,
b1d6dcf5 127 prefix, format_timespan(u, sizeof(u), c->cpu_quota_per_sec_usec, 1),
4ad49000 128 prefix, c->blockio_weight,
95ae05c0 129 prefix, c->startup_blockio_weight,
4ad49000 130 prefix, c->memory_limit,
03a7b521 131 prefix, c->tasks_max,
a931ad47
LP
132 prefix, cgroup_device_policy_to_string(c->device_policy),
133 prefix, yes_no(c->delegate));
4ad49000
LP
134
135 LIST_FOREACH(device_allow, a, c->device_allow)
136 fprintf(f,
137 "%sDeviceAllow=%s %s%s%s\n",
138 prefix,
139 a->path,
140 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
141
142 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
143 fprintf(f,
d53d9474 144 "%sBlockIODeviceWeight=%s %" PRIu64,
4ad49000
LP
145 prefix,
146 w->path,
147 w->weight);
148
149 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
150 char buf[FORMAT_BYTES_MAX];
151
152 fprintf(f,
153 "%s%s=%s %s\n",
154 prefix,
155 b->read ? "BlockIOReadBandwidth" : "BlockIOWriteBandwidth",
156 b->path,
157 format_bytes(buf, sizeof(buf), b->bandwidth));
158 }
159}
160
161static int lookup_blkio_device(const char *p, dev_t *dev) {
162 struct stat st;
163 int r;
164
165 assert(p);
166 assert(dev);
167
168 r = stat(p, &st);
4a62c710
MS
169 if (r < 0)
170 return log_warning_errno(errno, "Couldn't stat device %s: %m", p);
8e274523 171
4ad49000
LP
172 if (S_ISBLK(st.st_mode))
173 *dev = st.st_rdev;
174 else if (major(st.st_dev) != 0) {
175 /* If this is not a device node then find the block
176 * device this file is stored on */
177 *dev = st.st_dev;
178
179 /* If this is a partition, try to get the originating
180 * block device */
181 block_get_whole_disk(*dev, dev);
182 } else {
183 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p);
184 return -ENODEV;
185 }
8e274523 186
8e274523 187 return 0;
8e274523
LP
188}
189
4ad49000
LP
190static int whitelist_device(const char *path, const char *node, const char *acc) {
191 char buf[2+DECIMAL_STR_MAX(dev_t)*2+2+4];
192 struct stat st;
8c6db833 193 int r;
8e274523 194
4ad49000
LP
195 assert(path);
196 assert(acc);
8e274523 197
4ad49000
LP
198 if (stat(node, &st) < 0) {
199 log_warning("Couldn't stat device %s", node);
200 return -errno;
201 }
202
203 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
204 log_warning("%s is not a device.", node);
205 return -ENODEV;
206 }
207
208 sprintf(buf,
209 "%c %u:%u %s",
210 S_ISCHR(st.st_mode) ? 'c' : 'b',
211 major(st.st_rdev), minor(st.st_rdev),
212 acc);
213
214 r = cg_set_attribute("devices", path, "devices.allow", buf);
1aeab12b 215 if (r < 0)
077ba06e 216 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
714e2e1d 217 "Failed to set devices.allow on %s: %m", path);
4ad49000
LP
218
219 return r;
8e274523
LP
220}
221
90060676
LP
222static int whitelist_major(const char *path, const char *name, char type, const char *acc) {
223 _cleanup_fclose_ FILE *f = NULL;
224 char line[LINE_MAX];
225 bool good = false;
226 int r;
227
228 assert(path);
229 assert(acc);
230 assert(type == 'b' || type == 'c');
231
232 f = fopen("/proc/devices", "re");
4a62c710
MS
233 if (!f)
234 return log_warning_errno(errno, "Cannot open /proc/devices to resolve %s (%c): %m", name, type);
90060676
LP
235
236 FOREACH_LINE(line, f, goto fail) {
237 char buf[2+DECIMAL_STR_MAX(unsigned)+3+4], *p, *w;
238 unsigned maj;
239
240 truncate_nl(line);
241
242 if (type == 'c' && streq(line, "Character devices:")) {
243 good = true;
244 continue;
245 }
246
247 if (type == 'b' && streq(line, "Block devices:")) {
248 good = true;
249 continue;
250 }
251
252 if (isempty(line)) {
253 good = false;
254 continue;
255 }
256
257 if (!good)
258 continue;
259
260 p = strstrip(line);
261
262 w = strpbrk(p, WHITESPACE);
263 if (!w)
264 continue;
265 *w = 0;
266
267 r = safe_atou(p, &maj);
268 if (r < 0)
269 continue;
270 if (maj <= 0)
271 continue;
272
273 w++;
274 w += strspn(w, WHITESPACE);
e41969e3
LP
275
276 if (fnmatch(name, w, 0) != 0)
90060676
LP
277 continue;
278
279 sprintf(buf,
280 "%c %u:* %s",
281 type,
282 maj,
283 acc);
284
285 r = cg_set_attribute("devices", path, "devices.allow", buf);
1aeab12b 286 if (r < 0)
077ba06e 287 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
714e2e1d 288 "Failed to set devices.allow on %s: %m", path);
90060676
LP
289 }
290
291 return 0;
292
293fail:
56f64d95 294 log_warning_errno(errno, "Failed to read /proc/devices: %m");
90060676
LP
295 return -errno;
296}
297
50f48ad3 298void cgroup_context_apply(CGroupContext *c, CGroupMask mask, const char *path, ManagerState state) {
01efdf13 299 bool is_root;
4ad49000
LP
300 int r;
301
302 assert(c);
303 assert(path);
8e274523 304
4ad49000
LP
305 if (mask == 0)
306 return;
8e274523 307
71c26873 308 /* Some cgroup attributes are not supported on the root cgroup,
01efdf13
LP
309 * hence silently ignore */
310 is_root = isempty(path) || path_equal(path, "/");
6da13913
ZJS
311 if (is_root)
312 /* Make sure we don't try to display messages with an empty path. */
313 path = "/";
01efdf13 314
714e2e1d
LP
315 /* We generally ignore errors caused by read-only mounted
316 * cgroup trees (assuming we are running in a container then),
317 * and missing cgroups, i.e. EROFS and ENOENT. */
318
efdb0237 319 if ((mask & CGROUP_MASK_CPU) && !is_root) {
d53d9474 320 char buf[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t)) + 1];
8e274523 321
d53d9474
LP
322 sprintf(buf, "%" PRIu64 "\n",
323 IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) && c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID ? c->startup_cpu_shares :
324 c->cpu_shares != CGROUP_CPU_SHARES_INVALID ? c->cpu_shares : CGROUP_CPU_SHARES_DEFAULT);
4ad49000 325 r = cg_set_attribute("cpu", path, "cpu.shares", buf);
1aeab12b 326 if (r < 0)
077ba06e 327 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
714e2e1d 328 "Failed to set cpu.shares on %s: %m", path);
b2f8b02e 329
9a054909 330 sprintf(buf, USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
b2f8b02e 331 r = cg_set_attribute("cpu", path, "cpu.cfs_period_us", buf);
1aeab12b 332 if (r < 0)
077ba06e 333 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
714e2e1d 334 "Failed to set cpu.cfs_period_us on %s: %m", path);
b2f8b02e 335
3a43da28 336 if (c->cpu_quota_per_sec_usec != USEC_INFINITY) {
9a054909 337 sprintf(buf, USEC_FMT "\n", c->cpu_quota_per_sec_usec * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC);
b2f8b02e
LP
338 r = cg_set_attribute("cpu", path, "cpu.cfs_quota_us", buf);
339 } else
340 r = cg_set_attribute("cpu", path, "cpu.cfs_quota_us", "-1");
1aeab12b 341 if (r < 0)
077ba06e 342 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
714e2e1d 343 "Failed to set cpu.cfs_quota_us on %s: %m", path);
4ad49000
LP
344 }
345
efdb0237 346 if (mask & CGROUP_MASK_BLKIO) {
d53d9474
LP
347 char buf[MAX(DECIMAL_STR_MAX(uint64_t)+1,
348 DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1)];
4ad49000
LP
349 CGroupBlockIODeviceWeight *w;
350 CGroupBlockIODeviceBandwidth *b;
351
01efdf13 352 if (!is_root) {
d53d9474
LP
353 sprintf(buf, "%" PRIu64 "\n",
354 IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) && c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ? c->startup_blockio_weight :
355 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ? c->blockio_weight : CGROUP_BLKIO_WEIGHT_DEFAULT);
01efdf13 356 r = cg_set_attribute("blkio", path, "blkio.weight", buf);
1aeab12b 357 if (r < 0)
077ba06e 358 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
714e2e1d 359 "Failed to set blkio.weight on %s: %m", path);
4ad49000 360
01efdf13
LP
361 /* FIXME: no way to reset this list */
362 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
363 dev_t dev;
4ad49000 364
01efdf13
LP
365 r = lookup_blkio_device(w->path, &dev);
366 if (r < 0)
367 continue;
8e274523 368
d53d9474 369 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), w->weight);
01efdf13 370 r = cg_set_attribute("blkio", path, "blkio.weight_device", buf);
1aeab12b 371 if (r < 0)
077ba06e 372 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
714e2e1d 373 "Failed to set blkio.weight_device on %s: %m", path);
01efdf13 374 }
4ad49000
LP
375 }
376
377 /* FIXME: no way to reset this list */
378 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
379 const char *a;
380 dev_t dev;
381
382 r = lookup_blkio_device(b->path, &dev);
383 if (r < 0)
384 continue;
385
386 a = b->read ? "blkio.throttle.read_bps_device" : "blkio.throttle.write_bps_device";
387
388 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), b->bandwidth);
389 r = cg_set_attribute("blkio", path, a, buf);
1aeab12b 390 if (r < 0)
077ba06e 391 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
714e2e1d 392 "Failed to set %s on %s: %m", a, path);
d686d8a9 393 }
8e274523
LP
394 }
395
efdb0237 396 if ((mask & CGROUP_MASK_MEMORY) && !is_root) {
6a94f2e9 397 if (c->memory_limit != (uint64_t) -1) {
e58cec11
LP
398 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
399
6a94f2e9 400 sprintf(buf, "%" PRIu64 "\n", c->memory_limit);
efdb0237
LP
401
402 if (cg_unified() <= 0)
403 r = cg_set_attribute("memory", path, "memory.limit_in_bytes", buf);
404 else
405 r = cg_set_attribute("memory", path, "memory.max", buf);
406
407 } else {
408 if (cg_unified() <= 0)
409 r = cg_set_attribute("memory", path, "memory.limit_in_bytes", "-1");
410 else
411 r = cg_set_attribute("memory", path, "memory.max", "max");
412 }
8e274523 413
1aeab12b 414 if (r < 0)
077ba06e 415 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
efdb0237 416 "Failed to set memory.limit_in_bytes/memory.max on %s: %m", path);
4ad49000 417 }
8e274523 418
3905f127 419 if ((mask & CGROUP_MASK_DEVICES) && !is_root) {
4ad49000 420 CGroupDeviceAllow *a;
8e274523 421
714e2e1d
LP
422 /* Changing the devices list of a populated cgroup
423 * might result in EINVAL, hence ignore EINVAL
424 * here. */
425
4ad49000
LP
426 if (c->device_allow || c->device_policy != CGROUP_AUTO)
427 r = cg_set_attribute("devices", path, "devices.deny", "a");
428 else
429 r = cg_set_attribute("devices", path, "devices.allow", "a");
1aeab12b 430 if (r < 0)
077ba06e 431 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
714e2e1d 432 "Failed to reset devices.list on %s: %m", path);
fb385181 433
4ad49000
LP
434 if (c->device_policy == CGROUP_CLOSED ||
435 (c->device_policy == CGROUP_AUTO && c->device_allow)) {
436 static const char auto_devices[] =
7d711efb
LP
437 "/dev/null\0" "rwm\0"
438 "/dev/zero\0" "rwm\0"
439 "/dev/full\0" "rwm\0"
440 "/dev/random\0" "rwm\0"
441 "/dev/urandom\0" "rwm\0"
442 "/dev/tty\0" "rwm\0"
443 "/dev/pts/ptmx\0" "rw\0"; /* /dev/pts/ptmx may not be duplicated, but accessed */
4ad49000
LP
444
445 const char *x, *y;
446
447 NULSTR_FOREACH_PAIR(x, y, auto_devices)
448 whitelist_device(path, x, y);
7d711efb
LP
449
450 whitelist_major(path, "pts", 'c', "rw");
451 whitelist_major(path, "kdbus", 'c', "rw");
452 whitelist_major(path, "kdbus/*", 'c', "rw");
4ad49000
LP
453 }
454
455 LIST_FOREACH(device_allow, a, c->device_allow) {
456 char acc[4];
457 unsigned k = 0;
458
459 if (a->r)
460 acc[k++] = 'r';
461 if (a->w)
462 acc[k++] = 'w';
463 if (a->m)
464 acc[k++] = 'm';
fb385181 465
4ad49000
LP
466 if (k == 0)
467 continue;
fb385181 468
4ad49000 469 acc[k++] = 0;
90060676
LP
470
471 if (startswith(a->path, "/dev/"))
472 whitelist_device(path, a->path, acc);
473 else if (startswith(a->path, "block-"))
474 whitelist_major(path, a->path + 6, 'b', acc);
475 else if (startswith(a->path, "char-"))
476 whitelist_major(path, a->path + 5, 'c', acc);
477 else
478 log_debug("Ignoring device %s while writing cgroup attribute.", a->path);
4ad49000
LP
479 }
480 }
03a7b521
LP
481
482 if ((mask & CGROUP_MASK_PIDS) && !is_root) {
483
484 if (c->tasks_max != (uint64_t) -1) {
485 char buf[DECIMAL_STR_MAX(uint64_t) + 2];
486
487 sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
488 r = cg_set_attribute("pids", path, "pids.max", buf);
489 } else
490 r = cg_set_attribute("pids", path, "pids.max", "max");
491
492 if (r < 0)
077ba06e 493 log_full_errno(IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
03a7b521
LP
494 "Failed to set pids.max on %s: %m", path);
495 }
fb385181
LP
496}
497
efdb0237
LP
498CGroupMask cgroup_context_get_mask(CGroupContext *c) {
499 CGroupMask mask = 0;
8e274523 500
4ad49000 501 /* Figure out which controllers we need */
8e274523 502
b2f8b02e 503 if (c->cpu_accounting ||
d53d9474
LP
504 c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
505 c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID ||
3a43da28 506 c->cpu_quota_per_sec_usec != USEC_INFINITY)
efdb0237 507 mask |= CGROUP_MASK_CPUACCT | CGROUP_MASK_CPU;
ecedd90f 508
4ad49000 509 if (c->blockio_accounting ||
d53d9474
LP
510 c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
511 c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID ||
4ad49000 512 c->blockio_device_weights ||
db785129 513 c->blockio_device_bandwidths)
efdb0237 514 mask |= CGROUP_MASK_BLKIO;
ecedd90f 515
4ad49000 516 if (c->memory_accounting ||
ddca82ac 517 c->memory_limit != (uint64_t) -1)
efdb0237 518 mask |= CGROUP_MASK_MEMORY;
8e274523 519
a931ad47
LP
520 if (c->device_allow ||
521 c->device_policy != CGROUP_AUTO)
3905f127 522 mask |= CGROUP_MASK_DEVICES;
4ad49000 523
03a7b521
LP
524 if (c->tasks_accounting ||
525 c->tasks_max != (uint64_t) -1)
526 mask |= CGROUP_MASK_PIDS;
527
4ad49000 528 return mask;
8e274523
LP
529}
530
efdb0237 531CGroupMask unit_get_own_mask(Unit *u) {
4ad49000 532 CGroupContext *c;
8e274523 533
efdb0237
LP
534 /* Returns the mask of controllers the unit needs for itself */
535
4ad49000
LP
536 c = unit_get_cgroup_context(u);
537 if (!c)
538 return 0;
8e274523 539
a931ad47 540 /* If delegation is turned on, then turn on all cgroups,
19af675e
LP
541 * unless we are on the legacy hierarchy and the process we
542 * fork into it is known to drop privileges, and hence
543 * shouldn't get access to the controllers.
544 *
545 * Note that on the unified hierarchy it is safe to delegate
546 * controllers to unprivileged services. */
a931ad47
LP
547
548 if (c->delegate) {
549 ExecContext *e;
550
551 e = unit_get_exec_context(u);
19af675e
LP
552 if (!e ||
553 exec_context_maintains_privileges(e) ||
554 cg_unified() > 0)
efdb0237 555 return _CGROUP_MASK_ALL;
a931ad47
LP
556 }
557
db785129 558 return cgroup_context_get_mask(c);
8e274523
LP
559}
560
efdb0237 561CGroupMask unit_get_members_mask(Unit *u) {
4ad49000 562 assert(u);
bc432dc7 563
efdb0237
LP
564 /* Returns the mask of controllers all of the unit's children
565 * require, merged */
566
bc432dc7
LP
567 if (u->cgroup_members_mask_valid)
568 return u->cgroup_members_mask;
569
570 u->cgroup_members_mask = 0;
571
572 if (u->type == UNIT_SLICE) {
573 Unit *member;
574 Iterator i;
575
576 SET_FOREACH(member, u->dependencies[UNIT_BEFORE], i) {
577
578 if (member == u)
579 continue;
580
d4fdc205 581 if (UNIT_DEREF(member->slice) != u)
bc432dc7
LP
582 continue;
583
584 u->cgroup_members_mask |=
efdb0237 585 unit_get_own_mask(member) |
bc432dc7
LP
586 unit_get_members_mask(member);
587 }
588 }
589
590 u->cgroup_members_mask_valid = true;
6414b7c9 591 return u->cgroup_members_mask;
246aa6dd
LP
592}
593
efdb0237 594CGroupMask unit_get_siblings_mask(Unit *u) {
4ad49000 595 assert(u);
246aa6dd 596
efdb0237
LP
597 /* Returns the mask of controllers all of the unit's siblings
598 * require, i.e. the members mask of the unit's parent slice
599 * if there is one. */
600
bc432dc7 601 if (UNIT_ISSET(u->slice))
637f421e 602 return unit_get_members_mask(UNIT_DEREF(u->slice));
4ad49000 603
efdb0237 604 return unit_get_own_mask(u) | unit_get_members_mask(u);
246aa6dd
LP
605}
606
efdb0237
LP
607CGroupMask unit_get_subtree_mask(Unit *u) {
608
609 /* Returns the mask of this subtree, meaning of the group
610 * itself and its children. */
611
612 return unit_get_own_mask(u) | unit_get_members_mask(u);
613}
614
615CGroupMask unit_get_target_mask(Unit *u) {
616 CGroupMask mask;
617
618 /* This returns the cgroup mask of all controllers to enable
619 * for a specific cgroup, i.e. everything it needs itself,
620 * plus all that its children need, plus all that its siblings
621 * need. This is primarily useful on the legacy cgroup
622 * hierarchy, where we need to duplicate each cgroup in each
623 * hierarchy that shall be enabled for it. */
6414b7c9 624
efdb0237
LP
625 mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
626 mask &= u->manager->cgroup_supported;
627
628 return mask;
629}
630
631CGroupMask unit_get_enable_mask(Unit *u) {
632 CGroupMask mask;
633
634 /* This returns the cgroup mask of all controllers to enable
635 * for the children of a specific cgroup. This is primarily
636 * useful for the unified cgroup hierarchy, where each cgroup
637 * controls which controllers are enabled for its children. */
638
639 mask = unit_get_members_mask(u);
6414b7c9
DS
640 mask &= u->manager->cgroup_supported;
641
642 return mask;
643}
644
645/* Recurse from a unit up through its containing slices, propagating
646 * mask bits upward. A unit is also member of itself. */
bc432dc7 647void unit_update_cgroup_members_masks(Unit *u) {
efdb0237 648 CGroupMask m;
bc432dc7
LP
649 bool more;
650
651 assert(u);
652
653 /* Calculate subtree mask */
efdb0237 654 m = unit_get_subtree_mask(u);
bc432dc7
LP
655
656 /* See if anything changed from the previous invocation. If
657 * not, we're done. */
658 if (u->cgroup_subtree_mask_valid && m == u->cgroup_subtree_mask)
659 return;
660
661 more =
662 u->cgroup_subtree_mask_valid &&
663 ((m & ~u->cgroup_subtree_mask) != 0) &&
664 ((~m & u->cgroup_subtree_mask) == 0);
665
666 u->cgroup_subtree_mask = m;
667 u->cgroup_subtree_mask_valid = true;
668
6414b7c9
DS
669 if (UNIT_ISSET(u->slice)) {
670 Unit *s = UNIT_DEREF(u->slice);
bc432dc7
LP
671
672 if (more)
673 /* There's more set now than before. We
674 * propagate the new mask to the parent's mask
675 * (not caring if it actually was valid or
676 * not). */
677
678 s->cgroup_members_mask |= m;
679
680 else
681 /* There's less set now than before (or we
682 * don't know), we need to recalculate
683 * everything, so let's invalidate the
684 * parent's members mask */
685
686 s->cgroup_members_mask_valid = false;
687
688 /* And now make sure that this change also hits our
689 * grandparents */
690 unit_update_cgroup_members_masks(s);
6414b7c9
DS
691 }
692}
693
efdb0237 694static const char *migrate_callback(CGroupMask mask, void *userdata) {
03b90d4b
LP
695 Unit *u = userdata;
696
697 assert(mask != 0);
698 assert(u);
699
700 while (u) {
701 if (u->cgroup_path &&
702 u->cgroup_realized &&
703 (u->cgroup_realized_mask & mask) == mask)
704 return u->cgroup_path;
705
706 u = UNIT_DEREF(u->slice);
707 }
708
709 return NULL;
710}
711
efdb0237
LP
712char *unit_default_cgroup_path(Unit *u) {
713 _cleanup_free_ char *escaped = NULL, *slice = NULL;
714 int r;
715
716 assert(u);
717
718 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
719 return strdup(u->manager->cgroup_root);
720
721 if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
722 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
723 if (r < 0)
724 return NULL;
725 }
726
727 escaped = cg_escape(u->id);
728 if (!escaped)
729 return NULL;
730
731 if (slice)
732 return strjoin(u->manager->cgroup_root, "/", slice, "/", escaped, NULL);
733 else
734 return strjoin(u->manager->cgroup_root, "/", escaped, NULL);
735}
736
737int unit_set_cgroup_path(Unit *u, const char *path) {
738 _cleanup_free_ char *p = NULL;
739 int r;
740
741 assert(u);
742
743 if (path) {
744 p = strdup(path);
745 if (!p)
746 return -ENOMEM;
747 } else
748 p = NULL;
749
750 if (streq_ptr(u->cgroup_path, p))
751 return 0;
752
753 if (p) {
754 r = hashmap_put(u->manager->cgroup_unit, p, u);
755 if (r < 0)
756 return r;
757 }
758
759 unit_release_cgroup(u);
760
761 u->cgroup_path = p;
762 p = NULL;
763
764 return 1;
765}
766
767int unit_watch_cgroup(Unit *u) {
768 _cleanup_free_ char *populated = NULL;
769 int r;
770
771 assert(u);
772
773 if (!u->cgroup_path)
774 return 0;
775
776 if (u->cgroup_inotify_wd >= 0)
777 return 0;
778
779 /* Only applies to the unified hierarchy */
780 r = cg_unified();
781 if (r < 0)
782 return log_unit_error_errno(u, r, "Failed detect wether the unified hierarchy is used: %m");
783 if (r == 0)
784 return 0;
785
786 /* Don't watch the root slice, it's pointless. */
787 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
788 return 0;
789
790 r = hashmap_ensure_allocated(&u->manager->cgroup_inotify_wd_unit, &trivial_hash_ops);
791 if (r < 0)
792 return log_oom();
793
794 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.populated", &populated);
795 if (r < 0)
796 return log_oom();
797
798 u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, populated, IN_MODIFY);
799 if (u->cgroup_inotify_wd < 0) {
800
801 if (errno == ENOENT) /* If the directory is already
802 * gone we don't need to track
803 * it, so this is not an error */
804 return 0;
805
806 return log_unit_error_errno(u, errno, "Failed to add inotify watch descriptor for control group %s: %m", u->cgroup_path);
807 }
808
809 r = hashmap_put(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd), u);
810 if (r < 0)
811 return log_unit_error_errno(u, r, "Failed to add inotify watch descriptor to hash map: %m");
812
813 return 0;
814}
815
816static int unit_create_cgroup(
817 Unit *u,
818 CGroupMask target_mask,
819 CGroupMask enable_mask) {
820
0cd385d3 821 CGroupContext *c;
bc432dc7 822 int r;
64747e2d 823
4ad49000 824 assert(u);
64747e2d 825
0cd385d3
LP
826 c = unit_get_cgroup_context(u);
827 if (!c)
828 return 0;
829
7b3fd631
LP
830 if (!u->cgroup_path) {
831 _cleanup_free_ char *path = NULL;
64747e2d 832
7b3fd631
LP
833 path = unit_default_cgroup_path(u);
834 if (!path)
835 return log_oom();
836
efdb0237
LP
837 r = unit_set_cgroup_path(u, path);
838 if (r == -EEXIST)
839 return log_unit_error_errno(u, r, "Control group %s exists already.", path);
840 if (r < 0)
841 return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
b58b8e11
HH
842 }
843
03b90d4b 844 /* First, create our own group */
efdb0237 845 r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
23bbb0de 846 if (r < 0)
efdb0237
LP
847 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
848
849 /* Start watching it */
850 (void) unit_watch_cgroup(u);
851
852 /* Enable all controllers we need */
853 r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path);
854 if (r < 0)
855 log_unit_warning_errno(u, r, "Failed to enable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
03b90d4b
LP
856
857 /* Keep track that this is now realized */
4ad49000 858 u->cgroup_realized = true;
efdb0237 859 u->cgroup_realized_mask = target_mask;
4ad49000 860
0cd385d3
LP
861 if (u->type != UNIT_SLICE && !c->delegate) {
862
863 /* Then, possibly move things over, but not if
864 * subgroups may contain processes, which is the case
865 * for slice and delegation units. */
866 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
867 if (r < 0)
efdb0237 868 log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
0cd385d3 869 }
03b90d4b 870
64747e2d
LP
871 return 0;
872}
873
7b3fd631
LP
874int unit_attach_pids_to_cgroup(Unit *u) {
875 int r;
876 assert(u);
877
878 r = unit_realize_cgroup(u);
879 if (r < 0)
880 return r;
881
882 r = cg_attach_many_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->pids, migrate_callback, u);
883 if (r < 0)
884 return r;
885
886 return 0;
887}
888
efdb0237 889static bool unit_has_mask_realized(Unit *u, CGroupMask target_mask) {
bc432dc7
LP
890 assert(u);
891
efdb0237 892 return u->cgroup_realized && u->cgroup_realized_mask == target_mask;
6414b7c9
DS
893}
894
895/* Check if necessary controllers and attributes for a unit are in place.
896 *
897 * If so, do nothing.
898 * If not, create paths, move processes over, and set attributes.
899 *
900 * Returns 0 on success and < 0 on failure. */
db785129 901static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
efdb0237 902 CGroupMask target_mask, enable_mask;
6414b7c9 903 int r;
64747e2d 904
4ad49000 905 assert(u);
64747e2d 906
4ad49000 907 if (u->in_cgroup_queue) {
71fda00f 908 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
4ad49000
LP
909 u->in_cgroup_queue = false;
910 }
64747e2d 911
efdb0237
LP
912 target_mask = unit_get_target_mask(u);
913 if (unit_has_mask_realized(u, target_mask))
0a1eb06d 914 return 0;
64747e2d 915
4ad49000 916 /* First, realize parents */
6414b7c9 917 if (UNIT_ISSET(u->slice)) {
db785129 918 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
6414b7c9
DS
919 if (r < 0)
920 return r;
921 }
4ad49000
LP
922
923 /* And then do the real work */
efdb0237
LP
924 enable_mask = unit_get_enable_mask(u);
925 r = unit_create_cgroup(u, target_mask, enable_mask);
6414b7c9
DS
926 if (r < 0)
927 return r;
928
929 /* Finally, apply the necessary attributes. */
50f48ad3 930 cgroup_context_apply(unit_get_cgroup_context(u), target_mask, u->cgroup_path, state);
6414b7c9
DS
931
932 return 0;
64747e2d
LP
933}
934
4ad49000 935static void unit_add_to_cgroup_queue(Unit *u) {
ecedd90f 936
4ad49000
LP
937 if (u->in_cgroup_queue)
938 return;
8e274523 939
71fda00f 940 LIST_PREPEND(cgroup_queue, u->manager->cgroup_queue, u);
4ad49000
LP
941 u->in_cgroup_queue = true;
942}
8c6db833 943
4ad49000 944unsigned manager_dispatch_cgroup_queue(Manager *m) {
db785129 945 ManagerState state;
4ad49000 946 unsigned n = 0;
db785129 947 Unit *i;
6414b7c9 948 int r;
ecedd90f 949
db785129
LP
950 state = manager_state(m);
951
4ad49000
LP
952 while ((i = m->cgroup_queue)) {
953 assert(i->in_cgroup_queue);
ecedd90f 954
db785129 955 r = unit_realize_cgroup_now(i, state);
6414b7c9 956 if (r < 0)
efdb0237 957 log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
0a1eb06d 958
4ad49000
LP
959 n++;
960 }
ecedd90f 961
4ad49000 962 return n;
8e274523
LP
963}
964
4ad49000
LP
965static void unit_queue_siblings(Unit *u) {
966 Unit *slice;
ca949c9d 967
4ad49000
LP
968 /* This adds the siblings of the specified unit and the
969 * siblings of all parent units to the cgroup queue. (But
970 * neither the specified unit itself nor the parents.) */
971
972 while ((slice = UNIT_DEREF(u->slice))) {
973 Iterator i;
974 Unit *m;
8f53a7b8 975
4ad49000
LP
976 SET_FOREACH(m, slice->dependencies[UNIT_BEFORE], i) {
977 if (m == u)
978 continue;
8e274523 979
6414b7c9
DS
980 /* Skip units that have a dependency on the slice
981 * but aren't actually in it. */
4ad49000 982 if (UNIT_DEREF(m->slice) != slice)
50159e6a 983 continue;
8e274523 984
6414b7c9
DS
985 /* No point in doing cgroup application for units
986 * without active processes. */
987 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
988 continue;
989
990 /* If the unit doesn't need any new controllers
991 * and has current ones realized, it doesn't need
992 * any changes. */
993 if (unit_has_mask_realized(m, unit_get_target_mask(m)))
994 continue;
995
4ad49000 996 unit_add_to_cgroup_queue(m);
50159e6a
LP
997 }
998
4ad49000 999 u = slice;
8e274523 1000 }
4ad49000
LP
1001}
1002
0a1eb06d 1003int unit_realize_cgroup(Unit *u) {
4ad49000
LP
1004 assert(u);
1005
35b7ff80 1006 if (!UNIT_HAS_CGROUP_CONTEXT(u))
0a1eb06d 1007 return 0;
8e274523 1008
4ad49000
LP
1009 /* So, here's the deal: when realizing the cgroups for this
1010 * unit, we need to first create all parents, but there's more
1011 * actually: for the weight-based controllers we also need to
1012 * make sure that all our siblings (i.e. units that are in the
73e231ab 1013 * same slice as we are) have cgroups, too. Otherwise, things
4ad49000
LP
1014 * would become very uneven as each of their processes would
1015 * get as much resources as all our group together. This call
1016 * will synchronously create the parent cgroups, but will
1017 * defer work on the siblings to the next event loop
1018 * iteration. */
ca949c9d 1019
4ad49000
LP
1020 /* Add all sibling slices to the cgroup queue. */
1021 unit_queue_siblings(u);
1022
6414b7c9 1023 /* And realize this one now (and apply the values) */
db785129 1024 return unit_realize_cgroup_now(u, manager_state(u->manager));
8e274523
LP
1025}
1026
efdb0237
LP
1027void unit_release_cgroup(Unit *u) {
1028 assert(u);
1029
1030 /* Forgets all cgroup details for this cgroup */
1031
1032 if (u->cgroup_path) {
1033 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1034 u->cgroup_path = mfree(u->cgroup_path);
1035 }
1036
1037 if (u->cgroup_inotify_wd >= 0) {
1038 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1039 log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1040
1041 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1042 u->cgroup_inotify_wd = -1;
1043 }
1044}
1045
1046void unit_prune_cgroup(Unit *u) {
8e274523 1047 int r;
efdb0237 1048 bool is_root_slice;
8e274523 1049
4ad49000 1050 assert(u);
8e274523 1051
efdb0237
LP
1052 /* Removes the cgroup, if empty and possible, and stops watching it. */
1053
4ad49000
LP
1054 if (!u->cgroup_path)
1055 return;
8e274523 1056
efdb0237
LP
1057 is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1058
1059 r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
dab5bf85 1060 if (r < 0) {
efdb0237 1061 log_debug_errno(r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
dab5bf85
RL
1062 return;
1063 }
8e274523 1064
efdb0237
LP
1065 if (is_root_slice)
1066 return;
1067
1068 unit_release_cgroup(u);
0a1eb06d 1069
4ad49000 1070 u->cgroup_realized = false;
bc432dc7 1071 u->cgroup_realized_mask = 0;
8e274523
LP
1072}
1073
efdb0237 1074int unit_search_main_pid(Unit *u, pid_t *ret) {
4ad49000
LP
1075 _cleanup_fclose_ FILE *f = NULL;
1076 pid_t pid = 0, npid, mypid;
efdb0237 1077 int r;
4ad49000
LP
1078
1079 assert(u);
efdb0237 1080 assert(ret);
4ad49000
LP
1081
1082 if (!u->cgroup_path)
efdb0237 1083 return -ENXIO;
4ad49000 1084
efdb0237
LP
1085 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1086 if (r < 0)
1087 return r;
4ad49000
LP
1088
1089 mypid = getpid();
1090 while (cg_read_pid(f, &npid) > 0) {
1091 pid_t ppid;
1092
1093 if (npid == pid)
1094 continue;
8e274523 1095
4ad49000 1096 /* Ignore processes that aren't our kids */
6bc73acb 1097 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
4ad49000 1098 continue;
8e274523 1099
efdb0237 1100 if (pid != 0)
4ad49000
LP
1101 /* Dang, there's more than one daemonized PID
1102 in this group, so we don't know what process
1103 is the main process. */
efdb0237
LP
1104
1105 return -ENODATA;
8e274523 1106
4ad49000 1107 pid = npid;
8e274523
LP
1108 }
1109
efdb0237
LP
1110 *ret = pid;
1111 return 0;
1112}
1113
1114static int unit_watch_pids_in_path(Unit *u, const char *path) {
b3c5bad3 1115 _cleanup_closedir_ DIR *d = NULL;
efdb0237
LP
1116 _cleanup_fclose_ FILE *f = NULL;
1117 int ret = 0, r;
1118
1119 assert(u);
1120 assert(path);
1121
1122 r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1123 if (r < 0)
1124 ret = r;
1125 else {
1126 pid_t pid;
1127
1128 while ((r = cg_read_pid(f, &pid)) > 0) {
1129 r = unit_watch_pid(u, pid);
1130 if (r < 0 && ret >= 0)
1131 ret = r;
1132 }
1133
1134 if (r < 0 && ret >= 0)
1135 ret = r;
1136 }
1137
1138 r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1139 if (r < 0) {
1140 if (ret >= 0)
1141 ret = r;
1142 } else {
1143 char *fn;
1144
1145 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1146 _cleanup_free_ char *p = NULL;
1147
1148 p = strjoin(path, "/", fn, NULL);
1149 free(fn);
1150
1151 if (!p)
1152 return -ENOMEM;
1153
1154 r = unit_watch_pids_in_path(u, p);
1155 if (r < 0 && ret >= 0)
1156 ret = r;
1157 }
1158
1159 if (r < 0 && ret >= 0)
1160 ret = r;
1161 }
1162
1163 return ret;
1164}
1165
1166int unit_watch_all_pids(Unit *u) {
1167 assert(u);
1168
1169 /* Adds all PIDs from our cgroup to the set of PIDs we
1170 * watch. This is a fallback logic for cases where we do not
1171 * get reliable cgroup empty notifications: we try to use
1172 * SIGCHLD as replacement. */
1173
1174 if (!u->cgroup_path)
1175 return -ENOENT;
1176
1177 if (cg_unified() > 0) /* On unified we can use proper notifications */
1178 return 0;
1179
1180 return unit_watch_pids_in_path(u, u->cgroup_path);
1181}
1182
1183int unit_notify_cgroup_empty(Unit *u) {
1184 int r;
1185
1186 assert(u);
1187
1188 if (!u->cgroup_path)
1189 return 0;
1190
1191 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
1192 if (r <= 0)
1193 return r;
1194
1195 unit_add_to_gc_queue(u);
1196
1197 if (UNIT_VTABLE(u)->notify_cgroup_empty)
1198 UNIT_VTABLE(u)->notify_cgroup_empty(u);
1199
1200 return 0;
1201}
1202
1203static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1204 Manager *m = userdata;
1205
1206 assert(s);
1207 assert(fd >= 0);
1208 assert(m);
1209
1210 for (;;) {
1211 union inotify_event_buffer buffer;
1212 struct inotify_event *e;
1213 ssize_t l;
1214
1215 l = read(fd, &buffer, sizeof(buffer));
1216 if (l < 0) {
1217 if (errno == EINTR || errno == EAGAIN)
1218 return 0;
1219
1220 return log_error_errno(errno, "Failed to read control group inotify events: %m");
1221 }
1222
1223 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1224 Unit *u;
1225
1226 if (e->wd < 0)
1227 /* Queue overflow has no watch descriptor */
1228 continue;
1229
1230 if (e->mask & IN_IGNORED)
1231 /* The watch was just removed */
1232 continue;
1233
1234 u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
1235 if (!u) /* Not that inotify might deliver
1236 * events for a watch even after it
1237 * was removed, because it was queued
1238 * before the removal. Let's ignore
1239 * this here safely. */
1240 continue;
1241
1242 (void) unit_notify_cgroup_empty(u);
1243 }
1244 }
8e274523
LP
1245}
1246
8e274523 1247int manager_setup_cgroup(Manager *m) {
9444b1f2 1248 _cleanup_free_ char *path = NULL;
efdb0237
LP
1249 CGroupController c;
1250 int r, unified;
1251 char *e;
8e274523
LP
1252
1253 assert(m);
1254
35d2e7ec 1255 /* 1. Determine hierarchy */
efdb0237 1256 m->cgroup_root = mfree(m->cgroup_root);
9444b1f2 1257 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
23bbb0de
MS
1258 if (r < 0)
1259 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
8e274523 1260
efdb0237
LP
1261 /* Chop off the init scope, if we are already located in it */
1262 e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
0d8c31ff 1263
efdb0237
LP
1264 /* LEGACY: Also chop off the system slice if we are in
1265 * it. This is to support live upgrades from older systemd
1266 * versions where PID 1 was moved there. Also see
1267 * cg_get_root_path(). */
1268 if (!e && m->running_as == MANAGER_SYSTEM) {
9444b1f2 1269 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
15c60e99 1270 if (!e)
efdb0237 1271 e = endswith(m->cgroup_root, "/system"); /* even more legacy */
0baf24dd 1272 }
efdb0237
LP
1273 if (e)
1274 *e = 0;
7ccfb64a 1275
9444b1f2
LP
1276 /* And make sure to store away the root value without trailing
1277 * slash, even for the root dir, so that we can easily prepend
1278 * it everywhere. */
efdb0237
LP
1279 while ((e = endswith(m->cgroup_root, "/")))
1280 *e = 0;
8e274523 1281
35d2e7ec 1282 /* 2. Show data */
9444b1f2 1283 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
23bbb0de
MS
1284 if (r < 0)
1285 return log_error_errno(r, "Cannot find cgroup mount point: %m");
8e274523 1286
efdb0237
LP
1287 unified = cg_unified();
1288 if (unified < 0)
1289 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
1290 if (unified > 0)
1291 log_debug("Unified cgroup hierarchy is located at %s.", path);
1292 else
1293 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER ". File system hierarchy is at %s.", path);
1294
0d8c31ff 1295 if (!m->test_run) {
efdb0237 1296 const char *scope_path;
c6c18be3 1297
0d8c31ff 1298 /* 3. Install agent */
efdb0237
LP
1299 if (unified) {
1300
1301 /* In the unified hierarchy we can can get
1302 * cgroup empty notifications via inotify. */
1303
1304 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1305 safe_close(m->cgroup_inotify_fd);
1306
1307 m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1308 if (m->cgroup_inotify_fd < 0)
1309 return log_error_errno(errno, "Failed to create control group inotify object: %m");
1310
1311 r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
1312 if (r < 0)
1313 return log_error_errno(r, "Failed to watch control group inotify object: %m");
1314
1315 r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_IDLE - 5);
1316 if (r < 0)
1317 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
1318
1319 (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
1320
1321 } else if (m->running_as == MANAGER_SYSTEM) {
1322
1323 /* On the legacy hierarchy we only get
1324 * notifications via cgroup agents. (Which
1325 * isn't really reliable, since it does not
1326 * generate events when control groups with
1327 * children run empty. */
1328
0d8c31ff
ZJS
1329 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
1330 if (r < 0)
da927ba9 1331 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
0d8c31ff
ZJS
1332 else if (r > 0)
1333 log_debug("Installed release agent.");
efdb0237 1334 else if (r == 0)
0d8c31ff
ZJS
1335 log_debug("Release agent already installed.");
1336 }
8e274523 1337
efdb0237
LP
1338 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1339 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1340 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
23bbb0de 1341 if (r < 0)
efdb0237
LP
1342 return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
1343
1344 /* also, move all other userspace processes remaining
1345 * in the root cgroup into that scope. */
1346 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, false);
1347 if (r < 0)
1348 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
c6c18be3 1349
0d8c31ff
ZJS
1350 /* 5. And pin it, so that it cannot be unmounted */
1351 safe_close(m->pin_cgroupfs_fd);
0d8c31ff 1352 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
4a62c710
MS
1353 if (m->pin_cgroupfs_fd < 0)
1354 return log_error_errno(errno, "Failed to open pin file: %m");
0d8c31ff 1355
cc98b302 1356 /* 6. Always enable hierarchical support if it exists... */
efdb0237
LP
1357 if (!unified)
1358 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
c6c18be3
LP
1359 }
1360
0d8c31ff 1361 /* 7. Figure out which controllers are supported */
efdb0237
LP
1362 r = cg_mask_supported(&m->cgroup_supported);
1363 if (r < 0)
1364 return log_error_errno(r, "Failed to determine supported controllers: %m");
1365
1366 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
1367 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & c));
9156e799 1368
a32360f1 1369 return 0;
8e274523
LP
1370}
1371
c6c18be3 1372void manager_shutdown_cgroup(Manager *m, bool delete) {
8e274523
LP
1373 assert(m);
1374
9444b1f2
LP
1375 /* We can't really delete the group, since we are in it. But
1376 * let's trim it. */
1377 if (delete && m->cgroup_root)
efdb0237
LP
1378 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
1379
1380 m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
1381
1382 m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1383 m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
8e274523 1384
03e334a1 1385 m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
c6c18be3 1386
efdb0237 1387 m->cgroup_root = mfree(m->cgroup_root);
8e274523
LP
1388}
1389
4ad49000 1390Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
acb14d31 1391 char *p;
4ad49000 1392 Unit *u;
acb14d31
LP
1393
1394 assert(m);
1395 assert(cgroup);
acb14d31 1396
4ad49000
LP
1397 u = hashmap_get(m->cgroup_unit, cgroup);
1398 if (u)
1399 return u;
acb14d31 1400
8e70580b 1401 p = strdupa(cgroup);
acb14d31
LP
1402 for (;;) {
1403 char *e;
1404
1405 e = strrchr(p, '/');
efdb0237
LP
1406 if (!e || e == p)
1407 return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
acb14d31
LP
1408
1409 *e = 0;
1410
4ad49000
LP
1411 u = hashmap_get(m->cgroup_unit, p);
1412 if (u)
1413 return u;
acb14d31
LP
1414 }
1415}
1416
b3ac818b 1417Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
4ad49000 1418 _cleanup_free_ char *cgroup = NULL;
acb14d31 1419 int r;
8e274523 1420
8c47c732
LP
1421 assert(m);
1422
b3ac818b
LP
1423 if (pid <= 0)
1424 return NULL;
1425
1426 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
1427 if (r < 0)
1428 return NULL;
1429
1430 return manager_get_unit_by_cgroup(m, cgroup);
1431}
1432
1433Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
1434 Unit *u;
1435
1436 assert(m);
1437
efdb0237 1438 if (pid <= 0)
8c47c732
LP
1439 return NULL;
1440
efdb0237
LP
1441 if (pid == 1)
1442 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
1443
fea72cc0 1444 u = hashmap_get(m->watch_pids1, PID_TO_PTR(pid));
5fe8876b
LP
1445 if (u)
1446 return u;
1447
fea72cc0 1448 u = hashmap_get(m->watch_pids2, PID_TO_PTR(pid));
5fe8876b
LP
1449 if (u)
1450 return u;
1451
b3ac818b 1452 return manager_get_unit_by_pid_cgroup(m, pid);
6dde1f33 1453}
4fbf50b3 1454
4ad49000
LP
1455int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
1456 Unit *u;
4fbf50b3 1457
4ad49000
LP
1458 assert(m);
1459 assert(cgroup);
4fbf50b3 1460
4ad49000 1461 u = manager_get_unit_by_cgroup(m, cgroup);
5ad096b3
LP
1462 if (!u)
1463 return 0;
b56c28c3 1464
efdb0237 1465 return unit_notify_cgroup_empty(u);
5ad096b3
LP
1466}
1467
1468int unit_get_memory_current(Unit *u, uint64_t *ret) {
1469 _cleanup_free_ char *v = NULL;
1470 int r;
1471
1472 assert(u);
1473 assert(ret);
1474
1475 if (!u->cgroup_path)
1476 return -ENODATA;
1477
efdb0237 1478 if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
5ad096b3
LP
1479 return -ENODATA;
1480
efdb0237
LP
1481 if (cg_unified() <= 0)
1482 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
1483 else
1484 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
5ad096b3
LP
1485 if (r == -ENOENT)
1486 return -ENODATA;
1487 if (r < 0)
1488 return r;
1489
1490 return safe_atou64(v, ret);
1491}
1492
03a7b521
LP
1493int unit_get_tasks_current(Unit *u, uint64_t *ret) {
1494 _cleanup_free_ char *v = NULL;
1495 int r;
1496
1497 assert(u);
1498 assert(ret);
1499
1500 if (!u->cgroup_path)
1501 return -ENODATA;
1502
1503 if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
1504 return -ENODATA;
1505
1506 r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
1507 if (r == -ENOENT)
1508 return -ENODATA;
1509 if (r < 0)
1510 return r;
1511
1512 return safe_atou64(v, ret);
1513}
1514
5ad096b3
LP
1515static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
1516 _cleanup_free_ char *v = NULL;
1517 uint64_t ns;
1518 int r;
1519
1520 assert(u);
1521 assert(ret);
1522
1523 if (!u->cgroup_path)
1524 return -ENODATA;
1525
efdb0237 1526 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
5ad096b3
LP
1527 return -ENODATA;
1528
1529 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
1530 if (r == -ENOENT)
1531 return -ENODATA;
1532 if (r < 0)
1533 return r;
1534
1535 r = safe_atou64(v, &ns);
1536 if (r < 0)
1537 return r;
1538
1539 *ret = ns;
1540 return 0;
1541}
1542
1543int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
1544 nsec_t ns;
1545 int r;
1546
1547 r = unit_get_cpu_usage_raw(u, &ns);
1548 if (r < 0)
1549 return r;
1550
1551 if (ns > u->cpuacct_usage_base)
1552 ns -= u->cpuacct_usage_base;
1553 else
1554 ns = 0;
1555
1556 *ret = ns;
1557 return 0;
1558}
1559
1560int unit_reset_cpu_usage(Unit *u) {
1561 nsec_t ns;
1562 int r;
1563
1564 assert(u);
1565
1566 r = unit_get_cpu_usage_raw(u, &ns);
1567 if (r < 0) {
1568 u->cpuacct_usage_base = 0;
1569 return r;
b56c28c3 1570 }
2633eb83 1571
5ad096b3 1572 u->cpuacct_usage_base = ns;
4ad49000 1573 return 0;
4fbf50b3
LP
1574}
1575
e9db43d5
LP
1576bool unit_cgroup_delegate(Unit *u) {
1577 CGroupContext *c;
1578
1579 assert(u);
1580
1581 c = unit_get_cgroup_context(u);
1582 if (!c)
1583 return false;
1584
1585 return c->delegate;
1586}
1587
e7ab4d1a
LP
1588void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
1589 assert(u);
1590
1591 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1592 return;
1593
1594 if (m == 0)
1595 return;
1596
1597 if ((u->cgroup_realized_mask & m) == 0)
1598 return;
1599
1600 u->cgroup_realized_mask &= ~m;
1601 unit_add_to_cgroup_queue(u);
1602}
1603
1604void manager_invalidate_startup_units(Manager *m) {
1605 Iterator i;
1606 Unit *u;
1607
1608 assert(m);
1609
1610 SET_FOREACH(u, m->startup_units, i)
1611 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_BLKIO);
1612}
1613
4ad49000
LP
1614static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
1615 [CGROUP_AUTO] = "auto",
1616 [CGROUP_CLOSED] = "closed",
1617 [CGROUP_STRICT] = "strict",
1618};
4fbf50b3 1619
4ad49000 1620DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);