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