chiark / gitweb /
core: remove duplicate includes (#3771)
[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(Unit *u, 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", u->cgroup_path, "io.weight", buf);
427         if (r < 0)
428                 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
429                               "Failed to set io.weight: %m");
430 }
431
432 static void cgroup_apply_blkio_device_weight(Unit *u, 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", u->cgroup_path, "blkio.weight_device", buf);
443         if (r < 0)
444                 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
445                               "Failed to set blkio.weight_device: %m");
446 }
447
448 static unsigned cgroup_apply_io_device_limit(Unit *u, 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", u->cgroup_path, "io.max", 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 io.max: %m");
476         return n;
477 }
478
479 static unsigned cgroup_apply_blkio_device_limit(Unit *u, 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", u->cgroup_path, "blkio.throttle.read_bps_device", buf);
493         if (r < 0)
494                 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
495                               "Failed to set blkio.throttle.read_bps_device: %m");
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", u->cgroup_path, "blkio.throttle.write_bps_device", buf);
501         if (r < 0)
502                 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
503                               "Failed to set blkio.throttle.write_bps_device: %m");
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(Unit *u, 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", u->cgroup_path, file, buf);
520         if (r < 0)
521                 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
522                               "Failed to set %s: %m", file);
523 }
524
525 static void cgroup_context_apply(Unit *u, CGroupMask mask, ManagerState state) {
526         const char *path;
527         CGroupContext *c;
528         bool is_root;
529         int r;
530
531         assert(u);
532
533         c = unit_get_cgroup_context(u);
534         path = u->cgroup_path;
535
536         assert(c);
537         assert(path);
538
539         if (mask == 0)
540                 return;
541
542         /* Some cgroup attributes are not supported on the root cgroup,
543          * hence silently ignore */
544         is_root = isempty(path) || path_equal(path, "/");
545         if (is_root)
546                 /* Make sure we don't try to display messages with an empty path. */
547                 path = "/";
548
549         /* We generally ignore errors caused by read-only mounted
550          * cgroup trees (assuming we are running in a container then),
551          * and missing cgroups, i.e. EROFS and ENOENT. */
552
553         if ((mask & CGROUP_MASK_CPU) && !is_root) {
554                 char buf[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t)) + 1];
555
556                 sprintf(buf, "%" PRIu64 "\n",
557                         IN_SET(state, MANAGER_STARTING, MANAGER_INITIALIZING) && c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID ? c->startup_cpu_shares :
558                         c->cpu_shares != CGROUP_CPU_SHARES_INVALID ? c->cpu_shares : CGROUP_CPU_SHARES_DEFAULT);
559                 r = cg_set_attribute("cpu", path, "cpu.shares", buf);
560                 if (r < 0)
561                         log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
562                                       "Failed to set cpu.shares: %m");
563
564                 sprintf(buf, USEC_FMT "\n", CGROUP_CPU_QUOTA_PERIOD_USEC);
565                 r = cg_set_attribute("cpu", path, "cpu.cfs_period_us", buf);
566                 if (r < 0)
567                         log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
568                                       "Failed to set cpu.cfs_period_us: %m");
569
570                 if (c->cpu_quota_per_sec_usec != USEC_INFINITY) {
571                         sprintf(buf, USEC_FMT "\n", c->cpu_quota_per_sec_usec * CGROUP_CPU_QUOTA_PERIOD_USEC / USEC_PER_SEC);
572                         r = cg_set_attribute("cpu", path, "cpu.cfs_quota_us", buf);
573                 } else
574                         r = cg_set_attribute("cpu", path, "cpu.cfs_quota_us", "-1");
575                 if (r < 0)
576                         log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
577                                       "Failed to set cpu.cfs_quota_us: %m");
578         }
579
580         if (mask & CGROUP_MASK_IO) {
581                 bool has_io = cgroup_context_has_io_config(c);
582                 bool has_blockio = cgroup_context_has_blockio_config(c);
583
584                 if (!is_root) {
585                         char buf[8+DECIMAL_STR_MAX(uint64_t)+1];
586                         uint64_t weight;
587
588                         if (has_io)
589                                 weight = cgroup_context_io_weight(c, state);
590                         else if (has_blockio)
591                                 weight = cgroup_weight_blkio_to_io(cgroup_context_blkio_weight(c, state));
592                         else
593                                 weight = CGROUP_WEIGHT_DEFAULT;
594
595                         xsprintf(buf, "default %" PRIu64 "\n", weight);
596                         r = cg_set_attribute("io", path, "io.weight", buf);
597                         if (r < 0)
598                                 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
599                                               "Failed to set io.weight: %m");
600
601                         if (has_io) {
602                                 CGroupIODeviceWeight *w;
603
604                                 /* FIXME: no way to reset this list */
605                                 LIST_FOREACH(device_weights, w, c->io_device_weights)
606                                         cgroup_apply_io_device_weight(u, w->path, w->weight);
607                         } else if (has_blockio) {
608                                 CGroupBlockIODeviceWeight *w;
609
610                                 /* FIXME: no way to reset this list */
611                                 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
612                                         cgroup_apply_io_device_weight(u, w->path, cgroup_weight_blkio_to_io(w->weight));
613                         }
614                 }
615
616                 /* Apply limits and free ones without config. */
617                 if (has_io) {
618                         CGroupIODeviceLimit *l, *next;
619
620                         LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
621                                 if (!cgroup_apply_io_device_limit(u, l->path, l->limits))
622                                         cgroup_context_free_io_device_limit(c, l);
623                         }
624                 } else if (has_blockio) {
625                         CGroupBlockIODeviceBandwidth *b, *next;
626
627                         LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths) {
628                                 uint64_t limits[_CGROUP_IO_LIMIT_TYPE_MAX];
629                                 CGroupIOLimitType type;
630
631                                 for (type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
632                                         limits[type] = cgroup_io_limit_defaults[type];
633
634                                 limits[CGROUP_IO_RBPS_MAX] = b->rbps;
635                                 limits[CGROUP_IO_WBPS_MAX] = b->wbps;
636
637                                 if (!cgroup_apply_io_device_limit(u, b->path, limits))
638                                         cgroup_context_free_blockio_device_bandwidth(c, b);
639                         }
640                 }
641         }
642
643         if (mask & CGROUP_MASK_BLKIO) {
644                 bool has_io = cgroup_context_has_io_config(c);
645                 bool has_blockio = cgroup_context_has_blockio_config(c);
646
647                 if (!is_root) {
648                         char buf[DECIMAL_STR_MAX(uint64_t)+1];
649                         uint64_t weight;
650
651                         if (has_blockio)
652                                 weight = cgroup_context_blkio_weight(c, state);
653                         else if (has_io)
654                                 weight = cgroup_weight_io_to_blkio(cgroup_context_io_weight(c, state));
655                         else
656                                 weight = CGROUP_BLKIO_WEIGHT_DEFAULT;
657
658                         xsprintf(buf, "%" PRIu64 "\n", weight);
659                         r = cg_set_attribute("blkio", path, "blkio.weight", buf);
660                         if (r < 0)
661                                 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
662                                               "Failed to set blkio.weight: %m");
663
664                         if (has_blockio) {
665                                 CGroupBlockIODeviceWeight *w;
666
667                                 /* FIXME: no way to reset this list */
668                                 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
669                                         cgroup_apply_blkio_device_weight(u, w->path, w->weight);
670                         } else if (has_io) {
671                                 CGroupIODeviceWeight *w;
672
673                                 /* FIXME: no way to reset this list */
674                                 LIST_FOREACH(device_weights, w, c->io_device_weights)
675                                         cgroup_apply_blkio_device_weight(u, w->path, cgroup_weight_io_to_blkio(w->weight));
676                         }
677                 }
678
679                 /* Apply limits and free ones without config. */
680                 if (has_blockio) {
681                         CGroupBlockIODeviceBandwidth *b, *next;
682
683                         LIST_FOREACH_SAFE(device_bandwidths, b, next, c->blockio_device_bandwidths) {
684                                 if (!cgroup_apply_blkio_device_limit(u, b->path, b->rbps, b->wbps))
685                                         cgroup_context_free_blockio_device_bandwidth(c, b);
686                         }
687                 } else if (has_io) {
688                         CGroupIODeviceLimit *l, *next;
689
690                         LIST_FOREACH_SAFE(device_limits, l, next, c->io_device_limits) {
691                                 if (!cgroup_apply_blkio_device_limit(u, l->path, l->limits[CGROUP_IO_RBPS_MAX], l->limits[CGROUP_IO_WBPS_MAX]))
692                                         cgroup_context_free_io_device_limit(c, l);
693                         }
694                 }
695         }
696
697         if ((mask & CGROUP_MASK_MEMORY) && !is_root) {
698                 if (cg_unified() > 0) {
699                         uint64_t max = c->memory_max;
700
701                         if (cgroup_context_has_unified_memory_config(c))
702                                 max = c->memory_max;
703                         else
704                                 max = c->memory_limit;
705
706                         cgroup_apply_unified_memory_limit(u, "memory.low", c->memory_low);
707                         cgroup_apply_unified_memory_limit(u, "memory.high", c->memory_high);
708                         cgroup_apply_unified_memory_limit(u, "memory.max", max);
709                 } else {
710                         char buf[DECIMAL_STR_MAX(uint64_t) + 1];
711
712                         if (c->memory_limit != CGROUP_LIMIT_MAX)
713                                 xsprintf(buf, "%" PRIu64 "\n", c->memory_limit);
714                         else
715                                 xsprintf(buf, "%" PRIu64 "\n", c->memory_max);
716
717                         r = cg_set_attribute("memory", path, "memory.limit_in_bytes", buf);
718                         if (r < 0)
719                                 log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
720                                               "Failed to set memory.limit_in_bytes: %m");
721                 }
722         }
723
724         if ((mask & CGROUP_MASK_DEVICES) && !is_root) {
725                 CGroupDeviceAllow *a;
726
727                 /* Changing the devices list of a populated cgroup
728                  * might result in EINVAL, hence ignore EINVAL
729                  * here. */
730
731                 if (c->device_allow || c->device_policy != CGROUP_AUTO)
732                         r = cg_set_attribute("devices", path, "devices.deny", "a");
733                 else
734                         r = cg_set_attribute("devices", path, "devices.allow", "a");
735                 if (r < 0)
736                         log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EINVAL, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
737                                       "Failed to reset devices.list: %m");
738
739                 if (c->device_policy == CGROUP_CLOSED ||
740                     (c->device_policy == CGROUP_AUTO && c->device_allow)) {
741                         static const char auto_devices[] =
742                                 "/dev/null\0" "rwm\0"
743                                 "/dev/zero\0" "rwm\0"
744                                 "/dev/full\0" "rwm\0"
745                                 "/dev/random\0" "rwm\0"
746                                 "/dev/urandom\0" "rwm\0"
747                                 "/dev/tty\0" "rwm\0"
748                                 "/dev/pts/ptmx\0" "rw\0"; /* /dev/pts/ptmx may not be duplicated, but accessed */
749
750                         const char *x, *y;
751
752                         NULSTR_FOREACH_PAIR(x, y, auto_devices)
753                                 whitelist_device(path, x, y);
754
755                         whitelist_major(path, "pts", 'c', "rw");
756                         whitelist_major(path, "kdbus", 'c', "rw");
757                         whitelist_major(path, "kdbus/*", 'c', "rw");
758                 }
759
760                 LIST_FOREACH(device_allow, a, c->device_allow) {
761                         char acc[4];
762                         unsigned k = 0;
763
764                         if (a->r)
765                                 acc[k++] = 'r';
766                         if (a->w)
767                                 acc[k++] = 'w';
768                         if (a->m)
769                                 acc[k++] = 'm';
770
771                         if (k == 0)
772                                 continue;
773
774                         acc[k++] = 0;
775
776                         if (startswith(a->path, "/dev/"))
777                                 whitelist_device(path, a->path, acc);
778                         else if (startswith(a->path, "block-"))
779                                 whitelist_major(path, a->path + 6, 'b', acc);
780                         else if (startswith(a->path, "char-"))
781                                 whitelist_major(path, a->path + 5, 'c', acc);
782                         else
783                                 log_unit_debug(u, "Ignoring device %s while writing cgroup attribute.", a->path);
784                 }
785         }
786
787         if ((mask & CGROUP_MASK_PIDS) && !is_root) {
788
789                 if (c->tasks_max != (uint64_t) -1) {
790                         char buf[DECIMAL_STR_MAX(uint64_t) + 2];
791
792                         sprintf(buf, "%" PRIu64 "\n", c->tasks_max);
793                         r = cg_set_attribute("pids", path, "pids.max", buf);
794                 } else
795                         r = cg_set_attribute("pids", path, "pids.max", "max");
796
797                 if (r < 0)
798                         log_unit_full(u, IN_SET(r, -ENOENT, -EROFS, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
799                                       "Failed to set pids.max: %m");
800         }
801 }
802
803 CGroupMask cgroup_context_get_mask(CGroupContext *c) {
804         CGroupMask mask = 0;
805
806         /* Figure out which controllers we need */
807
808         if (c->cpu_accounting ||
809             c->cpu_shares != CGROUP_CPU_SHARES_INVALID ||
810             c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID ||
811             c->cpu_quota_per_sec_usec != USEC_INFINITY)
812                 mask |= CGROUP_MASK_CPUACCT | CGROUP_MASK_CPU;
813
814         if (cgroup_context_has_io_config(c) || cgroup_context_has_blockio_config(c))
815                 mask |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
816
817         if (c->memory_accounting ||
818             c->memory_limit != CGROUP_LIMIT_MAX ||
819             cgroup_context_has_unified_memory_config(c))
820                 mask |= CGROUP_MASK_MEMORY;
821
822         if (c->device_allow ||
823             c->device_policy != CGROUP_AUTO)
824                 mask |= CGROUP_MASK_DEVICES;
825
826         if (c->tasks_accounting ||
827             c->tasks_max != (uint64_t) -1)
828                 mask |= CGROUP_MASK_PIDS;
829
830         return mask;
831 }
832
833 CGroupMask unit_get_own_mask(Unit *u) {
834         CGroupContext *c;
835
836         /* Returns the mask of controllers the unit needs for itself */
837
838         c = unit_get_cgroup_context(u);
839         if (!c)
840                 return 0;
841
842         /* If delegation is turned on, then turn on all cgroups,
843          * unless we are on the legacy hierarchy and the process we
844          * fork into it is known to drop privileges, and hence
845          * shouldn't get access to the controllers.
846          *
847          * Note that on the unified hierarchy it is safe to delegate
848          * controllers to unprivileged services. */
849
850         if (c->delegate) {
851                 ExecContext *e;
852
853                 e = unit_get_exec_context(u);
854                 if (!e ||
855                     exec_context_maintains_privileges(e) ||
856                     cg_unified() > 0)
857                         return _CGROUP_MASK_ALL;
858         }
859
860         return cgroup_context_get_mask(c);
861 }
862
863 CGroupMask unit_get_members_mask(Unit *u) {
864         assert(u);
865
866         /* Returns the mask of controllers all of the unit's children
867          * require, merged */
868
869         if (u->cgroup_members_mask_valid)
870                 return u->cgroup_members_mask;
871
872         u->cgroup_members_mask = 0;
873
874         if (u->type == UNIT_SLICE) {
875                 Unit *member;
876                 Iterator i;
877
878                 SET_FOREACH(member, u->dependencies[UNIT_BEFORE], i) {
879
880                         if (member == u)
881                                 continue;
882
883                         if (UNIT_DEREF(member->slice) != u)
884                                 continue;
885
886                         u->cgroup_members_mask |=
887                                 unit_get_own_mask(member) |
888                                 unit_get_members_mask(member);
889                 }
890         }
891
892         u->cgroup_members_mask_valid = true;
893         return u->cgroup_members_mask;
894 }
895
896 CGroupMask unit_get_siblings_mask(Unit *u) {
897         assert(u);
898
899         /* Returns the mask of controllers all of the unit's siblings
900          * require, i.e. the members mask of the unit's parent slice
901          * if there is one. */
902
903         if (UNIT_ISSET(u->slice))
904                 return unit_get_members_mask(UNIT_DEREF(u->slice));
905
906         return unit_get_own_mask(u) | unit_get_members_mask(u);
907 }
908
909 CGroupMask unit_get_subtree_mask(Unit *u) {
910
911         /* Returns the mask of this subtree, meaning of the group
912          * itself and its children. */
913
914         return unit_get_own_mask(u) | unit_get_members_mask(u);
915 }
916
917 CGroupMask unit_get_target_mask(Unit *u) {
918         CGroupMask mask;
919
920         /* This returns the cgroup mask of all controllers to enable
921          * for a specific cgroup, i.e. everything it needs itself,
922          * plus all that its children need, plus all that its siblings
923          * need. This is primarily useful on the legacy cgroup
924          * hierarchy, where we need to duplicate each cgroup in each
925          * hierarchy that shall be enabled for it. */
926
927         mask = unit_get_own_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
928         mask &= u->manager->cgroup_supported;
929
930         return mask;
931 }
932
933 CGroupMask unit_get_enable_mask(Unit *u) {
934         CGroupMask mask;
935
936         /* This returns the cgroup mask of all controllers to enable
937          * for the children of a specific cgroup. This is primarily
938          * useful for the unified cgroup hierarchy, where each cgroup
939          * controls which controllers are enabled for its children. */
940
941         mask = unit_get_members_mask(u);
942         mask &= u->manager->cgroup_supported;
943
944         return mask;
945 }
946
947 /* Recurse from a unit up through its containing slices, propagating
948  * mask bits upward. A unit is also member of itself. */
949 void unit_update_cgroup_members_masks(Unit *u) {
950         CGroupMask m;
951         bool more;
952
953         assert(u);
954
955         /* Calculate subtree mask */
956         m = unit_get_subtree_mask(u);
957
958         /* See if anything changed from the previous invocation. If
959          * not, we're done. */
960         if (u->cgroup_subtree_mask_valid && m == u->cgroup_subtree_mask)
961                 return;
962
963         more =
964                 u->cgroup_subtree_mask_valid &&
965                 ((m & ~u->cgroup_subtree_mask) != 0) &&
966                 ((~m & u->cgroup_subtree_mask) == 0);
967
968         u->cgroup_subtree_mask = m;
969         u->cgroup_subtree_mask_valid = true;
970
971         if (UNIT_ISSET(u->slice)) {
972                 Unit *s = UNIT_DEREF(u->slice);
973
974                 if (more)
975                         /* There's more set now than before. We
976                          * propagate the new mask to the parent's mask
977                          * (not caring if it actually was valid or
978                          * not). */
979
980                         s->cgroup_members_mask |= m;
981
982                 else
983                         /* There's less set now than before (or we
984                          * don't know), we need to recalculate
985                          * everything, so let's invalidate the
986                          * parent's members mask */
987
988                         s->cgroup_members_mask_valid = false;
989
990                 /* And now make sure that this change also hits our
991                  * grandparents */
992                 unit_update_cgroup_members_masks(s);
993         }
994 }
995
996 static const char *migrate_callback(CGroupMask mask, void *userdata) {
997         Unit *u = userdata;
998
999         assert(mask != 0);
1000         assert(u);
1001
1002         while (u) {
1003                 if (u->cgroup_path &&
1004                     u->cgroup_realized &&
1005                     (u->cgroup_realized_mask & mask) == mask)
1006                         return u->cgroup_path;
1007
1008                 u = UNIT_DEREF(u->slice);
1009         }
1010
1011         return NULL;
1012 }
1013
1014 char *unit_default_cgroup_path(Unit *u) {
1015         _cleanup_free_ char *escaped = NULL, *slice = NULL;
1016         int r;
1017
1018         assert(u);
1019
1020         if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1021                 return strdup(u->manager->cgroup_root);
1022
1023         if (UNIT_ISSET(u->slice) && !unit_has_name(UNIT_DEREF(u->slice), SPECIAL_ROOT_SLICE)) {
1024                 r = cg_slice_to_path(UNIT_DEREF(u->slice)->id, &slice);
1025                 if (r < 0)
1026                         return NULL;
1027         }
1028
1029         escaped = cg_escape(u->id);
1030         if (!escaped)
1031                 return NULL;
1032
1033         if (slice)
1034                 return strjoin(u->manager->cgroup_root, "/", slice, "/", escaped, NULL);
1035         else
1036                 return strjoin(u->manager->cgroup_root, "/", escaped, NULL);
1037 }
1038
1039 int unit_set_cgroup_path(Unit *u, const char *path) {
1040         _cleanup_free_ char *p = NULL;
1041         int r;
1042
1043         assert(u);
1044
1045         if (path) {
1046                 p = strdup(path);
1047                 if (!p)
1048                         return -ENOMEM;
1049         } else
1050                 p = NULL;
1051
1052         if (streq_ptr(u->cgroup_path, p))
1053                 return 0;
1054
1055         if (p) {
1056                 r = hashmap_put(u->manager->cgroup_unit, p, u);
1057                 if (r < 0)
1058                         return r;
1059         }
1060
1061         unit_release_cgroup(u);
1062
1063         u->cgroup_path = p;
1064         p = NULL;
1065
1066         return 1;
1067 }
1068
1069 int unit_watch_cgroup(Unit *u) {
1070         _cleanup_free_ char *events = NULL;
1071         int r;
1072
1073         assert(u);
1074
1075         if (!u->cgroup_path)
1076                 return 0;
1077
1078         if (u->cgroup_inotify_wd >= 0)
1079                 return 0;
1080
1081         /* Only applies to the unified hierarchy */
1082         r = cg_unified();
1083         if (r < 0)
1084                 return log_unit_error_errno(u, r, "Failed detect whether the unified hierarchy is used: %m");
1085         if (r == 0)
1086                 return 0;
1087
1088         /* Don't watch the root slice, it's pointless. */
1089         if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1090                 return 0;
1091
1092         r = hashmap_ensure_allocated(&u->manager->cgroup_inotify_wd_unit, &trivial_hash_ops);
1093         if (r < 0)
1094                 return log_oom();
1095
1096         r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events", &events);
1097         if (r < 0)
1098                 return log_oom();
1099
1100         u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
1101         if (u->cgroup_inotify_wd < 0) {
1102
1103                 if (errno == ENOENT) /* If the directory is already
1104                                       * gone we don't need to track
1105                                       * it, so this is not an error */
1106                         return 0;
1107
1108                 return log_unit_error_errno(u, errno, "Failed to add inotify watch descriptor for control group %s: %m", u->cgroup_path);
1109         }
1110
1111         r = hashmap_put(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd), u);
1112         if (r < 0)
1113                 return log_unit_error_errno(u, r, "Failed to add inotify watch descriptor to hash map: %m");
1114
1115         return 0;
1116 }
1117
1118 static int unit_create_cgroup(
1119                 Unit *u,
1120                 CGroupMask target_mask,
1121                 CGroupMask enable_mask) {
1122
1123         CGroupContext *c;
1124         int r;
1125
1126         assert(u);
1127
1128         c = unit_get_cgroup_context(u);
1129         if (!c)
1130                 return 0;
1131
1132         if (!u->cgroup_path) {
1133                 _cleanup_free_ char *path = NULL;
1134
1135                 path = unit_default_cgroup_path(u);
1136                 if (!path)
1137                         return log_oom();
1138
1139                 r = unit_set_cgroup_path(u, path);
1140                 if (r == -EEXIST)
1141                         return log_unit_error_errno(u, r, "Control group %s exists already.", path);
1142                 if (r < 0)
1143                         return log_unit_error_errno(u, r, "Failed to set unit's control group path to %s: %m", path);
1144         }
1145
1146         /* First, create our own group */
1147         r = cg_create_everywhere(u->manager->cgroup_supported, target_mask, u->cgroup_path);
1148         if (r < 0)
1149                 return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", u->cgroup_path);
1150
1151         /* Start watching it */
1152         (void) unit_watch_cgroup(u);
1153
1154         /* Enable all controllers we need */
1155         r = cg_enable_everywhere(u->manager->cgroup_supported, enable_mask, u->cgroup_path);
1156         if (r < 0)
1157                 log_unit_warning_errno(u, r, "Failed to enable controllers on cgroup %s, ignoring: %m", u->cgroup_path);
1158
1159         /* Keep track that this is now realized */
1160         u->cgroup_realized = true;
1161         u->cgroup_realized_mask = target_mask;
1162         u->cgroup_enabled_mask = enable_mask;
1163
1164         if (u->type != UNIT_SLICE && !c->delegate) {
1165
1166                 /* Then, possibly move things over, but not if
1167                  * subgroups may contain processes, which is the case
1168                  * for slice and delegation units. */
1169                 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
1170                 if (r < 0)
1171                         log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
1172         }
1173
1174         return 0;
1175 }
1176
1177 int unit_attach_pids_to_cgroup(Unit *u) {
1178         int r;
1179         assert(u);
1180
1181         r = unit_realize_cgroup(u);
1182         if (r < 0)
1183                 return r;
1184
1185         r = cg_attach_many_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->pids, migrate_callback, u);
1186         if (r < 0)
1187                 return r;
1188
1189         return 0;
1190 }
1191
1192 static bool unit_has_mask_realized(Unit *u, CGroupMask target_mask, CGroupMask enable_mask) {
1193         assert(u);
1194
1195         return u->cgroup_realized && u->cgroup_realized_mask == target_mask && u->cgroup_enabled_mask == enable_mask;
1196 }
1197
1198 /* Check if necessary controllers and attributes for a unit are in place.
1199  *
1200  * If so, do nothing.
1201  * If not, create paths, move processes over, and set attributes.
1202  *
1203  * Returns 0 on success and < 0 on failure. */
1204 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
1205         CGroupMask target_mask, enable_mask;
1206         int r;
1207
1208         assert(u);
1209
1210         if (u->in_cgroup_queue) {
1211                 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
1212                 u->in_cgroup_queue = false;
1213         }
1214
1215         target_mask = unit_get_target_mask(u);
1216         enable_mask = unit_get_enable_mask(u);
1217
1218         if (unit_has_mask_realized(u, target_mask, enable_mask))
1219                 return 0;
1220
1221         /* First, realize parents */
1222         if (UNIT_ISSET(u->slice)) {
1223                 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
1224                 if (r < 0)
1225                         return r;
1226         }
1227
1228         /* And then do the real work */
1229         r = unit_create_cgroup(u, target_mask, enable_mask);
1230         if (r < 0)
1231                 return r;
1232
1233         /* Finally, apply the necessary attributes. */
1234         cgroup_context_apply(u, target_mask, state);
1235
1236         return 0;
1237 }
1238
1239 static void unit_add_to_cgroup_queue(Unit *u) {
1240
1241         if (u->in_cgroup_queue)
1242                 return;
1243
1244         LIST_PREPEND(cgroup_queue, u->manager->cgroup_queue, u);
1245         u->in_cgroup_queue = true;
1246 }
1247
1248 unsigned manager_dispatch_cgroup_queue(Manager *m) {
1249         ManagerState state;
1250         unsigned n = 0;
1251         Unit *i;
1252         int r;
1253
1254         state = manager_state(m);
1255
1256         while ((i = m->cgroup_queue)) {
1257                 assert(i->in_cgroup_queue);
1258
1259                 r = unit_realize_cgroup_now(i, state);
1260                 if (r < 0)
1261                         log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
1262
1263                 n++;
1264         }
1265
1266         return n;
1267 }
1268
1269 static void unit_queue_siblings(Unit *u) {
1270         Unit *slice;
1271
1272         /* This adds the siblings of the specified unit and the
1273          * siblings of all parent units to the cgroup queue. (But
1274          * neither the specified unit itself nor the parents.) */
1275
1276         while ((slice = UNIT_DEREF(u->slice))) {
1277                 Iterator i;
1278                 Unit *m;
1279
1280                 SET_FOREACH(m, slice->dependencies[UNIT_BEFORE], i) {
1281                         if (m == u)
1282                                 continue;
1283
1284                         /* Skip units that have a dependency on the slice
1285                          * but aren't actually in it. */
1286                         if (UNIT_DEREF(m->slice) != slice)
1287                                 continue;
1288
1289                         /* No point in doing cgroup application for units
1290                          * without active processes. */
1291                         if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
1292                                 continue;
1293
1294                         /* If the unit doesn't need any new controllers
1295                          * and has current ones realized, it doesn't need
1296                          * any changes. */
1297                         if (unit_has_mask_realized(m, unit_get_target_mask(m), unit_get_enable_mask(m)))
1298                                 continue;
1299
1300                         unit_add_to_cgroup_queue(m);
1301                 }
1302
1303                 u = slice;
1304         }
1305 }
1306
1307 int unit_realize_cgroup(Unit *u) {
1308         assert(u);
1309
1310         if (!UNIT_HAS_CGROUP_CONTEXT(u))
1311                 return 0;
1312
1313         /* So, here's the deal: when realizing the cgroups for this
1314          * unit, we need to first create all parents, but there's more
1315          * actually: for the weight-based controllers we also need to
1316          * make sure that all our siblings (i.e. units that are in the
1317          * same slice as we are) have cgroups, too. Otherwise, things
1318          * would become very uneven as each of their processes would
1319          * get as much resources as all our group together. This call
1320          * will synchronously create the parent cgroups, but will
1321          * defer work on the siblings to the next event loop
1322          * iteration. */
1323
1324         /* Add all sibling slices to the cgroup queue. */
1325         unit_queue_siblings(u);
1326
1327         /* And realize this one now (and apply the values) */
1328         return unit_realize_cgroup_now(u, manager_state(u->manager));
1329 }
1330
1331 void unit_release_cgroup(Unit *u) {
1332         assert(u);
1333
1334         /* Forgets all cgroup details for this cgroup */
1335
1336         if (u->cgroup_path) {
1337                 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1338                 u->cgroup_path = mfree(u->cgroup_path);
1339         }
1340
1341         if (u->cgroup_inotify_wd >= 0) {
1342                 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1343                         log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1344
1345                 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1346                 u->cgroup_inotify_wd = -1;
1347         }
1348 }
1349
1350 void unit_prune_cgroup(Unit *u) {
1351         int r;
1352         bool is_root_slice;
1353
1354         assert(u);
1355
1356         /* Removes the cgroup, if empty and possible, and stops watching it. */
1357
1358         if (!u->cgroup_path)
1359                 return;
1360
1361         is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1362
1363         r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
1364         if (r < 0) {
1365                 log_unit_debug_errno(u, r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
1366                 return;
1367         }
1368
1369         if (is_root_slice)
1370                 return;
1371
1372         unit_release_cgroup(u);
1373
1374         u->cgroup_realized = false;
1375         u->cgroup_realized_mask = 0;
1376         u->cgroup_enabled_mask = 0;
1377 }
1378
1379 int unit_search_main_pid(Unit *u, pid_t *ret) {
1380         _cleanup_fclose_ FILE *f = NULL;
1381         pid_t pid = 0, npid, mypid;
1382         int r;
1383
1384         assert(u);
1385         assert(ret);
1386
1387         if (!u->cgroup_path)
1388                 return -ENXIO;
1389
1390         r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1391         if (r < 0)
1392                 return r;
1393
1394         mypid = getpid();
1395         while (cg_read_pid(f, &npid) > 0)  {
1396                 pid_t ppid;
1397
1398                 if (npid == pid)
1399                         continue;
1400
1401                 /* Ignore processes that aren't our kids */
1402                 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
1403                         continue;
1404
1405                 if (pid != 0)
1406                         /* Dang, there's more than one daemonized PID
1407                         in this group, so we don't know what process
1408                         is the main process. */
1409
1410                         return -ENODATA;
1411
1412                 pid = npid;
1413         }
1414
1415         *ret = pid;
1416         return 0;
1417 }
1418
1419 static int unit_watch_pids_in_path(Unit *u, const char *path) {
1420         _cleanup_closedir_ DIR *d = NULL;
1421         _cleanup_fclose_ FILE *f = NULL;
1422         int ret = 0, r;
1423
1424         assert(u);
1425         assert(path);
1426
1427         r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1428         if (r < 0)
1429                 ret = r;
1430         else {
1431                 pid_t pid;
1432
1433                 while ((r = cg_read_pid(f, &pid)) > 0) {
1434                         r = unit_watch_pid(u, pid);
1435                         if (r < 0 && ret >= 0)
1436                                 ret = r;
1437                 }
1438
1439                 if (r < 0 && ret >= 0)
1440                         ret = r;
1441         }
1442
1443         r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1444         if (r < 0) {
1445                 if (ret >= 0)
1446                         ret = r;
1447         } else {
1448                 char *fn;
1449
1450                 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1451                         _cleanup_free_ char *p = NULL;
1452
1453                         p = strjoin(path, "/", fn, NULL);
1454                         free(fn);
1455
1456                         if (!p)
1457                                 return -ENOMEM;
1458
1459                         r = unit_watch_pids_in_path(u, p);
1460                         if (r < 0 && ret >= 0)
1461                                 ret = r;
1462                 }
1463
1464                 if (r < 0 && ret >= 0)
1465                         ret = r;
1466         }
1467
1468         return ret;
1469 }
1470
1471 int unit_watch_all_pids(Unit *u) {
1472         assert(u);
1473
1474         /* Adds all PIDs from our cgroup to the set of PIDs we
1475          * watch. This is a fallback logic for cases where we do not
1476          * get reliable cgroup empty notifications: we try to use
1477          * SIGCHLD as replacement. */
1478
1479         if (!u->cgroup_path)
1480                 return -ENOENT;
1481
1482         if (cg_unified() > 0) /* On unified we can use proper notifications */
1483                 return 0;
1484
1485         return unit_watch_pids_in_path(u, u->cgroup_path);
1486 }
1487
1488 int unit_notify_cgroup_empty(Unit *u) {
1489         int r;
1490
1491         assert(u);
1492
1493         if (!u->cgroup_path)
1494                 return 0;
1495
1496         r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
1497         if (r <= 0)
1498                 return r;
1499
1500         unit_add_to_gc_queue(u);
1501
1502         if (UNIT_VTABLE(u)->notify_cgroup_empty)
1503                 UNIT_VTABLE(u)->notify_cgroup_empty(u);
1504
1505         return 0;
1506 }
1507
1508 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1509         Manager *m = userdata;
1510
1511         assert(s);
1512         assert(fd >= 0);
1513         assert(m);
1514
1515         for (;;) {
1516                 union inotify_event_buffer buffer;
1517                 struct inotify_event *e;
1518                 ssize_t l;
1519
1520                 l = read(fd, &buffer, sizeof(buffer));
1521                 if (l < 0) {
1522                         if (errno == EINTR || errno == EAGAIN)
1523                                 return 0;
1524
1525                         return log_error_errno(errno, "Failed to read control group inotify events: %m");
1526                 }
1527
1528                 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1529                         Unit *u;
1530
1531                         if (e->wd < 0)
1532                                 /* Queue overflow has no watch descriptor */
1533                                 continue;
1534
1535                         if (e->mask & IN_IGNORED)
1536                                 /* The watch was just removed */
1537                                 continue;
1538
1539                         u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
1540                         if (!u) /* Not that inotify might deliver
1541                                  * events for a watch even after it
1542                                  * was removed, because it was queued
1543                                  * before the removal. Let's ignore
1544                                  * this here safely. */
1545                                 continue;
1546
1547                         (void) unit_notify_cgroup_empty(u);
1548                 }
1549         }
1550 }
1551 #endif // 0
1552
1553 int manager_setup_cgroup(Manager *m) {
1554         _cleanup_free_ char *path = NULL;
1555         CGroupController c;
1556         int r, unified;
1557         char *e;
1558
1559         assert(m);
1560
1561         /* 1. Determine hierarchy */
1562         m->cgroup_root = mfree(m->cgroup_root);
1563         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
1564         if (r < 0)
1565                 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
1566
1567 #if 0 /// elogind does not support systemd scopes and slices
1568         /* Chop off the init scope, if we are already located in it */
1569         e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1570
1571         /* LEGACY: Also chop off the system slice if we are in
1572          * it. This is to support live upgrades from older systemd
1573          * versions where PID 1 was moved there. Also see
1574          * cg_get_root_path(). */
1575         if (!e && MANAGER_IS_SYSTEM(m)) {
1576                 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
1577                 if (!e)
1578                         e = endswith(m->cgroup_root, "/system"); /* even more legacy */
1579         }
1580         if (e)
1581                 *e = 0;
1582 #endif // 0
1583
1584         /* And make sure to store away the root value without trailing
1585          * slash, even for the root dir, so that we can easily prepend
1586          * it everywhere. */
1587         while ((e = endswith(m->cgroup_root, "/")))
1588                 *e = 0;
1589         log_debug_elogind("Cgroup Controller \"%s\" -> root \"%s\"",
1590                           SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root);
1591
1592         /* 2. Show data */
1593         r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
1594         if (r < 0)
1595                 return log_error_errno(r, "Cannot find cgroup mount point: %m");
1596
1597         unified = cg_unified();
1598         if (unified < 0)
1599                 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
1600         if (unified > 0)
1601                 log_debug("Unified cgroup hierarchy is located at %s.", path);
1602         else
1603                 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER ". File system hierarchy is at %s.", path);
1604
1605         if (!m->test_run) {
1606                 const char *scope_path;
1607
1608                 /* 3. Install agent */
1609                 if (unified) {
1610
1611                         /* In the unified hierarchy we can can get
1612                          * cgroup empty notifications via inotify. */
1613
1614 #if 0 /// elogind does not support the unified hierarchy, yet.
1615                         m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1616                         safe_close(m->cgroup_inotify_fd);
1617
1618                         m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1619                         if (m->cgroup_inotify_fd < 0)
1620                                 return log_error_errno(errno, "Failed to create control group inotify object: %m");
1621
1622                         r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
1623                         if (r < 0)
1624                                 return log_error_errno(r, "Failed to watch control group inotify object: %m");
1625
1626                         /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
1627                          * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
1628                         r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_NORMAL-5);
1629                         if (r < 0)
1630                                 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
1631
1632                         (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
1633
1634 #else
1635                         return log_error_errno(EOPNOTSUPP, "Unified cgroup hierarchy not supported: %m");
1636 #endif // 0
1637                 } else if (MANAGER_IS_SYSTEM(m)) {
1638
1639                         /* On the legacy hierarchy we only get
1640                          * notifications via cgroup agents. (Which
1641                          * isn't really reliable, since it does not
1642                          * generate events when control groups with
1643                          * children run empty. */
1644
1645                         r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
1646                         if (r < 0)
1647                                 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
1648                         else if (r > 0)
1649                                 log_debug("Installed release agent.");
1650                         else if (r == 0)
1651                                 log_debug("Release agent already installed.");
1652                 }
1653
1654 #if 0 /// elogind is not meant to run in systemd init scope
1655                 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1656                 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1657                 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1658 #else
1659                 if (streq(SYSTEMD_CGROUP_CONTROLLER, "name=elogind"))
1660                         // we are our own cgroup controller
1661                         scope_path = strjoina("");
1662                 else if (streq(m->cgroup_root, "/elogind"))
1663                         // root already is our cgroup
1664                         scope_path = strjoina(m->cgroup_root);
1665                 else
1666                         // we have to create our own group
1667                         scope_path = strjoina(m->cgroup_root, "/elogind");
1668                 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1669 #endif // 0
1670                 if (r < 0)
1671                         return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
1672                 log_debug_elogind("Created control group \"%s\"", scope_path);
1673
1674                 /* also, move all other userspace processes remaining
1675                  * in the root cgroup into that scope. */
1676                 r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1677                 if (r < 0)
1678                         log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
1679
1680                 /* 5. And pin it, so that it cannot be unmounted */
1681                 safe_close(m->pin_cgroupfs_fd);
1682                 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
1683                 if (m->pin_cgroupfs_fd < 0)
1684                         return log_error_errno(errno, "Failed to open pin file: %m");
1685
1686                 /* 6.  Always enable hierarchical support if it exists... */
1687                 if (!unified)
1688                         (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
1689         }
1690
1691         /* 7. Figure out which controllers are supported */
1692         r = cg_mask_supported(&m->cgroup_supported);
1693         if (r < 0)
1694                 return log_error_errno(r, "Failed to determine supported controllers: %m");
1695
1696         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
1697                 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & CGROUP_CONTROLLER_TO_MASK(c)));
1698
1699         return 0;
1700 }
1701
1702 void manager_shutdown_cgroup(Manager *m, bool delete) {
1703         assert(m);
1704
1705         /* We can't really delete the group, since we are in it. But
1706          * let's trim it. */
1707         if (delete && m->cgroup_root)
1708                 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
1709
1710 #if 0 /// elogind does not support the unified hierarchy, yet.
1711         m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
1712
1713         m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1714         m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
1715 #endif // 0
1716
1717         m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
1718
1719         m->cgroup_root = mfree(m->cgroup_root);
1720 }
1721
1722 #if 0 /// UNNEEDED by elogind
1723 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
1724         char *p;
1725         Unit *u;
1726
1727         assert(m);
1728         assert(cgroup);
1729
1730         u = hashmap_get(m->cgroup_unit, cgroup);
1731         if (u)
1732                 return u;
1733
1734         p = strdupa(cgroup);
1735         for (;;) {
1736                 char *e;
1737
1738                 e = strrchr(p, '/');
1739                 if (!e || e == p)
1740                         return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
1741
1742                 *e = 0;
1743
1744                 u = hashmap_get(m->cgroup_unit, p);
1745                 if (u)
1746                         return u;
1747         }
1748 }
1749
1750 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
1751         _cleanup_free_ char *cgroup = NULL;
1752         int r;
1753
1754         assert(m);
1755
1756         if (pid <= 0)
1757                 return NULL;
1758
1759         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
1760         if (r < 0)
1761                 return NULL;
1762
1763         return manager_get_unit_by_cgroup(m, cgroup);
1764 }
1765
1766 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
1767         Unit *u;
1768
1769         assert(m);
1770
1771         if (pid <= 0)
1772                 return NULL;
1773
1774         if (pid == 1)
1775                 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
1776
1777         u = hashmap_get(m->watch_pids1, PID_TO_PTR(pid));
1778         if (u)
1779                 return u;
1780
1781         u = hashmap_get(m->watch_pids2, PID_TO_PTR(pid));
1782         if (u)
1783                 return u;
1784
1785         return manager_get_unit_by_pid_cgroup(m, pid);
1786 }
1787
1788 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
1789         Unit *u;
1790
1791         assert(m);
1792         assert(cgroup);
1793
1794         log_debug("Got cgroup empty notification for: %s", cgroup);
1795
1796         u = manager_get_unit_by_cgroup(m, cgroup);
1797         if (!u)
1798                 return 0;
1799
1800         return unit_notify_cgroup_empty(u);
1801 }
1802
1803 int unit_get_memory_current(Unit *u, uint64_t *ret) {
1804         _cleanup_free_ char *v = NULL;
1805         int r;
1806
1807         assert(u);
1808         assert(ret);
1809
1810         if (!u->cgroup_path)
1811                 return -ENODATA;
1812
1813         if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
1814                 return -ENODATA;
1815
1816         if (cg_unified() <= 0)
1817                 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
1818         else
1819                 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
1820         if (r == -ENOENT)
1821                 return -ENODATA;
1822         if (r < 0)
1823                 return r;
1824
1825         return safe_atou64(v, ret);
1826 }
1827
1828 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
1829         _cleanup_free_ char *v = NULL;
1830         int r;
1831
1832         assert(u);
1833         assert(ret);
1834
1835         if (!u->cgroup_path)
1836                 return -ENODATA;
1837
1838         if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
1839                 return -ENODATA;
1840
1841         r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
1842         if (r == -ENOENT)
1843                 return -ENODATA;
1844         if (r < 0)
1845                 return r;
1846
1847         return safe_atou64(v, ret);
1848 }
1849
1850 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
1851         _cleanup_free_ char *v = NULL;
1852         uint64_t ns;
1853         int r;
1854
1855         assert(u);
1856         assert(ret);
1857
1858         if (!u->cgroup_path)
1859                 return -ENODATA;
1860
1861         if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
1862                 return -ENODATA;
1863
1864         r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
1865         if (r == -ENOENT)
1866                 return -ENODATA;
1867         if (r < 0)
1868                 return r;
1869
1870         r = safe_atou64(v, &ns);
1871         if (r < 0)
1872                 return r;
1873
1874         *ret = ns;
1875         return 0;
1876 }
1877
1878 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
1879         nsec_t ns;
1880         int r;
1881
1882         r = unit_get_cpu_usage_raw(u, &ns);
1883         if (r < 0)
1884                 return r;
1885
1886         if (ns > u->cpuacct_usage_base)
1887                 ns -= u->cpuacct_usage_base;
1888         else
1889                 ns = 0;
1890
1891         *ret = ns;
1892         return 0;
1893 }
1894
1895 int unit_reset_cpu_usage(Unit *u) {
1896         nsec_t ns;
1897         int r;
1898
1899         assert(u);
1900
1901         r = unit_get_cpu_usage_raw(u, &ns);
1902         if (r < 0) {
1903                 u->cpuacct_usage_base = 0;
1904                 return r;
1905         }
1906
1907         u->cpuacct_usage_base = ns;
1908         return 0;
1909 }
1910
1911 bool unit_cgroup_delegate(Unit *u) {
1912         CGroupContext *c;
1913
1914         assert(u);
1915
1916         c = unit_get_cgroup_context(u);
1917         if (!c)
1918                 return false;
1919
1920         return c->delegate;
1921 }
1922
1923 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
1924         assert(u);
1925
1926         if (!UNIT_HAS_CGROUP_CONTEXT(u))
1927                 return;
1928
1929         if (m == 0)
1930                 return;
1931
1932         /* always invalidate compat pairs together */
1933         if (m & (CGROUP_MASK_IO | CGROUP_MASK_BLKIO))
1934                 m |= CGROUP_MASK_IO | CGROUP_MASK_BLKIO;
1935
1936         if ((u->cgroup_realized_mask & m) == 0)
1937                 return;
1938
1939         u->cgroup_realized_mask &= ~m;
1940         unit_add_to_cgroup_queue(u);
1941 }
1942
1943 void manager_invalidate_startup_units(Manager *m) {
1944         Iterator i;
1945         Unit *u;
1946
1947         assert(m);
1948
1949         SET_FOREACH(u, m->startup_units, i)
1950                 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_IO|CGROUP_MASK_BLKIO);
1951 }
1952
1953 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
1954         [CGROUP_AUTO] = "auto",
1955         [CGROUP_CLOSED] = "closed",
1956         [CGROUP_STRICT] = "strict",
1957 };
1958
1959 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);
1960 #endif // 0