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