chiark / gitweb /
tree-wide: drop NULL sentinel from strjoin
[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_weight) {
692                                 uint64_t weight = cgroup_context_cpu_weight(c, state);
693
694                                 shares = cgroup_cpu_weight_to_shares(weight);
695
696                                 log_cgroup_compat(u, "Applying [Startup]CpuWeight %" PRIu64 " as [Startup]CpuShares %" PRIu64 " on %s",
697                                                   weight, shares, path);
698                         } else if (has_shares)
699                                 shares = cgroup_context_cpu_shares(c, state);
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_io) {
793                                 uint64_t io_weight = cgroup_context_io_weight(c, state);
794
795                                 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
796
797                                 log_cgroup_compat(u, "Applying [Startup]IOWeight %" PRIu64 " as [Startup]BlockIOWeight %" PRIu64,
798                                                   io_weight, weight);
799                         } else if (has_blockio)
800                                 weight = cgroup_context_blkio_weight(c, state);
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_io) {
811                                 CGroupIODeviceWeight *w;
812
813                                 /* FIXME: no way to reset this list */
814                                 LIST_FOREACH(device_weights, w, c->io_device_weights) {
815                                         weight = cgroup_weight_io_to_blkio(w->weight);
816
817                                         log_cgroup_compat(u, "Applying IODeviceWeight %" PRIu64 " as BlockIODeviceWeight %" PRIu64 " for %s",
818                                                           w->weight, weight, w->path);
819
820                                         cgroup_apply_blkio_device_weight(u, w->path, weight);
821                                 }
822                         } else if (has_blockio) {
823                                 CGroupBlockIODeviceWeight *w;
824
825                                 /* FIXME: no way to reset this list */
826                                 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
827                                         cgroup_apply_blkio_device_weight(u, w->path, w->weight);
828                         }
829                 }
830
831                 /* Apply limits and free ones without config. */
832                 if (has_io) {
833                         CGroupIODeviceLimit *l, *next;
834
835                         LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
836                                 log_cgroup_compat(u, "Applying IO{Read|Write}Bandwidth %" PRIu64 " %" PRIu64 " as BlockIO{Read|Write}BandwidthMax for %s",
837                                                   l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX], l->path);
838
839                                 if (!cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]))
840                                         cgroup_context_free_io_device_limit(c, l);
841                         }
842                 } else if (has_blockio) {
843                         CGroupBlockIODeviceBandwidth *b, *next;
844
845                         LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths)
846                                 if (!cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps))
847                                         cgroup_context_free_blockio_device_bandwidth(c, b);
848                 }
849         }
850
851         if ((mask & CGROUP_MASK_MEMORY) && !is_root) {
852                 if (cg_all_unified() > 0) {
853                         uint64_t max;
854                         uint64_t swap_max = CGROUP_LIMIT_MAX;
855
856                         if (cgroup_context_has_unified_memory_config(c)) {
857                                 max = c->memory_max;
858                                 swap_max = c->memory_swap_max;
859                         } else {
860                                 max = c->memory_limit;
861
862                                 if (max != CGROUP_LIMIT_MAX)
863                                         log_cgroup_compat(u, "Applying MemoryLimit %" PRIu64 " as MemoryMax", max);
864                         }
865
866                         cgroup_apply_unified_memory_limit(u, "memory.low", c->memory_low);
867                         cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
868                         cgroup_apply_unified_memory_limit(u, "memory.max", max);
869                         cgroup_apply_unified_memory_limit(u, "memory.swap.max", swap_max);
870                 } else {
871                         char buf[DECIMAL_STR_MAX(uint64_t) + 1];
872                         uint64_t val;
873
874                         if (cgroup_context_has_unified_memory_config(c)) {
875                                 val = c->memory_max;
876                                 log_cgroup_compat(u, "Applying MemoryMax %" PRIi64 " as MemoryLimit", val);
877                         } else
878                                 val = c->memory_limit;
879
880                         if (val == CGROUP_LIMIT_MAX)
881                                 strncpy(buf, "-1\n", sizeof(buf));
882                         else
883                                 xsprintf(buf, "%" PRIu64 "\n", val);
884
885                         r = cg_set_attribute("memory", path, "memory.limit_in_bytes", buf);
886                         if (r < 0)
887                                 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
888                                               "Failed to set memory.limit_in_bytes: %m");
889                 }
890         }
891
892         if ((mask & CGROUP_MASK_DEVICES) && !is_root) {
893                 CGroupDeviceAllow *a;
894
895                 /* Changing the devices list of a populated cgroup
896                  * might result in EINVAL, hence ignore EINVAL
897                  * here. */
898
899                 if (c->device_allow || c->device_policy != CGROUP_AUTO)
900                         r = cg_set_attribute("devices", path, "devices.deny", "a");
901                 else
902                         r = cg_set_attribute("devices", path, "devices.allow", "a");
903                 if (r < 0)
904                         log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
905                                       "Failed to reset devices.list: %m");
906
907                 if (c->device_policy == CGROUP_CLOSED ||
908                     (c->device_policy == CGROUP_AUTO && c->device_allow)) {
909                         static const char auto_devices[] =
910                                 "/dev/null\0" "rwm\0"
911                                 "/dev/zero\0" "rwm\0"
912                                 "/dev/full\0" "rwm\0"
913                                 "/dev/random\0" "rwm\0"
914                                 "/dev/urandom\0" "rwm\0"
915                                 "/dev/tty\0" "rwm\0"
916                                 "/dev/pts/ptmx\0" "rw\0" /* /dev/pts/ptmx may not be duplicated, but accessed */
917                                 /* Allow /run/elogind/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
918                                 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
919                                 "/run/systemd/inaccessible/chr\0" "rwm\0"
920                                 "/run/systemd/inaccessible/blk\0" "rwm\0";
921
922                         const char *x, *y;
923
924                         NULSTR_FOREACH_PAIR(x, y, auto_devices)
925                                 whitelist_device(path, x, y);
926
927                         whitelist_major(path, "pts", 'c', "rw");
928                         whitelist_major(path, "kdbus", 'c', "rw");
929                         whitelist_major(path, "kdbus/*", 'c', "rw");
930                 }
931
932                 LIST_FOREACH(device_allow, a, c->device_allow) {
933                         char acc[4], *val;
934                         unsigned k = 0;
935
936                         if (a->r)
937                                 acc[k++] = 'r';
938                         if (a->w)
939                                 acc[k++] = 'w';
940                         if (a->m)
941                                 acc[k++] = 'm';
942
943                         if (k == 0)
944                                 continue;
945
946                         acc[k++] = 0;
947
948                         if (startswith(a->path, "/dev/"))
949                                 whitelist_device(path, a->path, acc);
950                         else if ((val = startswith(a->path, "block-")))
951                                 whitelist_major(path, val, 'b', acc);
952                         else if ((val = startswith(a->path, "char-")))
953                                 whitelist_major(path, val, 'c', acc);
954                         else
955                                 log_unit_debug(u, "Ignoring device %s while writing cgroup attribute.", a->path);
956                 }
957         }
958
959         if ((mask & CGROUP_MASK_PIDS) && !is_root) {
960
961                 if (c->tasks_max != CGROUP_LIMIT_MAX) {
962                         char buf[DECIMAL_STR_MAX(uint64_t) + 2];
963
964                         sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
965                         r = cg_set_attribute("pids", path, "pids.max", buf);
966                 } else
967                         r = cg_set_attribute("pids", path, "pids.max", "max");
968
969                 if (r < 0)
970                         log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
971                                       "Failed to set pids.max: %m");
972         }
973 }
974
975 CGroupMask cgroup_context_get_mask(CGroupContext *c) {
976         CGroupMask mask = 0;
977
978         /* Figure out which controllers we need */
979
980         if (c->cpu_accounting ||
981             cgroup_context_has_cpu_weight(c) ||
982             cgroup_context_has_cpu_shares(c) ||
983             c->cpu_quota_per_sec_usec != USEC_INFINITY)
984                 mask |= CGROUP_MASK_CPUACCT | CGROUP_MASK_CPU;
985
986         if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
987                 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
988
989         if (c->memory_accounting ||
990             c->memory_limit != CGROUP_LIMIT_MAX ||
991             cgroup_context_has_unified_memory_config(c))
992                 mask |= CGROUP_MASK_MEMORY;
993
994         if (c->device_allow ||
995             c->device_policy != CGROUP_AUTO)
996                 mask |= CGROUP_MASK_DEVICES;
997
998         if (c->tasks_accounting ||
999             c->tasks_max != (uint64_t) -1)
1000                 mask |= CGROUP_MASK_PIDS;
1001
1002         return mask;
1003 }
1004
1005 CGroupMask unit_get_own_mask(Unit *u) {
1006         CGroupContext *c;
1007
1008         /* Returns the mask of controllers the unit needs for itself */
1009
1010         c = unit_get_cgroup_context(u);
1011         if (!c)
1012                 return 0;
1013
1014         /* If delegation is turned on, then turn on all cgroups,
1015          * unless we are on the legacy hierarchy and the process we
1016          * fork into it is known to drop privileges, and hence
1017          * shouldn't get access to the controllers.
1018          *
1019          * Note that on the unified hierarchy it is safe to delegate
1020          * controllers to unprivileged services. */
1021
1022         if (c->delegate) {
1023                 ExecContext *e;
1024
1025                 e = unit_get_exec_context(u);
1026                 if (!e ||
1027                     exec_context_maintains_privileges(e) ||
1028                     cg_all_unified() > 0)
1029                         return _CGROUP_MASK_ALL;
1030         }
1031
1032         return cgroup_context_get_mask(c);
1033 }
1034
1035 CGroupMask unit_get_members_mask(Unit *u) {
1036         assert(u);
1037
1038         /* Returns the mask of controllers all of the unit's children
1039          * require, merged */
1040
1041         if (u->cgroup_members_mask_valid)
1042                 return u->cgroup_members_mask;
1043
1044         u->cgroup_members_mask = 0;
1045
1046         if (u->type == UNIT_SLICE) {
1047                 Unit *member;
1048                 Iterator i;
1049
1050                 SET_FOREACH(member, u->dependencies[UNIT_BEFORE], i) {
1051
1052                         if (member == u)
1053                                 continue;
1054
1055                         if (UNIT_DEREF(member->slice) != u)
1056                                 continue;
1057
1058                         u->cgroup_members_mask |=
1059                                 unit_get_own_mask(member) |
1060                                 unit_get_members_mask(member);
1061                 }
1062         }
1063
1064         u->cgroup_members_mask_valid = true;
1065         return u->cgroup_members_mask;
1066 }
1067
1068 CGroupMask unit_get_siblings_mask(Unit *u) {
1069         assert(u);
1070
1071         /* Returns the mask of controllers all of the unit's siblings
1072          * require, i.e. the members mask of the unit's parent slice
1073          * if there is one. */
1074
1075         if (UNIT_ISSET(u->slice))
1076                 return unit_get_members_mask(UNIT_DEREF(u->slice));
1077
1078         return unit_get_own_mask(u) | unit_get_members_mask(u);
1079 }
1080
1081 CGroupMask unit_get_subtree_mask(Unit *u) {
1082
1083         /* Returns the mask of this subtree, meaning of the group
1084          * itself and its children. */
1085
1086         return unit_get_own_mask(u) | unit_get_members_mask(u);
1087 }
1088
1089 CGroupMask unit_get_target_mask(Unit *u) {
1090         CGroupMask mask;
1091
1092         /* This returns the cgroup mask of all controllers to enable
1093          * for a specific cgroup, i.e. everything it needs itself,
1094          * plus all that its children need, plus all that its siblings
1095          * need. This is primarily useful on the legacy cgroup
1096          * hierarchy, where we need to duplicate each cgroup in each
1097          * hierarchy that shall be enabled for it. */
1098
1099         mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
1100         mask &= u->manager->cgroup_supported;
1101
1102         return mask;
1103 }
1104
1105 CGroupMask unit_get_enable_mask(Unit *u) {
1106         CGroupMask mask;
1107
1108         /* This returns the cgroup mask of all controllers to enable
1109          * for the children of a specific cgroup. This is primarily
1110          * useful for the unified cgroup hierarchy, where each cgroup
1111          * controls which controllers are enabled for its children. */
1112
1113         mask = unit_get_members_mask(u);
1114         mask &= u->manager->cgroup_supported;
1115
1116         return mask;
1117 }
1118
1119 /* Recurse from a unit up through its containing slices, propagating
1120  * mask bits upward. A unit is also member of itself. */
1121 void unit_update_cgroup_members_masks(Unit *u) {
1122         CGroupMask m;
1123         bool more;
1124
1125         assert(u);
1126
1127         /* Calculate subtree mask */
1128         m = unit_get_subtree_mask(u);
1129
1130         /* See if anything changed from the previous invocation. If
1131          * not, we're done. */
1132         if (u->cgroup_subtree_mask_valid && m == u->cgroup_subtree_mask)
1133                 return;
1134
1135         more =
1136                 u->cgroup_subtree_mask_valid &&
1137                 ((m & ~u->cgroup_subtree_mask) != 0) &&
1138                 ((~m & u->cgroup_subtree_mask) == 0);
1139
1140         u->cgroup_subtree_mask = m;
1141         u->cgroup_subtree_mask_valid = true;
1142
1143         if (UNIT_ISSET(u->slice)) {
1144                 Unit *s = UNIT_DEREF(u->slice);
1145
1146                 if (more)
1147                         /* There's more set now than before. We
1148                          * propagate the new mask to the parent's mask
1149                          * (not caring if it actually was valid or
1150                          * not). */
1151
1152                         s->cgroup_members_mask |= m;
1153
1154                 else
1155                         /* There's less set now than before (or we
1156                          * don't know), we need to recalculate
1157                          * everything, so let's invalidate the
1158                          * parent's members mask */
1159
1160                         s->cgroup_members_mask_valid = false;
1161
1162                 /* And now make sure that this change also hits our
1163                  * grandparents */
1164                 unit_update_cgroup_members_masks(s);
1165         }
1166 }
1167
1168 static const char *migrate_callback(CGroupMask mask, void *userdata) {
1169         Unit *u = userdata;
1170
1171         assert(mask != 0);
1172         assert(u);
1173
1174         while (u) {
1175                 if (u->cgroup_path &&
1176                     u->cgroup_realized &&
1177                     (u->cgroup_realized_mask & mask) == mask)
1178                         return u->cgroup_path;
1179
1180                 u = UNIT_DEREF(u->slice);
1181         }
1182
1183         return NULL;
1184 }
1185
1186 char *unit_default_cgroup_path(Unit *u) {
1187         _cleanup_free_ char *escaped = NULL, *slice = NULL;
1188         int r;
1189
1190         assert(u);
1191
1192         if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1193                 return strdup(u->manager->cgroup_root);
1194
1195         if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1196                 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1197                 if (r < 0)
1198                         return NULL;
1199         }
1200
1201         escaped = cg_escape(u->id);
1202         if (!escaped)
1203                 return NULL;
1204
1205         if (slice)
1206                 return strjoin(u->manager->cgroup_root, "/", slice, "/",
1207                                escaped);
1208         else
1209                 return strjoin(u->manager->cgroup_root, "/", escaped);
1210 }
1211
1212 int unit_set_cgroup_path(Unit *u, const char *path) {
1213         _cleanup_free_ char *p = NULL;
1214         int r;
1215
1216         assert(u);
1217
1218         if (path) {
1219                 p = strdup(path);
1220                 if (!p)
1221                         return -ENOMEM;
1222         } else
1223                 p = NULL;
1224
1225         if (streq_ptr(u->cgroup_path, p))
1226                 return 0;
1227
1228         if (p) {
1229                 r = hashmap_put(u->manager->cgroup_unit, p, u);
1230                 if (r < 0)
1231                         return r;
1232         }
1233
1234         unit_release_cgroup(u);
1235
1236         u->cgroup_path = p;
1237         p = NULL;
1238
1239         return 1;
1240 }
1241
1242 int unit_watch_cgroup(Unit *u) {
1243         _cleanup_free_ char *events = NULL;
1244         int r;
1245
1246         assert(u);
1247
1248         if (!u->cgroup_path)
1249                 return 0;
1250
1251         if (u->cgroup_inotify_wd >= 0)
1252                 return 0;
1253
1254         /* Only applies to the unified hierarchy */
1255         r = cg_unified(SYSTEMD_CGROUP_CONTROLLER);
1256         if (r < 0)
1257                 return log_unit_error_errno(u, r, "Failed detect whether the unified hierarchy is used: %m");
1258         if (r == 0)
1259                 return 0;
1260
1261         /* Don't watch the root slice, it's pointless. */
1262         if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1263                 return 0;
1264
1265         r = hashmap_ensure_allocated(&u->manager->cgroup_inotify_wd_unit, &trivial_hash_ops);
1266         if (r < 0)
1267                 return log_oom();
1268
1269         r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1270         if (r < 0)
1271                 return log_oom();
1272
1273         u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1274         if (u->cgroup_inotify_wd < 0) {
1275
1276                 if (errno == ENOENT) /* If the directory is already
1277                                       * gone we don't need to track
1278                                       * it, so this is not an error */
1279                         return 0;
1280
1281                 return log_unit_error_errno(u, errno, "Failed to add inotify watch descriptor for control group %s: %m", u->cgroup_path);
1282         }
1283
1284         r = hashmap_put(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd), u);
1285         if (r < 0)
1286                 return log_unit_error_errno(u, r, "Failed to add inotify watch descriptor to hash map: %m");
1287
1288         return 0;
1289 }
1290
1291 static int unit_create_cgroup(
1292                 Unit *u,
1293                 CGroupMask target_mask,
1294                 CGroupMask enable_mask) {
1295
1296         CGroupContext *c;
1297         int r;
1298
1299         assert(u);
1300
1301         c = unit_get_cgroup_context(u);
1302         if (!c)
1303                 return 0;
1304
1305         if (!u->cgroup_path) {
1306                 _cleanup_free_ char *path = NULL;
1307
1308                 path = unit_default_cgroup_path(u);
1309                 if (!path)
1310                         return log_oom();
1311
1312                 r = unit_set_cgroup_path(u, path);
1313                 if (r == -EEXIST)
1314                         return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1315                 if (r < 0)
1316                         return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1317         }
1318
1319         /* First, create our own group */
1320         r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1321         if (r < 0)
1322                 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1323
1324         /* Start watching it */
1325         (void) unit_watch_cgroup(u);
1326
1327         /* Enable all controllers we need */
1328         r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path);
1329         if (r < 0)
1330                 log_unit_warning_errno(u, r, "Failed to enable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
1331
1332         /* Keep track that this is now realized */
1333         u->cgroup_realized = true;
1334         u->cgroup_realized_mask = target_mask;
1335         u->cgroup_enabled_mask = enable_mask;
1336
1337         if (u->type != UNIT_SLICE && !c->delegate) {
1338
1339                 /* Then, possibly move things over, but not if
1340                  * subgroups may contain processes, which is the case
1341                  * for slice and delegation units. */
1342                 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1343                 if (r < 0)
1344                         log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
1345         }
1346
1347         return 0;
1348 }
1349
1350 int unit_attach_pids_to_cgroup(Unit *u) {
1351         int r;
1352         assert(u);
1353
1354         r = unit_realize_cgroup(u);
1355         if (r < 0)
1356                 return r;
1357
1358         r = cg_attach_many_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->pids, migrate_callback, u);
1359         if (r < 0)
1360                 return r;
1361
1362         return 0;
1363 }
1364
1365 static void cgroup_xattr_apply(Unit *u) {
1366         char ids[SD_ID128_STRING_MAX];
1367         int r;
1368
1369         assert(u);
1370
1371         if (!MANAGER_IS_SYSTEM(u->manager))
1372                 return;
1373
1374         if (sd_id128_is_null(u->invocation_id))
1375                 return;
1376
1377         r = cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
1378                          "trusted.invocation_id",
1379                          sd_id128_to_string(u->invocation_id, ids), 32,
1380                          0);
1381         if (r < 0)
1382                 log_unit_warning_errno(u, r, "Failed to set invocation ID on control group %s, ignoring: %m", u->cgroup_path);
1383 }
1384
1385 static bool unit_has_mask_realized(Unit *u, CGroupMask target_mask, CGroupMask enable_mask) {
1386         assert(u);
1387
1388         return u->cgroup_realized && u->cgroup_realized_mask == target_mask && u->cgroup_enabled_mask == enable_mask;
1389 }
1390
1391 /* Check if necessary controllers and attributes for a unit are in place.
1392  *
1393  * If so, do nothing.
1394  * If not, create paths, move processes over, and set attributes.
1395  *
1396  * Returns 0 on success and < 0 on failure. */
1397 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
1398         CGroupMask target_mask, enable_mask;
1399         int r;
1400
1401         assert(u);
1402
1403         if (u->in_cgroup_queue) {
1404                 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
1405                 u->in_cgroup_queue = false;
1406         }
1407
1408         target_mask = unit_get_target_mask(u);
1409         enable_mask = unit_get_enable_mask(u);
1410
1411         if (unit_has_mask_realized(u, target_mask, enable_mask))
1412                 return 0;
1413
1414         /* First, realize parents */
1415         if (UNIT_ISSET(u->slice)) {
1416                 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
1417                 if (r < 0)
1418                         return r;
1419         }
1420
1421         /* And then do the real work */
1422         r = unit_create_cgroup(u, target_mask, enable_mask);
1423         if (r < 0)
1424                 return r;
1425
1426         /* Finally, apply the necessary attributes. */
1427         cgroup_context_apply(u, target_mask, state);
1428         cgroup_xattr_apply(u);
1429
1430         return 0;
1431 }
1432
1433 static void unit_add_to_cgroup_queue(Unit *u) {
1434
1435         if (u->in_cgroup_queue)
1436                 return;
1437
1438         LIST_PREPEND(cgroup_queue, u->manager->cgroup_queue, u);
1439         u->in_cgroup_queue = true;
1440 }
1441
1442 unsigned manager_dispatch_cgroup_queue(Manager *m) {
1443         ManagerState state;
1444         unsigned n = 0;
1445         Unit *i;
1446         int r;
1447
1448         state = manager_state(m);
1449
1450         while ((i = m->cgroup_queue)) {
1451                 assert(i->in_cgroup_queue);
1452
1453                 r = unit_realize_cgroup_now(i, state);
1454                 if (r < 0)
1455                         log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
1456
1457                 n++;
1458         }
1459
1460         return n;
1461 }
1462
1463 static void unit_queue_siblings(Unit *u) {
1464         Unit *slice;
1465
1466         /* This adds the siblings of the specified unit and the
1467          * siblings of all parent units to the cgroup queue. (But
1468          * neither the specified unit itself nor the parents.) */
1469
1470         while ((slice = UNIT_DEREF(u->slice))) {
1471                 Iterator i;
1472                 Unit *m;
1473
1474                 SET_FOREACH(m, slice->dependencies[UNIT_BEFORE], i) {
1475                         if (m == u)
1476                                 continue;
1477
1478                         /* Skip units that have a dependency on the slice
1479                          * but aren't actually in it. */
1480                         if (UNIT_DEREF(m->slice) != slice)
1481                                 continue;
1482
1483                         /* No point in doing cgroup application for units
1484                          * without active processes. */
1485                         if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
1486                                 continue;
1487
1488                         /* If the unit doesn't need any new controllers
1489                          * and has current ones realized, it doesn't need
1490                          * any changes. */
1491                         if (unit_has_mask_realized(m, unit_get_target_mask(m), unit_get_enable_mask(m)))
1492                                 continue;
1493
1494                         unit_add_to_cgroup_queue(m);
1495                 }
1496
1497                 u = slice;
1498         }
1499 }
1500
1501 int unit_realize_cgroup(Unit *u) {
1502         assert(u);
1503
1504         if (!UNIT_HAS_CGROUP_CONTEXT(u))
1505                 return 0;
1506
1507         /* So, here's the deal: when realizing the cgroups for this
1508          * unit, we need to first create all parents, but there's more
1509          * actually: for the weight-based controllers we also need to
1510          * make sure that all our siblings (i.e. units that are in the
1511          * same slice as we are) have cgroups, too. Otherwise, things
1512          * would become very uneven as each of their processes would
1513          * get as much resources as all our group together. This call
1514          * will synchronously create the parent cgroups, but will
1515          * defer work on the siblings to the next event loop
1516          * iteration. */
1517
1518         /* Add all sibling slices to the cgroup queue. */
1519         unit_queue_siblings(u);
1520
1521         /* And realize this one now (and apply the values) */
1522         return unit_realize_cgroup_now(u, manager_state(u->manager));
1523 }
1524
1525 void unit_release_cgroup(Unit *u) {
1526         assert(u);
1527
1528         /* Forgets all cgroup details for this cgroup */
1529
1530         if (u->cgroup_path) {
1531                 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1532                 u->cgroup_path = mfree(u->cgroup_path);
1533         }
1534
1535         if (u->cgroup_inotify_wd >= 0) {
1536                 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1537                         log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1538
1539                 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1540                 u->cgroup_inotify_wd = -1;
1541         }
1542 }
1543
1544 void unit_prune_cgroup(Unit *u) {
1545         int r;
1546         bool is_root_slice;
1547
1548         assert(u);
1549
1550         /* Removes the cgroup, if empty and possible, and stops watching it. */
1551
1552         if (!u->cgroup_path)
1553                 return;
1554
1555         (void) unit_get_cpu_usage(u, NULL); /* Cache the last CPU usage value before we destroy the cgroup */
1556
1557         is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1558
1559         r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
1560         if (r < 0) {
1561                 log_unit_debug_errno(u, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
1562                 return;
1563         }
1564
1565         if (is_root_slice)
1566                 return;
1567
1568         unit_release_cgroup(u);
1569
1570         u->cgroup_realized = false;
1571         u->cgroup_realized_mask = 0;
1572         u->cgroup_enabled_mask = 0;
1573 }
1574
1575 int unit_search_main_pid(Unit *u, pid_t *ret) {
1576         _cleanup_fclose_ FILE *f = NULL;
1577         pid_t pid = 0, npid, mypid;
1578         int r;
1579
1580         assert(u);
1581         assert(ret);
1582
1583         if (!u->cgroup_path)
1584                 return -ENXIO;
1585
1586         r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1587         if (r < 0)
1588                 return r;
1589
1590         mypid = getpid();
1591         while (cg_read_pid(f, &npid) > 0)  {
1592                 pid_t ppid;
1593
1594                 if (npid == pid)
1595                         continue;
1596
1597                 /* Ignore processes that aren't our kids */
1598                 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
1599                         continue;
1600
1601                 if (pid != 0)
1602                         /* Dang, there's more than one daemonized PID
1603                         in this group, so we don't know what process
1604                         is the main process. */
1605
1606                         return -ENODATA;
1607
1608                 pid = npid;
1609         }
1610
1611         *ret = pid;
1612         return 0;
1613 }
1614
1615 static int unit_watch_pids_in_path(Unit *u, const char *path) {
1616         _cleanup_closedir_ DIR *d = NULL;
1617         _cleanup_fclose_ FILE *f = NULL;
1618         int ret = 0, r;
1619
1620         assert(u);
1621         assert(path);
1622
1623         r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1624         if (r < 0)
1625                 ret = r;
1626         else {
1627                 pid_t pid;
1628
1629                 while ((r = cg_read_pid(f, &pid)) > 0) {
1630                         r = unit_watch_pid(u, pid);
1631                         if (r < 0 && ret >= 0)
1632                                 ret = r;
1633                 }
1634
1635                 if (r < 0 && ret >= 0)
1636                         ret = r;
1637         }
1638
1639         r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1640         if (r < 0) {
1641                 if (ret >= 0)
1642                         ret = r;
1643         } else {
1644                 char *fn;
1645
1646                 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1647                         _cleanup_free_ char *p = NULL;
1648
1649                         p = strjoin(path, "/", fn);
1650                         free(fn);
1651
1652                         if (!p)
1653                                 return -ENOMEM;
1654
1655                         r = unit_watch_pids_in_path(u, p);
1656                         if (r < 0 && ret >= 0)
1657                                 ret = r;
1658                 }
1659
1660                 if (r < 0 && ret >= 0)
1661                         ret = r;
1662         }
1663
1664         return ret;
1665 }
1666
1667 int unit_watch_all_pids(Unit *u) {
1668         assert(u);
1669
1670         /* Adds all PIDs from our cgroup to the set of PIDs we
1671          * watch. This is a fallback logic for cases where we do not
1672          * get reliable cgroup empty notifications: we try to use
1673          * SIGCHLD as replacement. */
1674
1675         if (!u->cgroup_path)
1676                 return -ENOENT;
1677
1678         if (cg_unified(SYSTEMD_CGROUP_CONTROLLER) > 0) /* On unified we can use proper notifications */
1679                 return 0;
1680
1681         return unit_watch_pids_in_path(u, u->cgroup_path);
1682 }
1683
1684 int unit_notify_cgroup_empty(Unit *u) {
1685         int r;
1686
1687         assert(u);
1688
1689         if (!u->cgroup_path)
1690                 return 0;
1691
1692         r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
1693         if (r <= 0)
1694                 return r;
1695
1696         unit_add_to_gc_queue(u);
1697
1698         if (UNIT_VTABLE(u)->notify_cgroup_empty)
1699                 UNIT_VTABLE(u)->notify_cgroup_empty(u);
1700
1701         return 0;
1702 }
1703
1704 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1705         Manager *m = userdata;
1706
1707         assert(s);
1708         assert(fd >= 0);
1709         assert(m);
1710
1711         for (;;) {
1712                 union inotify_event_buffer buffer;
1713                 struct inotify_event *e;
1714                 ssize_t l;
1715
1716                 l = read(fd, &buffer, sizeof(buffer));
1717                 if (l < 0) {
1718                         if (errno == EINTR || errno == EAGAIN)
1719                                 return 0;
1720
1721                         return log_error_errno(errno, "Failed to read control group inotify events: %m");
1722                 }
1723
1724                 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1725                         Unit *u;
1726
1727                         if (e->wd < 0)
1728                                 /* Queue overflow has no watch descriptor */
1729                                 continue;
1730
1731                         if (e->mask & IN_IGNORED)
1732                                 /* The watch was just removed */
1733                                 continue;
1734
1735                         u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
1736                         if (!u) /* Not that inotify might deliver
1737                                  * events for a watch even after it
1738                                  * was removed, because it was queued
1739                                  * before the removal. Let's ignore
1740                                  * this here safely. */
1741                                 continue;
1742
1743                         (void) unit_notify_cgroup_empty(u);
1744                 }
1745         }
1746 }
1747 #endif // 0
1748
1749 int manager_setup_cgroup(Manager *m) {
1750         _cleanup_free_ char *path = NULL;
1751         CGroupController c;
1752         int r, all_unified, systemd_unified;
1753         char *e;
1754
1755         assert(m);
1756
1757         /* 1. Determine hierarchy */
1758         m->cgroup_root = mfree(m->cgroup_root);
1759         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
1760         if (r < 0)
1761                 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
1762
1763 #if 0 /// elogind does not support systemd scopes and slices
1764         /* Chop off the init scope, if we are already located in it */
1765         e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1766
1767         /* LEGACY: Also chop off the system slice if we are in
1768          * it. This is to support live upgrades from older systemd
1769          * versions where PID 1 was moved there. Also see
1770          * cg_get_root_path(). */
1771         if (!e && MANAGER_IS_SYSTEM(m)) {
1772                 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
1773                 if (!e)
1774                         e = endswith(m->cgroup_root, "/system"); /* even more legacy */
1775         }
1776         if (e)
1777                 *e = 0;
1778 #endif // 0
1779
1780         /* And make sure to store away the root value without trailing
1781          * slash, even for the root dir, so that we can easily prepend
1782          * it everywhere. */
1783         while ((e = endswith(m->cgroup_root, "/")))
1784                 *e = 0;
1785         log_debug_elogind("Cgroup Controller \"%s\" -> root \"%s\"",
1786                           SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root);
1787
1788         /* 2. Show data */
1789         r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
1790         if (r < 0)
1791                 return log_error_errno(r, "Cannot find cgroup mount point: %m");
1792
1793         all_unified = cg_all_unified();
1794         systemd_unified = cg_unified(SYSTEMD_CGROUP_CONTROLLER);
1795
1796         if (all_unified < 0 || systemd_unified < 0)
1797                 return log_error_errno(all_unified < 0 ? all_unified : systemd_unified,
1798                                        "Couldn't determine if we are running in the unified hierarchy: %m");
1799
1800         if (all_unified > 0)
1801                 log_debug("Unified cgroup hierarchy is located at %s.", path);
1802         else if (systemd_unified > 0)
1803                 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path);
1804         else
1805                 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER ". File system hierarchy is at %s.", path);
1806
1807         if (!m->test_run) {
1808                 const char *scope_path;
1809
1810                 /* 3. Install agent */
1811                 if (systemd_unified) {
1812
1813                         /* In the unified hierarchy we can get
1814                          * cgroup empty notifications via inotify. */
1815
1816 #if 0 /// elogind does not support the unified hierarchy, yet.
1817                         m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1818                         safe_close(m->cgroup_inotify_fd);
1819
1820                         m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1821                         if (m->cgroup_inotify_fd < 0)
1822                                 return log_error_errno(errno, "Failed to create control group inotify object: %m");
1823
1824                         r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
1825                         if (r < 0)
1826                                 return log_error_errno(r, "Failed to watch control group inotify object: %m");
1827
1828                         /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
1829                          * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
1830                         r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-5);
1831                         if (r < 0)
1832                                 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
1833
1834                         (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
1835
1836 #else
1837                         return log_error_errno(EOPNOTSUPP, "Unified cgroup hierarchy not supported: %m");
1838 #endif // 0
1839                 } else if (MANAGER_IS_SYSTEM(m)) {
1840
1841                         /* On the legacy hierarchy we only get
1842                          * notifications via cgroup agents. (Which
1843                          * isn't really reliable, since it does not
1844                          * generate events when control groups with
1845                          * children run empty. */
1846
1847                         r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
1848                         if (r < 0)
1849                                 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
1850                         else if (r > 0)
1851                                 log_debug("Installed release agent.");
1852                         else if (r == 0)
1853                                 log_debug("Release agent already installed.");
1854                 }
1855
1856 #if 0 /// elogind is not meant to run in systemd init scope
1857                 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1858                 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1859                 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1860 #else
1861                 if (streq(SYSTEMD_CGROUP_CONTROLLER, "name=elogind"))
1862                         // we are our own cgroup controller
1863                         scope_path = strjoina("");
1864                 else if (streq(m->cgroup_root, "/elogind"))
1865                         // root already is our cgroup
1866                         scope_path = strjoina(m->cgroup_root);
1867                 else
1868                         // we have to create our own group
1869                         scope_path = strjoina(m->cgroup_root, "/elogind");
1870                 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1871 #endif // 0
1872                 if (r < 0)
1873                         return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
1874                 log_debug_elogind("Created control group \"%s\"", scope_path);
1875
1876                 /* also, move all other userspace processes remaining
1877                  * in the root cgroup into that scope. */
1878                 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1879                 if (r < 0)
1880                         log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
1881
1882                 /* 5. And pin it, so that it cannot be unmounted */
1883                 safe_close(m->pin_cgroupfs_fd);
1884                 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
1885                 if (m->pin_cgroupfs_fd < 0)
1886                         return log_error_errno(errno, "Failed to open pin file: %m");
1887
1888                 /* 6.  Always enable hierarchical support if it exists... */
1889                 if (!all_unified)
1890                         (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
1891         }
1892
1893         /* 7. Figure out which controllers are supported */
1894         r = cg_mask_supported(&m->cgroup_supported);
1895         if (r < 0)
1896                 return log_error_errno(r, "Failed to determine supported controllers: %m");
1897
1898         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
1899                 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
1900
1901         return 0;
1902 }
1903
1904 void manager_shutdown_cgroup(Manager *m, bool delete) {
1905         assert(m);
1906
1907         /* We can't really delete the group, since we are in it. But
1908          * let's trim it. */
1909         if (delete && m->cgroup_root)
1910                 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
1911
1912 #if 0 /// elogind does not support the unified hierarchy, yet.
1913         m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
1914
1915         m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1916         m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
1917 #endif // 0
1918
1919         m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
1920
1921         m->cgroup_root = mfree(m->cgroup_root);
1922 }
1923
1924 #if 0 /// UNNEEDED by elogind
1925 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
1926         char *p;
1927         Unit *u;
1928
1929         assert(m);
1930         assert(cgroup);
1931
1932         u = hashmap_get(m->cgroup_unit, cgroup);
1933         if (u)
1934                 return u;
1935
1936         p = strdupa(cgroup);
1937         for (;;) {
1938                 char *e;
1939
1940                 e = strrchr(p, '/');
1941                 if (!e || e == p)
1942                         return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
1943
1944                 *e = 0;
1945
1946                 u = hashmap_get(m->cgroup_unit, p);
1947                 if (u)
1948                         return u;
1949         }
1950 }
1951
1952 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
1953         _cleanup_free_ char *cgroup = NULL;
1954         int r;
1955
1956         assert(m);
1957
1958         if (pid <= 0)
1959                 return NULL;
1960
1961         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
1962         if (r < 0)
1963                 return NULL;
1964
1965         return manager_get_unit_by_cgroup(m, cgroup);
1966 }
1967
1968 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
1969         Unit *u;
1970
1971         assert(m);
1972
1973         if (pid <= 0)
1974                 return NULL;
1975
1976         if (pid == 1)
1977                 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
1978
1979         u = hashmap_get(m->watch_pids1, PID_TO_PTR(pid));
1980         if (u)
1981                 return u;
1982
1983         u = hashmap_get(m->watch_pids2, PID_TO_PTR(pid));
1984         if (u)
1985                 return u;
1986
1987         return manager_get_unit_by_pid_cgroup(m, pid);
1988 }
1989 #endif // 0
1990
1991 #if 0 /// elogind must substitute this with its own variant
1992 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
1993         Unit *u;
1994
1995         assert(m);
1996         assert(cgroup);
1997
1998         log_debug("Got cgroup empty notification for: %s", cgroup);
1999
2000         u = manager_get_unit_by_cgroup(m, cgroup);
2001         if (!u)
2002                 return 0;
2003
2004         return unit_notify_cgroup_empty(u);
2005 }
2006 #else
2007 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
2008         Session *s;
2009
2010         assert(m);
2011         assert(cgroup);
2012
2013         log_debug("Got cgroup empty notification for: %s", cgroup);
2014
2015         s = hashmap_get(m->sessions, cgroup);
2016
2017         if (s) {
2018                 session_finalize(s);
2019                 session_free(s);
2020         } else
2021                 log_warning("Session not found: %s", cgroup);
2022
2023         return 0;
2024 }
2025 #endif // 0
2026 #if 0 /// UNNEEDED by elogind
2027 int unit_get_memory_current(Unit *u, uint64_t *ret) {
2028         _cleanup_free_ char *v = NULL;
2029         int r;
2030
2031         assert(u);
2032         assert(ret);
2033
2034         if (!u->cgroup_path)
2035                 return -ENODATA;
2036
2037         if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
2038                 return -ENODATA;
2039
2040         if (cg_all_unified() <= 0)
2041                 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
2042         else
2043                 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
2044         if (r == -ENOENT)
2045                 return -ENODATA;
2046         if (r < 0)
2047                 return r;
2048
2049         return safe_atou64(v, ret);
2050 }
2051
2052 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
2053         _cleanup_free_ char *v = NULL;
2054         int r;
2055
2056         assert(u);
2057         assert(ret);
2058
2059         if (!u->cgroup_path)
2060                 return -ENODATA;
2061
2062         if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
2063                 return -ENODATA;
2064
2065         r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
2066         if (r == -ENOENT)
2067                 return -ENODATA;
2068         if (r < 0)
2069                 return r;
2070
2071         return safe_atou64(v, ret);
2072 }
2073
2074 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
2075         _cleanup_free_ char *v = NULL;
2076         uint64_t ns;
2077         int r;
2078
2079         assert(u);
2080         assert(ret);
2081
2082         if (!u->cgroup_path)
2083                 return -ENODATA;
2084
2085         if (cg_all_unified() > 0) {
2086                 const char *keys[] = { "usage_usec", NULL };
2087                 _cleanup_free_ char *val = NULL;
2088                 uint64_t us;
2089
2090                 if ((u->cgroup_realized_mask & CGROUP_MASK_CPU) == 0)
2091                         return -ENODATA;
2092
2093                 r = cg_get_keyed_attribute("cpu", u->cgroup_path, "cpu.stat", keys, &val);
2094                 if (r < 0)
2095                         return r;
2096
2097                 r = safe_atou64(val, &us);
2098                 if (r < 0)
2099                         return r;
2100
2101                 ns = us * NSEC_PER_USEC;
2102         } else {
2103                 if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
2104                         return -ENODATA;
2105
2106                 r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
2107                 if (r == -ENOENT)
2108                         return -ENODATA;
2109                 if (r < 0)
2110                         return r;
2111
2112                 r = safe_atou64(v, &ns);
2113                 if (r < 0)
2114                         return r;
2115         }
2116
2117         *ret = ns;
2118         return 0;
2119 }
2120
2121 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
2122         nsec_t ns;
2123         int r;
2124
2125         assert(u);
2126
2127         /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2128          * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2129          * call this function with a NULL return value. */
2130
2131         r = unit_get_cpu_usage_raw(u, &ns);
2132         if (r == -ENODATA && u->cpu_usage_last != NSEC_INFINITY) {
2133                 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2134                  * cached value. */
2135
2136                 if (ret)
2137                         *ret = u->cpu_usage_last;
2138                 return 0;
2139         }
2140         if (r < 0)
2141                 return r;
2142
2143         if (ns > u->cpu_usage_base)
2144                 ns -= u->cpu_usage_base;
2145         else
2146                 ns = 0;
2147
2148         u->cpu_usage_last = ns;
2149         if (ret)
2150                 *ret = ns;
2151
2152         return 0;
2153 }
2154
2155 int unit_reset_cpu_usage(Unit *u) {
2156         nsec_t ns;
2157         int r;
2158
2159         assert(u);
2160
2161         u->cpu_usage_last = NSEC_INFINITY;
2162
2163         r = unit_get_cpu_usage_raw(u, &ns);
2164         if (r < 0) {
2165                 u->cpu_usage_base = 0;
2166                 return r;
2167         }
2168
2169         u->cpu_usage_base = ns;
2170         return 0;
2171 }
2172
2173 bool unit_cgroup_delegate(Unit *u) {
2174         CGroupContext *c;
2175
2176         assert(u);
2177
2178         c = unit_get_cgroup_context(u);
2179         if (!c)
2180                 return false;
2181
2182         return c->delegate;
2183 }
2184
2185 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
2186         assert(u);
2187
2188         if (!UNIT_HAS_CGROUP_CONTEXT(u))
2189                 return;
2190
2191         if (m == 0)
2192                 return;
2193
2194         /* always invalidate compat pairs together */
2195         if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
2196                 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
2197
2198         if ((u->cgroup_realized_mask & m) == 0)
2199                 return;
2200
2201         u->cgroup_realized_mask &= ~m;
2202         unit_add_to_cgroup_queue(u);
2203 }
2204
2205 void manager_invalidate_startup_units(Manager *m) {
2206         Iterator i;
2207         Unit *u;
2208
2209         assert(m);
2210
2211         SET_FOREACH(u, m->startup_units, i)
2212                 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
2213 }
2214
2215 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
2216         [CGROUP_AUTO] = "auto",
2217         [CGROUP_CLOSED] = "closed",
2218         [CGROUP_STRICT] = "strict",
2219 };
2220
2221 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);
2222 #endif // 0