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