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