chiark / gitweb /
Prep v229: Remove remaining emacs settings [2/6] src/core
[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 *populated = 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.populated", &populated);
796         if (r < 0)
797                 return log_oom();
798
799         u->cgroup_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, populated, 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
862         if (u->type != UNIT_SLICE && !c->delegate) {
863
864                 /* Then, possibly move things over, but not if
865                  * subgroups may contain processes, which is the case
866                  * for slice and delegation units. */
867                 r = cg_migrate_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->cgroup_path, migrate_callback, u);
868                 if (r < 0)
869                         log_unit_warning_errno(u, r, "Failed to migrate cgroup from to %s, ignoring: %m", u->cgroup_path);
870         }
871
872         return 0;
873 }
874
875 int unit_attach_pids_to_cgroup(Unit *u) {
876         int r;
877         assert(u);
878
879         r = unit_realize_cgroup(u);
880         if (r < 0)
881                 return r;
882
883         r = cg_attach_many_everywhere(u->manager->cgroup_supported, u->cgroup_path, u->pids, migrate_callback, u);
884         if (r < 0)
885                 return r;
886
887         return 0;
888 }
889
890 static bool unit_has_mask_realized(Unit *u, CGroupMask target_mask) {
891         assert(u);
892
893         return u->cgroup_realized && u->cgroup_realized_mask == target_mask;
894 }
895
896 /* Check if necessary controllers and attributes for a unit are in place.
897  *
898  * If so, do nothing.
899  * If not, create paths, move processes over, and set attributes.
900  *
901  * Returns 0 on success and < 0 on failure. */
902 static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
903         CGroupMask target_mask, enable_mask;
904         int r;
905
906         assert(u);
907
908         if (u->in_cgroup_queue) {
909                 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
910                 u->in_cgroup_queue = false;
911         }
912
913         target_mask = unit_get_target_mask(u);
914         if (unit_has_mask_realized(u, target_mask))
915                 return 0;
916
917         /* First, realize parents */
918         if (UNIT_ISSET(u->slice)) {
919                 r = unit_realize_cgroup_now(UNIT_DEREF(u->slice), state);
920                 if (r < 0)
921                         return r;
922         }
923
924         /* And then do the real work */
925         enable_mask = unit_get_enable_mask(u);
926         r = unit_create_cgroup(u, target_mask, enable_mask);
927         if (r < 0)
928                 return r;
929
930         /* Finally, apply the necessary attributes. */
931         cgroup_context_apply(unit_get_cgroup_context(u), target_mask, u->cgroup_path, state);
932
933         return 0;
934 }
935
936 static void unit_add_to_cgroup_queue(Unit *u) {
937
938         if (u->in_cgroup_queue)
939                 return;
940
941         LIST_PREPEND(cgroup_queue, u->manager->cgroup_queue, u);
942         u->in_cgroup_queue = true;
943 }
944
945 unsigned manager_dispatch_cgroup_queue(Manager *m) {
946         ManagerState state;
947         unsigned n = 0;
948         Unit *i;
949         int r;
950
951         state = manager_state(m);
952
953         while ((i = m->cgroup_queue)) {
954                 assert(i->in_cgroup_queue);
955
956                 r = unit_realize_cgroup_now(i, state);
957                 if (r < 0)
958                         log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
959
960                 n++;
961         }
962
963         return n;
964 }
965
966 static void unit_queue_siblings(Unit *u) {
967         Unit *slice;
968
969         /* This adds the siblings of the specified unit and the
970          * siblings of all parent units to the cgroup queue. (But
971          * neither the specified unit itself nor the parents.) */
972
973         while ((slice = UNIT_DEREF(u->slice))) {
974                 Iterator i;
975                 Unit *m;
976
977                 SET_FOREACH(m, slice->dependencies[UNIT_BEFORE], i) {
978                         if (m == u)
979                                 continue;
980
981                         /* Skip units that have a dependency on the slice
982                          * but aren't actually in it. */
983                         if (UNIT_DEREF(m->slice) != slice)
984                                 continue;
985
986                         /* No point in doing cgroup application for units
987                          * without active processes. */
988                         if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
989                                 continue;
990
991                         /* If the unit doesn't need any new controllers
992                          * and has current ones realized, it doesn't need
993                          * any changes. */
994                         if (unit_has_mask_realized(m, unit_get_target_mask(m)))
995                                 continue;
996
997                         unit_add_to_cgroup_queue(m);
998                 }
999
1000                 u = slice;
1001         }
1002 }
1003
1004 int unit_realize_cgroup(Unit *u) {
1005         assert(u);
1006
1007         if (!UNIT_HAS_CGROUP_CONTEXT(u))
1008                 return 0;
1009
1010         /* So, here's the deal: when realizing the cgroups for this
1011          * unit, we need to first create all parents, but there's more
1012          * actually: for the weight-based controllers we also need to
1013          * make sure that all our siblings (i.e. units that are in the
1014          * same slice as we are) have cgroups, too. Otherwise, things
1015          * would become very uneven as each of their processes would
1016          * get as much resources as all our group together. This call
1017          * will synchronously create the parent cgroups, but will
1018          * defer work on the siblings to the next event loop
1019          * iteration. */
1020
1021         /* Add all sibling slices to the cgroup queue. */
1022         unit_queue_siblings(u);
1023
1024         /* And realize this one now (and apply the values) */
1025         return unit_realize_cgroup_now(u, manager_state(u->manager));
1026 }
1027
1028 void unit_release_cgroup(Unit *u) {
1029         assert(u);
1030
1031         /* Forgets all cgroup details for this cgroup */
1032
1033         if (u->cgroup_path) {
1034                 (void) hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
1035                 u->cgroup_path = mfree(u->cgroup_path);
1036         }
1037
1038         if (u->cgroup_inotify_wd >= 0) {
1039                 if (inotify_rm_watch(u->manager->cgroup_inotify_fd, u->cgroup_inotify_wd) < 0)
1040                         log_unit_debug_errno(u, errno, "Failed to remove cgroup inotify watch %i for %s, ignoring", u->cgroup_inotify_wd, u->id);
1041
1042                 (void) hashmap_remove(u->manager->cgroup_inotify_wd_unit, INT_TO_PTR(u->cgroup_inotify_wd));
1043                 u->cgroup_inotify_wd = -1;
1044         }
1045 }
1046
1047 void unit_prune_cgroup(Unit *u) {
1048         int r;
1049         bool is_root_slice;
1050
1051         assert(u);
1052
1053         /* Removes the cgroup, if empty and possible, and stops watching it. */
1054
1055         if (!u->cgroup_path)
1056                 return;
1057
1058         is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
1059
1060         r = cg_trim_everywhere(u->manager->cgroup_supported, u->cgroup_path, !is_root_slice);
1061         if (r < 0) {
1062                 log_debug_errno(r, "Failed to destroy cgroup %s, ignoring: %m", u->cgroup_path);
1063                 return;
1064         }
1065
1066         if (is_root_slice)
1067                 return;
1068
1069         unit_release_cgroup(u);
1070
1071         u->cgroup_realized = false;
1072         u->cgroup_realized_mask = 0;
1073 }
1074
1075 int unit_search_main_pid(Unit *u, pid_t *ret) {
1076         _cleanup_fclose_ FILE *f = NULL;
1077         pid_t pid = 0, npid, mypid;
1078         int r;
1079
1080         assert(u);
1081         assert(ret);
1082
1083         if (!u->cgroup_path)
1084                 return -ENXIO;
1085
1086         r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f);
1087         if (r < 0)
1088                 return r;
1089
1090         mypid = getpid();
1091         while (cg_read_pid(f, &npid) > 0)  {
1092                 pid_t ppid;
1093
1094                 if (npid == pid)
1095                         continue;
1096
1097                 /* Ignore processes that aren't our kids */
1098                 if (get_process_ppid(npid, &ppid) >= 0 && ppid != mypid)
1099                         continue;
1100
1101                 if (pid != 0)
1102                         /* Dang, there's more than one daemonized PID
1103                         in this group, so we don't know what process
1104                         is the main process. */
1105
1106                         return -ENODATA;
1107
1108                 pid = npid;
1109         }
1110
1111         *ret = pid;
1112         return 0;
1113 }
1114
1115 static int unit_watch_pids_in_path(Unit *u, const char *path) {
1116         _cleanup_closedir_ DIR *d = NULL;
1117         _cleanup_fclose_ FILE *f = NULL;
1118         int ret = 0, r;
1119
1120         assert(u);
1121         assert(path);
1122
1123         r = cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, path, &f);
1124         if (r < 0)
1125                 ret = r;
1126         else {
1127                 pid_t pid;
1128
1129                 while ((r = cg_read_pid(f, &pid)) > 0) {
1130                         r = unit_watch_pid(u, pid);
1131                         if (r < 0 && ret >= 0)
1132                                 ret = r;
1133                 }
1134
1135                 if (r < 0 && ret >= 0)
1136                         ret = r;
1137         }
1138
1139         r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, path, &d);
1140         if (r < 0) {
1141                 if (ret >= 0)
1142                         ret = r;
1143         } else {
1144                 char *fn;
1145
1146                 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1147                         _cleanup_free_ char *p = NULL;
1148
1149                         p = strjoin(path, "/", fn, NULL);
1150                         free(fn);
1151
1152                         if (!p)
1153                                 return -ENOMEM;
1154
1155                         r = unit_watch_pids_in_path(u, p);
1156                         if (r < 0 && ret >= 0)
1157                                 ret = r;
1158                 }
1159
1160                 if (r < 0 && ret >= 0)
1161                         ret = r;
1162         }
1163
1164         return ret;
1165 }
1166
1167 int unit_watch_all_pids(Unit *u) {
1168         assert(u);
1169
1170         /* Adds all PIDs from our cgroup to the set of PIDs we
1171          * watch. This is a fallback logic for cases where we do not
1172          * get reliable cgroup empty notifications: we try to use
1173          * SIGCHLD as replacement. */
1174
1175         if (!u->cgroup_path)
1176                 return -ENOENT;
1177
1178         if (cg_unified() > 0) /* On unified we can use proper notifications */
1179                 return 0;
1180
1181         return unit_watch_pids_in_path(u, u->cgroup_path);
1182 }
1183
1184 int unit_notify_cgroup_empty(Unit *u) {
1185         int r;
1186
1187         assert(u);
1188
1189         if (!u->cgroup_path)
1190                 return 0;
1191
1192         r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
1193         if (r <= 0)
1194                 return r;
1195
1196         unit_add_to_gc_queue(u);
1197
1198         if (UNIT_VTABLE(u)->notify_cgroup_empty)
1199                 UNIT_VTABLE(u)->notify_cgroup_empty(u);
1200
1201         return 0;
1202 }
1203
1204 static int on_cgroup_inotify_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1205         Manager *m = userdata;
1206
1207         assert(s);
1208         assert(fd >= 0);
1209         assert(m);
1210
1211         for (;;) {
1212                 union inotify_event_buffer buffer;
1213                 struct inotify_event *e;
1214                 ssize_t l;
1215
1216                 l = read(fd, &buffer, sizeof(buffer));
1217                 if (l < 0) {
1218                         if (errno == EINTR || errno == EAGAIN)
1219                                 return 0;
1220
1221                         return log_error_errno(errno, "Failed to read control group inotify events: %m");
1222                 }
1223
1224                 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1225                         Unit *u;
1226
1227                         if (e->wd < 0)
1228                                 /* Queue overflow has no watch descriptor */
1229                                 continue;
1230
1231                         if (e->mask & IN_IGNORED)
1232                                 /* The watch was just removed */
1233                                 continue;
1234
1235                         u = hashmap_get(m->cgroup_inotify_wd_unit, INT_TO_PTR(e->wd));
1236                         if (!u) /* Not that inotify might deliver
1237                                  * events for a watch even after it
1238                                  * was removed, because it was queued
1239                                  * before the removal. Let's ignore
1240                                  * this here safely. */
1241                                 continue;
1242
1243                         (void) unit_notify_cgroup_empty(u);
1244                 }
1245         }
1246 }
1247 #endif // 0
1248
1249 int manager_setup_cgroup(Manager *m) {
1250         _cleanup_free_ char *path = NULL;
1251         CGroupController c;
1252         int r, unified;
1253         char *e;
1254
1255         assert(m);
1256
1257         /* 1. Determine hierarchy */
1258         m->cgroup_root = mfree(m->cgroup_root);
1259         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
1260         if (r < 0)
1261                 return log_error_errno(r, "Cannot determine cgroup we are running in: %m");
1262
1263 #if 0 /// elogind does not support systemd scopes and slices
1264         /* Chop off the init scope, if we are already located in it */
1265         e = endswith(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1266
1267         /* LEGACY: Also chop off the system slice if we are in
1268          * it. This is to support live upgrades from older systemd
1269          * versions where PID 1 was moved there. Also see
1270          * cg_get_root_path(). */
1271         if (!e && m->running_as == MANAGER_SYSTEM) {
1272                 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
1273                 if (!e)
1274                         e = endswith(m->cgroup_root, "/system"); /* even more legacy */
1275         }
1276         if (e)
1277                 *e = 0;
1278 #endif // 0
1279
1280         /* And make sure to store away the root value without trailing
1281          * slash, even for the root dir, so that we can easily prepend
1282          * it everywhere. */
1283         while ((e = endswith(m->cgroup_root, "/")))
1284                 *e = 0;
1285         log_debug_elogind("Cgroup Controller \"%s\" -> root \"%s\"",
1286                           SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root);
1287
1288         /* 2. Show data */
1289         r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
1290         if (r < 0)
1291                 return log_error_errno(r, "Cannot find cgroup mount point: %m");
1292
1293         unified = cg_unified();
1294         if (unified < 0)
1295                 return log_error_errno(r, "Couldn't determine if we are running in the unified hierarchy: %m");
1296         if (unified > 0)
1297                 log_debug("Unified cgroup hierarchy is located at %s.", path);
1298         else
1299                 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER ". File system hierarchy is at %s.", path);
1300
1301         if (!m->test_run) {
1302                 const char *scope_path;
1303
1304                 /* 3. Install agent */
1305                 if (unified) {
1306
1307                         /* In the unified hierarchy we can can get
1308                          * cgroup empty notifications via inotify. */
1309
1310 #if 0 /// elogind does not support the unified hierarchy, yet.
1311                         m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1312                         safe_close(m->cgroup_inotify_fd);
1313
1314                         m->cgroup_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
1315                         if (m->cgroup_inotify_fd < 0)
1316                                 return log_error_errno(errno, "Failed to create control group inotify object: %m");
1317
1318                         r = sd_event_add_io(m->event, &m->cgroup_inotify_event_source, m->cgroup_inotify_fd, EPOLLIN, on_cgroup_inotify_event, m);
1319                         if (r < 0)
1320                                 return log_error_errno(r, "Failed to watch control group inotify object: %m");
1321
1322                         r = sd_event_source_set_priority(m->cgroup_inotify_event_source, SD_EVENT_PRIORITY_IDLE - 5);
1323                         if (r < 0)
1324                                 return log_error_errno(r, "Failed to set priority of inotify event source: %m");
1325
1326                         (void) sd_event_source_set_description(m->cgroup_inotify_event_source, "cgroup-inotify");
1327
1328 #else
1329                         return log_error_errno(EOPNOTSUPP, "Unified cgroup hierarchy not supported: %m");
1330 #endif // 0
1331                 } else if (m->running_as == MANAGER_SYSTEM) {
1332
1333                         /* On the legacy hierarchy we only get
1334                          * notifications via cgroup agents. (Which
1335                          * isn't really reliable, since it does not
1336                          * generate events when control groups with
1337                          * children run empty. */
1338
1339                         r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, ELOGIND_CGROUP_AGENT_PATH);
1340                         if (r < 0)
1341                                 log_warning_errno(r, "Failed to install release agent, ignoring: %m");
1342                         else if (r > 0)
1343                                 log_debug("Installed release agent.");
1344                         else if (r == 0)
1345                                 log_debug("Release agent already installed.");
1346                 }
1347
1348 #if 0 /// elogind is not meant to run in systemd init scope
1349                 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1350                 scope_path = strjoina(m->cgroup_root, "/" SPECIAL_INIT_SCOPE);
1351                 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1352 #else
1353                 if (streq(SYSTEMD_CGROUP_CONTROLLER, "name=elogind"))
1354                         // we are our own cgroup controller
1355                         scope_path = strjoina("");
1356                 else if (streq(m->cgroup_root, "/elogind"))
1357                         // root already is our cgroup
1358                         scope_path = strjoina(m->cgroup_root);
1359                 else
1360                         // we have to create our own group
1361                         scope_path = strjoina(m->cgroup_root, "/elogind");
1362                 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, scope_path, 0);
1363 #endif // 0
1364                 if (r < 0)
1365                         return log_error_errno(r, "Failed to create %s control group: %m", scope_path);
1366                 log_debug_elogind("Created control group \"%s\"", scope_path);
1367
1368                 /* also, move all other userspace processes remaining
1369                  * in the root cgroup into that scope. */
1370                 if (!streq(m->cgroup_root, scope_path)) {
1371                         r = cg_migrate(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, SYSTEMD_CGROUP_CONTROLLER, scope_path, false);
1372                         if (r < 0)
1373                                 log_warning_errno(r, "Couldn't move remaining userspace processes, ignoring: %m");
1374                 }
1375
1376                 /* 5. And pin it, so that it cannot be unmounted */
1377                 safe_close(m->pin_cgroupfs_fd);
1378                 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
1379                 if (m->pin_cgroupfs_fd < 0)
1380                         return log_error_errno(errno, "Failed to open pin file: %m");
1381
1382                 /* 6.  Always enable hierarchical support if it exists... */
1383                 if (!unified)
1384                         (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
1385         }
1386
1387         /* 7. Figure out which controllers are supported */
1388         r = cg_mask_supported(&m->cgroup_supported);
1389         if (r < 0)
1390                 return log_error_errno(r, "Failed to determine supported controllers: %m");
1391
1392         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++)
1393                 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c), yes_no(m->cgroup_supported & c));
1394
1395         return 0;
1396 }
1397
1398 void manager_shutdown_cgroup(Manager *m, bool delete) {
1399         assert(m);
1400
1401         /* We can't really delete the group, since we are in it. But
1402          * let's trim it. */
1403         if (delete && m->cgroup_root)
1404                 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
1405
1406 #if 0 /// elogind does not support the unified hierarchy, yet.
1407         m->cgroup_inotify_wd_unit = hashmap_free(m->cgroup_inotify_wd_unit);
1408
1409         m->cgroup_inotify_event_source = sd_event_source_unref(m->cgroup_inotify_event_source);
1410         m->cgroup_inotify_fd = safe_close(m->cgroup_inotify_fd);
1411 #endif // 0
1412
1413         m->pin_cgroupfs_fd = safe_close(m->pin_cgroupfs_fd);
1414
1415         m->cgroup_root = mfree(m->cgroup_root);
1416 }
1417
1418 #if 0 /// UNNEEDED by elogind
1419 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
1420         char *p;
1421         Unit *u;
1422
1423         assert(m);
1424         assert(cgroup);
1425
1426         u = hashmap_get(m->cgroup_unit, cgroup);
1427         if (u)
1428                 return u;
1429
1430         p = strdupa(cgroup);
1431         for (;;) {
1432                 char *e;
1433
1434                 e = strrchr(p, '/');
1435                 if (!e || e == p)
1436                         return hashmap_get(m->cgroup_unit, SPECIAL_ROOT_SLICE);
1437
1438                 *e = 0;
1439
1440                 u = hashmap_get(m->cgroup_unit, p);
1441                 if (u)
1442                         return u;
1443         }
1444 }
1445
1446 Unit *manager_get_unit_by_pid_cgroup(Manager *m, pid_t pid) {
1447         _cleanup_free_ char *cgroup = NULL;
1448         int r;
1449
1450         assert(m);
1451
1452         if (pid <= 0)
1453                 return NULL;
1454
1455         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
1456         if (r < 0)
1457                 return NULL;
1458
1459         return manager_get_unit_by_cgroup(m, cgroup);
1460 }
1461
1462 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
1463         Unit *u;
1464
1465         assert(m);
1466
1467         if (pid <= 0)
1468                 return NULL;
1469
1470         if (pid == 1)
1471                 return hashmap_get(m->units, SPECIAL_INIT_SCOPE);
1472
1473         u = hashmap_get(m->watch_pids1, PID_TO_PTR(pid));
1474         if (u)
1475                 return u;
1476
1477         u = hashmap_get(m->watch_pids2, PID_TO_PTR(pid));
1478         if (u)
1479                 return u;
1480
1481         return manager_get_unit_by_pid_cgroup(m, pid);
1482 }
1483
1484 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
1485         Unit *u;
1486
1487         assert(m);
1488         assert(cgroup);
1489
1490         u = manager_get_unit_by_cgroup(m, cgroup);
1491         if (!u)
1492                 return 0;
1493
1494         return unit_notify_cgroup_empty(u);
1495 }
1496
1497 int unit_get_memory_current(Unit *u, uint64_t *ret) {
1498         _cleanup_free_ char *v = NULL;
1499         int r;
1500
1501         assert(u);
1502         assert(ret);
1503
1504         if (!u->cgroup_path)
1505                 return -ENODATA;
1506
1507         if ((u->cgroup_realized_mask & CGROUP_MASK_MEMORY) == 0)
1508                 return -ENODATA;
1509
1510         if (cg_unified() <= 0)
1511                 r = cg_get_attribute("memory", u->cgroup_path, "memory.usage_in_bytes", &v);
1512         else
1513                 r = cg_get_attribute("memory", u->cgroup_path, "memory.current", &v);
1514         if (r == -ENOENT)
1515                 return -ENODATA;
1516         if (r < 0)
1517                 return r;
1518
1519         return safe_atou64(v, ret);
1520 }
1521
1522 int unit_get_tasks_current(Unit *u, uint64_t *ret) {
1523         _cleanup_free_ char *v = NULL;
1524         int r;
1525
1526         assert(u);
1527         assert(ret);
1528
1529         if (!u->cgroup_path)
1530                 return -ENODATA;
1531
1532         if ((u->cgroup_realized_mask & CGROUP_MASK_PIDS) == 0)
1533                 return -ENODATA;
1534
1535         r = cg_get_attribute("pids", u->cgroup_path, "pids.current", &v);
1536         if (r == -ENOENT)
1537                 return -ENODATA;
1538         if (r < 0)
1539                 return r;
1540
1541         return safe_atou64(v, ret);
1542 }
1543
1544 static int unit_get_cpu_usage_raw(Unit *u, nsec_t *ret) {
1545         _cleanup_free_ char *v = NULL;
1546         uint64_t ns;
1547         int r;
1548
1549         assert(u);
1550         assert(ret);
1551
1552         if (!u->cgroup_path)
1553                 return -ENODATA;
1554
1555         if ((u->cgroup_realized_mask & CGROUP_MASK_CPUACCT) == 0)
1556                 return -ENODATA;
1557
1558         r = cg_get_attribute("cpuacct", u->cgroup_path, "cpuacct.usage", &v);
1559         if (r == -ENOENT)
1560                 return -ENODATA;
1561         if (r < 0)
1562                 return r;
1563
1564         r = safe_atou64(v, &ns);
1565         if (r < 0)
1566                 return r;
1567
1568         *ret = ns;
1569         return 0;
1570 }
1571
1572 int unit_get_cpu_usage(Unit *u, nsec_t *ret) {
1573         nsec_t ns;
1574         int r;
1575
1576         r = unit_get_cpu_usage_raw(u, &ns);
1577         if (r < 0)
1578                 return r;
1579
1580         if (ns > u->cpuacct_usage_base)
1581                 ns -= u->cpuacct_usage_base;
1582         else
1583                 ns = 0;
1584
1585         *ret = ns;
1586         return 0;
1587 }
1588
1589 int unit_reset_cpu_usage(Unit *u) {
1590         nsec_t ns;
1591         int r;
1592
1593         assert(u);
1594
1595         r = unit_get_cpu_usage_raw(u, &ns);
1596         if (r < 0) {
1597                 u->cpuacct_usage_base = 0;
1598                 return r;
1599         }
1600
1601         u->cpuacct_usage_base = ns;
1602         return 0;
1603 }
1604
1605 bool unit_cgroup_delegate(Unit *u) {
1606         CGroupContext *c;
1607
1608         assert(u);
1609
1610         c = unit_get_cgroup_context(u);
1611         if (!c)
1612                 return false;
1613
1614         return c->delegate;
1615 }
1616
1617 void unit_invalidate_cgroup(Unit *u, CGroupMask m) {
1618         assert(u);
1619
1620         if (!UNIT_HAS_CGROUP_CONTEXT(u))
1621                 return;
1622
1623         if (m == 0)
1624                 return;
1625
1626         if ((u->cgroup_realized_mask & m) == 0)
1627                 return;
1628
1629         u->cgroup_realized_mask &= ~m;
1630         unit_add_to_cgroup_queue(u);
1631 }
1632
1633 void manager_invalidate_startup_units(Manager *m) {
1634         Iterator i;
1635         Unit *u;
1636
1637         assert(m);
1638
1639         SET_FOREACH(u, m->startup_units, i)
1640                 unit_invalidate_cgroup(u, CGROUP_MASK_CPU|CGROUP_MASK_BLKIO);
1641 }
1642
1643 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
1644         [CGROUP_AUTO] = "auto",
1645         [CGROUP_CLOSED] = "closed",
1646         [CGROUP_STRICT] = "strict",
1647 };
1648
1649 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);
1650 #endif // 0