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