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