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