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