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