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