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