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