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