chiark / gitweb /
156118b4a675729429621db7779bbd3e9da1b4fb
[elogind.git] / src / basic / cgroup-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2010 Lennart Poettering
6 ***/
7
8 #include <dirent.h>
9 #include <errno.h>
10 #include <ftw.h>
11 //#include <limits.h>
12 #include <signal.h>
13 //#include <stddef.h>
14 #include <stdio_ext.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <sys/stat.h>
18 //#include <sys/statfs.h>
19 #include <sys/types.h>
20 #include <sys/xattr.h>
21 #include <unistd.h>
22
23 #include "alloc-util.h"
24 #include "cgroup-util.h"
25 //#include "def.h"
26 #include "dirent-util.h"
27 #include "extract-word.h"
28 #include "fd-util.h"
29 #include "fileio.h"
30 #include "format-util.h"
31 #include "fs-util.h"
32 //#include "log.h"
33 #include "login-util.h"
34 #include "macro.h"
35 //#include "missing.h"
36 #include "mkdir.h"
37 #include "parse-util.h"
38 #include "path-util.h"
39 #include "proc-cmdline.h"
40 #include "process-util.h"
41 #include "set.h"
42 //#include "special.h"
43 #include "stat-util.h"
44 #include "stdio-util.h"
45 #include "string-table.h"
46 #include "string-util.h"
47 #include "strv.h"
48 #include "unit-name.h"
49 #include "user-util.h"
50
51 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
52         _cleanup_free_ char *fs = NULL;
53         FILE *f;
54         int r;
55
56         assert(_f);
57
58         r = cg_get_path(controller, path, "cgroup.procs", &fs);
59         if (r < 0)
60                 return r;
61
62         f = fopen(fs, "re");
63         if (!f)
64                 return -errno;
65
66         *_f = f;
67         return 0;
68 }
69
70 int cg_read_pid(FILE *f, pid_t *_pid) {
71         unsigned long ul;
72
73         /* Note that the cgroup.procs might contain duplicates! See
74          * cgroups.txt for details. */
75
76         assert(f);
77         assert(_pid);
78
79         errno = 0;
80         if (fscanf(f, "%lu", &ul) != 1) {
81
82                 if (feof(f))
83                         return 0;
84
85                 return errno > 0 ? -errno : -EIO;
86         }
87
88         if (ul <= 0)
89                 return -EIO;
90
91         *_pid = (pid_t) ul;
92         return 1;
93 }
94
95 int cg_read_event(
96                 const char *controller,
97                 const char *path,
98                 const char *event,
99                 char **val) {
100
101         _cleanup_free_ char *events = NULL, *content = NULL;
102         char *p, *line;
103         int r;
104
105         r = cg_get_path(controller, path, "cgroup.events", &events);
106         if (r < 0)
107                 return r;
108
109         r = read_full_file(events, &content, NULL);
110         if (r < 0)
111                 return r;
112
113         p = content;
114         while ((line = strsep(&p, "\n"))) {
115                 char *key;
116
117                 key = strsep(&line, " ");
118                 if (!key || !line)
119                         return -EINVAL;
120
121                 if (strcmp(key, event))
122                         continue;
123
124                 *val = strdup(line);
125                 return 0;
126         }
127
128         return -ENOENT;
129 }
130
131 #if 0 /// UNNEEDED by elogind
132 bool cg_ns_supported(void) {
133         static thread_local int enabled = -1;
134
135         if (enabled >= 0)
136                 return enabled;
137
138         if (access("/proc/self/ns/cgroup", F_OK) == 0)
139                 enabled = 1;
140         else
141                 enabled = 0;
142
143         return enabled;
144 }
145 #endif // 0
146
147 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
148         _cleanup_free_ char *fs = NULL;
149         int r;
150         DIR *d;
151
152         assert(_d);
153
154         /* This is not recursive! */
155
156         r = cg_get_path(controller, path, NULL, &fs);
157         if (r < 0)
158                 return r;
159
160         d = opendir(fs);
161         if (!d)
162                 return -errno;
163
164         *_d = d;
165         return 0;
166 }
167
168 int cg_read_subgroup(DIR *d, char **fn) {
169         struct dirent *de;
170
171         assert(d);
172         assert(fn);
173
174         FOREACH_DIRENT_ALL(de, d, return -errno) {
175                 char *b;
176
177                 if (de->d_type != DT_DIR)
178                         continue;
179
180                 if (dot_or_dot_dot(de->d_name))
181                         continue;
182
183                 b = strdup(de->d_name);
184                 if (!b)
185                         return -ENOMEM;
186
187                 *fn = b;
188                 return 1;
189         }
190
191         return 0;
192 }
193
194 int cg_rmdir(const char *controller, const char *path) {
195         _cleanup_free_ char *p = NULL;
196         int r;
197
198         r = cg_get_path(controller, path, NULL, &p);
199         if (r < 0)
200                 return r;
201
202         r = rmdir(p);
203         if (r < 0 && errno != ENOENT)
204                 return -errno;
205
206         r = cg_hybrid_unified();
207         if (r < 0)
208                 return r;
209         if (r == 0)
210                 return 0;
211
212         if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
213                 r = cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
214                 if (r < 0)
215                         log_warning_errno(r, "Failed to remove compat systemd cgroup %s: %m", path);
216         }
217
218         return 0;
219 }
220
221 int cg_kill(
222                 const char *controller,
223                 const char *path,
224                 int sig,
225                 CGroupFlags flags,
226                 Set *s,
227                 cg_kill_log_func_t log_kill,
228                 void *userdata) {
229
230         _cleanup_set_free_ Set *allocated_set = NULL;
231         bool done = false;
232         int r, ret = 0;
233         pid_t my_pid;
234
235         assert(sig >= 0);
236
237          /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
238           * SIGCONT on SIGKILL. */
239         if (IN_SET(sig, SIGCONT, SIGKILL))
240                 flags &= ~CGROUP_SIGCONT;
241
242         /* This goes through the tasks list and kills them all. This
243          * is repeated until no further processes are added to the
244          * tasks list, to properly handle forking processes */
245
246         if (!s) {
247                 s = allocated_set = set_new(NULL);
248                 if (!s)
249                         return -ENOMEM;
250         }
251
252         my_pid = getpid_cached();
253
254         do {
255                 _cleanup_fclose_ FILE *f = NULL;
256                 pid_t pid = 0;
257                 done = true;
258
259                 r = cg_enumerate_processes(controller, path, &f);
260                 if (r < 0) {
261                         if (ret >= 0 && r != -ENOENT)
262                                 return r;
263
264                         return ret;
265                 }
266
267                 while ((r = cg_read_pid(f, &pid)) > 0) {
268
269                         if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
270                                 continue;
271
272                         if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
273                                 continue;
274
275                         if (log_kill)
276                                 log_kill(pid, sig, userdata);
277
278                         /* If we haven't killed this process yet, kill
279                          * it */
280                         if (kill(pid, sig) < 0) {
281                                 if (ret >= 0 && errno != ESRCH)
282                                         ret = -errno;
283                         } else {
284                                 if (flags & CGROUP_SIGCONT)
285                                         (void) kill(pid, SIGCONT);
286
287                                 if (ret == 0)
288                                         ret = 1;
289                         }
290
291                         done = false;
292
293                         r = set_put(s, PID_TO_PTR(pid));
294                         if (r < 0) {
295                                 if (ret >= 0)
296                                         return r;
297
298                                 return ret;
299                         }
300                 }
301
302                 if (r < 0) {
303                         if (ret >= 0)
304                                 return r;
305
306                         return ret;
307                 }
308
309                 /* To avoid racing against processes which fork
310                  * quicker than we can kill them we repeat this until
311                  * no new pids need to be killed. */
312
313         } while (!done);
314
315         return ret;
316 }
317
318 int cg_kill_recursive(
319                 const char *controller,
320                 const char *path,
321                 int sig,
322                 CGroupFlags flags,
323                 Set *s,
324                 cg_kill_log_func_t log_kill,
325                 void *userdata) {
326
327         _cleanup_set_free_ Set *allocated_set = NULL;
328         _cleanup_closedir_ DIR *d = NULL;
329         int r, ret;
330         char *fn;
331
332         assert(path);
333         assert(sig >= 0);
334
335         if (!s) {
336                 s = allocated_set = set_new(NULL);
337                 if (!s)
338                         return -ENOMEM;
339         }
340
341         ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
342
343         r = cg_enumerate_subgroups(controller, path, &d);
344         if (r < 0) {
345                 if (ret >= 0 && r != -ENOENT)
346                         return r;
347
348                 return ret;
349         }
350
351         while ((r = cg_read_subgroup(d, &fn)) > 0) {
352                 _cleanup_free_ char *p = NULL;
353
354                 p = strjoin(path, "/", fn);
355                 free(fn);
356                 if (!p)
357                         return -ENOMEM;
358
359                 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
360                 if (r != 0 && ret >= 0)
361                         ret = r;
362         }
363         if (ret >= 0 && r < 0)
364                 ret = r;
365
366         if (flags & CGROUP_REMOVE) {
367                 r = cg_rmdir(controller, path);
368                 if (r < 0 && ret >= 0 && !IN_SET(r, -ENOENT, -EBUSY))
369                         return r;
370         }
371
372         return ret;
373 }
374
375 int cg_migrate(
376                 const char *cfrom,
377                 const char *pfrom,
378                 const char *cto,
379                 const char *pto,
380                 CGroupFlags flags) {
381
382         bool done = false;
383         _cleanup_set_free_ Set *s = NULL;
384         int r, ret = 0;
385         pid_t my_pid;
386
387         assert(cfrom);
388         assert(pfrom);
389         assert(cto);
390         assert(pto);
391
392         s = set_new(NULL);
393         if (!s)
394                 return -ENOMEM;
395
396         my_pid = getpid_cached();
397
398         log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
399                           cfrom, pfrom, cto, pto,
400                           (flags & CGROUP_IGNORE_SELF)
401                           ? "ignoring self" : "watching self");
402         do {
403                 _cleanup_fclose_ FILE *f = NULL;
404                 pid_t pid = 0;
405                 done = true;
406
407                 r = cg_enumerate_processes(cfrom, pfrom, &f);
408                 if (r < 0) {
409                         if (ret >= 0 && r != -ENOENT)
410                                 return r;
411
412                         return ret;
413                 }
414
415                 while ((r = cg_read_pid(f, &pid)) > 0) {
416
417                         /* This might do weird stuff if we aren't a
418                          * single-threaded program. However, we
419                          * luckily know we are not */
420                         if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
421                                 continue;
422
423                         if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
424                                 continue;
425
426                         /* Ignore kernel threads. Since they can only
427                          * exist in the root cgroup, we only check for
428                          * them there. */
429                         if (cfrom &&
430                             empty_or_root(pfrom) &&
431                             is_kernel_thread(pid) > 0)
432                                 continue;
433
434                         r = cg_attach(cto, pto, pid);
435                         if (r < 0) {
436                                 if (ret >= 0 && r != -ESRCH)
437                                         ret = r;
438                         } else if (ret == 0)
439                                 ret = 1;
440
441                         done = false;
442
443                         r = set_put(s, PID_TO_PTR(pid));
444                         if (r < 0) {
445                                 if (ret >= 0)
446                                         return r;
447
448                                 return ret;
449                         }
450                 }
451
452                 if (r < 0) {
453                         if (ret >= 0)
454                                 return r;
455
456                         return ret;
457                 }
458         } while (!done);
459
460         return ret;
461 }
462
463 int cg_migrate_recursive(
464                 const char *cfrom,
465                 const char *pfrom,
466                 const char *cto,
467                 const char *pto,
468                 CGroupFlags flags) {
469
470         _cleanup_closedir_ DIR *d = NULL;
471         int r, ret = 0;
472         char *fn;
473
474         assert(cfrom);
475         assert(pfrom);
476         assert(cto);
477         assert(pto);
478
479         ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
480
481         r = cg_enumerate_subgroups(cfrom, pfrom, &d);
482         if (r < 0) {
483                 if (ret >= 0 && r != -ENOENT)
484                         return r;
485
486                 return ret;
487         }
488
489         while ((r = cg_read_subgroup(d, &fn)) > 0) {
490                 _cleanup_free_ char *p = NULL;
491
492                 p = strjoin(pfrom, "/", fn);
493                 free(fn);
494                 if (!p)
495                         return -ENOMEM;
496
497                 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
498                 if (r != 0 && ret >= 0)
499                         ret = r;
500         }
501
502         if (r < 0 && ret >= 0)
503                 ret = r;
504
505         if (flags & CGROUP_REMOVE) {
506                 r = cg_rmdir(cfrom, pfrom);
507                 if (r < 0 && ret >= 0 && !IN_SET(r, -ENOENT, -EBUSY))
508                         return r;
509         }
510
511         return ret;
512 }
513
514 int cg_migrate_recursive_fallback(
515                 const char *cfrom,
516                 const char *pfrom,
517                 const char *cto,
518                 const char *pto,
519                 CGroupFlags flags) {
520
521         int r;
522
523         assert(cfrom);
524         assert(pfrom);
525         assert(cto);
526         assert(pto);
527
528         r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
529         if (r < 0) {
530                 char prefix[strlen(pto) + 1];
531
532                 /* This didn't work? Then let's try all prefixes of the destination */
533
534                 PATH_FOREACH_PREFIX(prefix, pto) {
535                         int q;
536
537                         q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
538                         if (q >= 0)
539                                 return q;
540                 }
541         }
542
543         return r;
544 }
545
546 static const char *controller_to_dirname(const char *controller) {
547         const char *e;
548
549         assert(controller);
550
551         /* Converts a controller name to the directory name below
552          * /sys/fs/cgroup/ we want to mount it to. Effectively, this
553          * just cuts off the name= prefixed used for named
554          * hierarchies, if it is specified. */
555
556         if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
557                 if (cg_hybrid_unified() > 0)
558                         controller = SYSTEMD_CGROUP_CONTROLLER_HYBRID;
559                 else
560                         controller = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
561         }
562
563         e = startswith(controller, "name=");
564         if (e)
565                 return e;
566
567         return controller;
568 }
569
570 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
571         const char *dn;
572         char *t = NULL;
573
574         assert(fs);
575         assert(controller);
576
577         dn = controller_to_dirname(controller);
578
579         if (isempty(path) && isempty(suffix))
580                 t = strappend("/sys/fs/cgroup/", dn);
581         else if (isempty(path))
582                 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix);
583         else if (isempty(suffix))
584                 t = strjoin("/sys/fs/cgroup/", dn, "/", path);
585         else
586                 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix);
587         if (!t)
588                 return -ENOMEM;
589
590         *fs = t;
591         return 0;
592 }
593
594 static int join_path_unified(const char *path, const char *suffix, char **fs) {
595         char *t;
596
597         assert(fs);
598
599         if (isempty(path) && isempty(suffix))
600                 t = strdup("/sys/fs/cgroup");
601         else if (isempty(path))
602                 t = strappend("/sys/fs/cgroup/", suffix);
603         else if (isempty(suffix))
604                 t = strappend("/sys/fs/cgroup/", path);
605         else
606                 t = strjoin("/sys/fs/cgroup/", path, "/", suffix);
607         if (!t)
608                 return -ENOMEM;
609
610         *fs = t;
611         return 0;
612 }
613
614 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
615         int r;
616
617         assert(fs);
618
619         if (!controller) {
620                 char *t;
621
622                 /* If no controller is specified, we return the path
623                  * *below* the controllers, without any prefix. */
624
625                 if (!path && !suffix)
626                         return -EINVAL;
627
628                 if (!suffix)
629                         t = strdup(path);
630                 else if (!path)
631                         t = strdup(suffix);
632                 else
633                         t = strjoin(path, "/", suffix);
634                 if (!t)
635                         return -ENOMEM;
636
637                 *fs = path_simplify(t, false);
638                 return 0;
639         }
640
641         if (!cg_controller_is_valid(controller))
642                 return -EINVAL;
643
644         r = cg_all_unified();
645         if (r < 0)
646                 return r;
647         if (r > 0)
648                 r = join_path_unified(path, suffix, fs);
649         else
650                 r = join_path_legacy(controller, path, suffix, fs);
651         if (r < 0)
652                 return r;
653
654         path_simplify(*fs, false);
655         return 0;
656 }
657
658 static int controller_is_accessible(const char *controller) {
659         int r;
660
661         assert(controller);
662
663         /* Checks whether a specific controller is accessible,
664          * i.e. its hierarchy mounted. In the unified hierarchy all
665          * controllers are considered accessible, except for the named
666          * hierarchies */
667
668         if (!cg_controller_is_valid(controller))
669                 return -EINVAL;
670
671         r = cg_all_unified();
672         if (r < 0)
673                 return r;
674         if (r > 0) {
675                 /* We don't support named hierarchies if we are using
676                  * the unified hierarchy. */
677
678                 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
679                         return 0;
680
681                 if (startswith(controller, "name="))
682                         return -EOPNOTSUPP;
683
684         } else {
685                 const char *cc, *dn;
686
687                 dn = controller_to_dirname(controller);
688                 cc = strjoina("/sys/fs/cgroup/", dn);
689
690                 if (laccess(cc, F_OK) < 0)
691                         return -errno;
692         }
693
694         return 0;
695 }
696
697 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
698         int r;
699
700         assert(controller);
701         assert(fs);
702
703         /* Check if the specified controller is actually accessible */
704         r = controller_is_accessible(controller);
705         if (r < 0)
706                 return r;
707
708         return cg_get_path(controller, path, suffix, fs);
709 }
710
711 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
712         assert(path);
713         assert(sb);
714         assert(ftwbuf);
715
716         if (typeflag != FTW_DP)
717                 return 0;
718
719         if (ftwbuf->level < 1)
720                 return 0;
721
722         (void) rmdir(path);
723         return 0;
724 }
725
726 int cg_trim(const char *controller, const char *path, bool delete_root) {
727         _cleanup_free_ char *fs = NULL;
728         int r = 0, q;
729
730         assert(path);
731
732         r = cg_get_path(controller, path, NULL, &fs);
733         if (r < 0)
734                 return r;
735
736         errno = 0;
737         if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
738                 if (errno == ENOENT)
739                         r = 0;
740                 else if (errno > 0)
741                         r = -errno;
742                 else
743                         r = -EIO;
744         }
745
746         if (delete_root) {
747                 if (rmdir(fs) < 0 && errno != ENOENT)
748                         return -errno;
749         }
750
751         q = cg_hybrid_unified();
752         if (q < 0)
753                 return q;
754         if (q > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
755                 q = cg_trim(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, delete_root);
756                 if (q < 0)
757                         log_warning_errno(q, "Failed to trim compat systemd cgroup %s: %m", path);
758         }
759
760         return r;
761 }
762
763 /* Create a cgroup in the hierarchy of controller.
764  * Returns 0 if the group already existed, 1 on success, negative otherwise.
765  */
766 int cg_create(const char *controller, const char *path) {
767         _cleanup_free_ char *fs = NULL;
768         int r;
769
770         r = cg_get_path_and_check(controller, path, NULL, &fs);
771         if (r < 0)
772                 return r;
773
774         r = mkdir_parents(fs, 0755);
775         if (r < 0)
776                 return r;
777
778         r = mkdir_errno_wrapper(fs, 0755);
779         if (r == -EEXIST)
780                 return 0;
781         if (r < 0)
782                 return r;
783
784         r = cg_hybrid_unified();
785         if (r < 0)
786                 return r;
787
788         if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
789                 r = cg_create(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
790                 if (r < 0)
791                         log_warning_errno(r, "Failed to create compat systemd cgroup %s: %m", path);
792         }
793
794         return 1;
795 }
796
797 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
798         int r, q;
799
800         assert(pid >= 0);
801
802         r = cg_create(controller, path);
803         if (r < 0)
804                 return r;
805
806         q = cg_attach(controller, path, pid);
807         if (q < 0)
808                 return q;
809
810         /* This does not remove the cgroup on failure */
811         return r;
812 }
813
814 int cg_attach(const char *controller, const char *path, pid_t pid) {
815         _cleanup_free_ char *fs = NULL;
816         char c[DECIMAL_STR_MAX(pid_t) + 2];
817         int r;
818
819         assert(path);
820         assert(pid >= 0);
821
822         r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
823         if (r < 0)
824                 return r;
825
826         if (pid == 0)
827                 pid = getpid_cached();
828
829         xsprintf(c, PID_FMT "\n", pid);
830
831         r = write_string_file(fs, c, 0);
832         if (r < 0)
833                 return r;
834
835         r = cg_hybrid_unified();
836         if (r < 0)
837                 return r;
838
839         if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
840                 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, pid);
841                 if (r < 0)
842                         log_warning_errno(r, "Failed to attach "PID_FMT" to compat systemd cgroup %s: %m", pid, path);
843         }
844
845         return 0;
846 }
847
848 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
849         int r;
850
851         assert(controller);
852         assert(path);
853         assert(pid >= 0);
854
855         r = cg_attach(controller, path, pid);
856         if (r < 0) {
857                 char prefix[strlen(path) + 1];
858
859                 /* This didn't work? Then let's try all prefixes of
860                  * the destination */
861
862                 PATH_FOREACH_PREFIX(prefix, path) {
863                         int q;
864
865                         q = cg_attach(controller, prefix, pid);
866                         if (q >= 0)
867                                 return q;
868                 }
869         }
870
871         return r;
872 }
873
874 #if 0 /// UNNEEDED by elogind
875 int cg_set_access(
876                 const char *controller,
877                 const char *path,
878                 uid_t uid,
879                 gid_t gid) {
880
881         struct Attribute {
882                 const char *name;
883                 bool fatal;
884         };
885
886         /* cgroupsv1, aka legacy/non-unified */
887         static const struct Attribute legacy_attributes[] = {
888                 { "cgroup.procs",           true  },
889                 { "tasks",                  false },
890                 { "cgroup.clone_children",  false },
891                 {},
892         };
893
894         /* cgroupsv2, aka unified */
895         static const struct Attribute unified_attributes[] = {
896                 { "cgroup.procs",           true  },
897                 { "cgroup.subtree_control", true  },
898                 { "cgroup.threads",         false },
899                 {},
900         };
901
902         static const struct Attribute* const attributes[] = {
903                 [false] = legacy_attributes,
904                 [true]  = unified_attributes,
905         };
906
907         _cleanup_free_ char *fs = NULL;
908         const struct Attribute *i;
909         int r, unified;
910
911         assert(path);
912
913         if (uid == UID_INVALID && gid == GID_INVALID)
914                 return 0;
915
916         unified = cg_unified_controller(controller);
917         if (unified < 0)
918                 return unified;
919
920         /* Configure access to the cgroup itself */
921         r = cg_get_path(controller, path, NULL, &fs);
922         if (r < 0)
923                 return r;
924
925         r = chmod_and_chown(fs, 0755, uid, gid);
926         if (r < 0)
927                 return r;
928
929         /* Configure access to the cgroup's attributes */
930         for (i = attributes[unified]; i->name; i++) {
931                 fs = mfree(fs);
932
933                 r = cg_get_path(controller, path, i->name, &fs);
934                 if (r < 0)
935                         return r;
936
937                 r = chmod_and_chown(fs, 0644, uid, gid);
938                 if (r < 0) {
939                         if (i->fatal)
940                                 return r;
941
942                         log_debug_errno(r, "Failed to set access on cgroup %s, ignoring: %m", fs);
943                 }
944         }
945
946         if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
947                 r = cg_hybrid_unified();
948                 if (r < 0)
949                         return r;
950                 if (r > 0) {
951                         /* Always propagate access mode from unified to legacy controller */
952                         r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, uid, gid);
953                         if (r < 0)
954                                 log_debug_errno(r, "Failed to set access on compatibility elogind cgroup %s, ignoring: %m", path);
955                 }
956         }
957
958         return 0;
959 }
960
961 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
962         _cleanup_free_ char *fs = NULL;
963         int r;
964
965         assert(path);
966         assert(name);
967         assert(value || size <= 0);
968
969         r = cg_get_path(controller, path, NULL, &fs);
970         if (r < 0)
971                 return r;
972
973         if (setxattr(fs, name, value, size, flags) < 0)
974                 return -errno;
975
976         return 0;
977 }
978
979 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
980         _cleanup_free_ char *fs = NULL;
981         ssize_t n;
982         int r;
983
984         assert(path);
985         assert(name);
986
987         r = cg_get_path(controller, path, NULL, &fs);
988         if (r < 0)
989                 return r;
990
991         n = getxattr(fs, name, value, size);
992         if (n < 0)
993                 return -errno;
994
995         return (int) n;
996 }
997 #endif // 0
998
999 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
1000         _cleanup_fclose_ FILE *f = NULL;
1001         char line[LINE_MAX];
1002 #if 0 /// At elogind we do not want that (false alarm) "maybe uninitialized" warning
1003         const char *fs, *controller_str;
1004 #else
1005         const char *fs, *controller_str = NULL;
1006 #endif // 0
1007         size_t cs = 0;
1008         int unified;
1009
1010         assert(path);
1011         assert(pid >= 0);
1012
1013         if (controller) {
1014                 if (!cg_controller_is_valid(controller))
1015                         return -EINVAL;
1016         } else
1017                 controller = SYSTEMD_CGROUP_CONTROLLER;
1018
1019         unified = cg_unified_controller(controller);
1020         if (unified < 0)
1021                 return unified;
1022         if (unified == 0) {
1023                 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
1024                         controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
1025                 else
1026                         controller_str = controller;
1027
1028                 cs = strlen(controller_str);
1029         }
1030
1031         fs = procfs_file_alloca(pid, "cgroup");
1032         log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
1033                           pid, fs, controller);
1034         f = fopen(fs, "re");
1035         if (!f)
1036                 return errno == ENOENT ? -ESRCH : -errno;
1037
1038         (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1039
1040         FOREACH_LINE(line, f, return -errno) {
1041                 char *e, *p;
1042
1043                 truncate_nl(line);
1044
1045                 if (unified) {
1046                         e = startswith(line, "0:");
1047                         if (!e)
1048                                 continue;
1049
1050                         e = strchr(e, ':');
1051                         if (!e)
1052                                 continue;
1053                 } else {
1054                         char *l;
1055                         size_t k;
1056                         const char *word, *state;
1057                         bool found = false;
1058
1059                         l = strchr(line, ':');
1060                         if (!l)
1061                                 continue;
1062
1063                         l++;
1064                         e = strchr(l, ':');
1065                         if (!e)
1066                                 continue;
1067
1068                         *e = 0;
1069                         FOREACH_WORD_SEPARATOR(word, k, l, ",", state)
1070                                 if (k == cs && memcmp(word, controller_str, cs) == 0) {
1071                                         found = true;
1072                                         break;
1073                                 }
1074                         if (!found)
1075                                 continue;
1076                 }
1077
1078                 log_debug_elogind("Found %s:%s", line, e+1);
1079                 p = strdup(e + 1);
1080                 if (!p)
1081                         return -ENOMEM;
1082
1083                 /* Truncate suffix indicating the process is a zombie */
1084                 e = endswith(p, " (deleted)");
1085                 if (e)
1086                         *e = 0;
1087
1088                 *path = p;
1089                 return 0;
1090         }
1091
1092         return -ENODATA;
1093 }
1094
1095 #if 0 /// UNNEEDED by elogind
1096 int cg_install_release_agent(const char *controller, const char *agent) {
1097         _cleanup_free_ char *fs = NULL, *contents = NULL;
1098         const char *sc;
1099         int r;
1100
1101         assert(agent);
1102
1103         r = cg_unified_controller(controller);
1104         if (r < 0)
1105                 return r;
1106         if (r > 0) /* doesn't apply to unified hierarchy */
1107                 return -EOPNOTSUPP;
1108
1109         r = cg_get_path(controller, NULL, "release_agent", &fs);
1110         if (r < 0)
1111                 return r;
1112
1113         r = read_one_line_file(fs, &contents);
1114         if (r < 0)
1115                 return r;
1116
1117         sc = strstrip(contents);
1118         if (isempty(sc)) {
1119                 r = write_string_file(fs, agent, 0);
1120                 if (r < 0)
1121                         return r;
1122         } else if (!path_equal(sc, agent))
1123                 return -EEXIST;
1124
1125         fs = mfree(fs);
1126         r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1127         if (r < 0)
1128                 return r;
1129
1130         contents = mfree(contents);
1131         r = read_one_line_file(fs, &contents);
1132         if (r < 0)
1133                 return r;
1134
1135         sc = strstrip(contents);
1136         if (streq(sc, "0")) {
1137                 r = write_string_file(fs, "1", 0);
1138                 if (r < 0)
1139                         return r;
1140
1141                 return 1;
1142         }
1143
1144         if (!streq(sc, "1"))
1145                 return -EIO;
1146
1147         return 0;
1148 }
1149
1150 int cg_uninstall_release_agent(const char *controller) {
1151         _cleanup_free_ char *fs = NULL;
1152         int r;
1153
1154         r = cg_unified_controller(controller);
1155         if (r < 0)
1156                 return r;
1157         if (r > 0) /* Doesn't apply to unified hierarchy */
1158                 return -EOPNOTSUPP;
1159
1160         r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1161         if (r < 0)
1162                 return r;
1163
1164         r = write_string_file(fs, "0", 0);
1165         if (r < 0)
1166                 return r;
1167
1168         fs = mfree(fs);
1169
1170         r = cg_get_path(controller, NULL, "release_agent", &fs);
1171         if (r < 0)
1172                 return r;
1173
1174         r = write_string_file(fs, "", 0);
1175         if (r < 0)
1176                 return r;
1177
1178         return 0;
1179 }
1180 #endif // 0
1181
1182 int cg_is_empty(const char *controller, const char *path) {
1183         _cleanup_fclose_ FILE *f = NULL;
1184         pid_t pid;
1185         int r;
1186
1187         assert(path);
1188
1189         r = cg_enumerate_processes(controller, path, &f);
1190         if (r == -ENOENT)
1191                 return 1;
1192         if (r < 0)
1193                 return r;
1194
1195         r = cg_read_pid(f, &pid);
1196         if (r < 0)
1197                 return r;
1198
1199         return r == 0;
1200 }
1201
1202 int cg_is_empty_recursive(const char *controller, const char *path) {
1203         int r;
1204
1205         assert(path);
1206
1207         /* The root cgroup is always populated */
1208         if (controller && empty_or_root(path))
1209                 return false;
1210
1211         r = cg_unified_controller(controller);
1212         if (r < 0)
1213                 return r;
1214         if (r > 0) {
1215                 _cleanup_free_ char *t = NULL;
1216
1217                 /* On the unified hierarchy we can check empty state
1218                  * via the "populated" attribute of "cgroup.events". */
1219
1220                 r = cg_read_event(controller, path, "populated", &t);
1221                 if (r < 0)
1222                         return r;
1223
1224                 return streq(t, "0");
1225         } else {
1226                 _cleanup_closedir_ DIR *d = NULL;
1227                 char *fn;
1228
1229                 r = cg_is_empty(controller, path);
1230                 if (r <= 0)
1231                         return r;
1232
1233                 r = cg_enumerate_subgroups(controller, path, &d);
1234                 if (r == -ENOENT)
1235                         return 1;
1236                 if (r < 0)
1237                         return r;
1238
1239                 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1240                         _cleanup_free_ char *p = NULL;
1241
1242                         p = strjoin(path, "/", fn);
1243                         free(fn);
1244                         if (!p)
1245                                 return -ENOMEM;
1246
1247                         r = cg_is_empty_recursive(controller, p);
1248                         if (r <= 0)
1249                                 return r;
1250                 }
1251                 if (r < 0)
1252                         return r;
1253
1254                 return true;
1255         }
1256 }
1257
1258 int cg_split_spec(const char *spec, char **controller, char **path) {
1259         char *t = NULL, *u = NULL;
1260         const char *e;
1261
1262         assert(spec);
1263
1264         if (*spec == '/') {
1265                 if (!path_is_normalized(spec))
1266                         return -EINVAL;
1267
1268                 if (path) {
1269                         t = strdup(spec);
1270                         if (!t)
1271                                 return -ENOMEM;
1272
1273                         *path = path_simplify(t, false);
1274                 }
1275
1276                 if (controller)
1277                         *controller = NULL;
1278
1279                 return 0;
1280         }
1281
1282         e = strchr(spec, ':');
1283         if (!e) {
1284                 if (!cg_controller_is_valid(spec))
1285                         return -EINVAL;
1286
1287                 if (controller) {
1288                         t = strdup(spec);
1289                         if (!t)
1290                                 return -ENOMEM;
1291
1292                         *controller = t;
1293                 }
1294
1295                 if (path)
1296                         *path = NULL;
1297
1298                 return 0;
1299         }
1300
1301         t = strndup(spec, e-spec);
1302         if (!t)
1303                 return -ENOMEM;
1304         if (!cg_controller_is_valid(t)) {
1305                 free(t);
1306                 return -EINVAL;
1307         }
1308
1309         if (isempty(e+1))
1310                 u = NULL;
1311         else {
1312                 u = strdup(e+1);
1313                 if (!u) {
1314                         free(t);
1315                         return -ENOMEM;
1316                 }
1317
1318                 if (!path_is_normalized(u) ||
1319                     !path_is_absolute(u)) {
1320                         free(t);
1321                         free(u);
1322                         return -EINVAL;
1323                 }
1324
1325                 path_simplify(u, false);
1326         }
1327
1328         if (controller)
1329                 *controller = t;
1330         else
1331                 free(t);
1332
1333         if (path)
1334                 *path = u;
1335         else
1336                 free(u);
1337
1338         return 0;
1339 }
1340
1341 int cg_mangle_path(const char *path, char **result) {
1342         _cleanup_free_ char *c = NULL, *p = NULL;
1343         char *t;
1344         int r;
1345
1346         assert(path);
1347         assert(result);
1348
1349         /* First, check if it already is a filesystem path */
1350         if (path_startswith(path, "/sys/fs/cgroup")) {
1351
1352                 t = strdup(path);
1353                 if (!t)
1354                         return -ENOMEM;
1355
1356                 *result = path_simplify(t, false);
1357                 return 0;
1358         }
1359
1360         /* Otherwise, treat it as cg spec */
1361         r = cg_split_spec(path, &c, &p);
1362         if (r < 0)
1363                 return r;
1364
1365         return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1366 }
1367
1368 int cg_get_root_path(char **path) {
1369         char *p, *e;
1370         int r;
1371
1372         assert(path);
1373
1374         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1375         if (r < 0)
1376                 return r;
1377
1378 #if 0 /// elogind does not support systemd scopes and slices
1379         e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1380         if (!e)
1381                 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1382         if (!e)
1383                 e = endswith(p, "/system"); /* even more legacy */
1384 #else
1385         e = endswith(p, "/elogind");
1386 #endif // 0
1387         if (e)
1388                 *e = 0;
1389
1390         *path = p;
1391         return 0;
1392 }
1393
1394 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1395         _cleanup_free_ char *rt = NULL;
1396         char *p;
1397         int r;
1398
1399         assert(cgroup);
1400         assert(shifted);
1401
1402         if (!root) {
1403                 /* If the root was specified let's use that, otherwise
1404                  * let's determine it from PID 1 */
1405
1406                 r = cg_get_root_path(&rt);
1407                 if (r < 0)
1408                         return r;
1409
1410                 root = rt;
1411                 log_debug_elogind("Determined root path: \"%s\"", root);
1412         }
1413
1414         p = path_startswith(cgroup, root);
1415 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1416         if (p && p > cgroup)
1417 #else
1418         if (p && p[0] && (p > cgroup))
1419 #endif // 0
1420                 *shifted = p - 1;
1421         else
1422                 *shifted = cgroup;
1423
1424         return 0;
1425 }
1426
1427 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1428         _cleanup_free_ char *raw = NULL;
1429         const char *c;
1430         int r;
1431
1432         assert(pid >= 0);
1433         assert(cgroup);
1434
1435         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1436         if (r < 0)
1437                 return r;
1438
1439         log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1440                           raw, pid, root ? root : "NULL");
1441         r = cg_shift_path(raw, root, &c);
1442         if (r < 0)
1443                 return r;
1444
1445         if (c == raw)
1446                 *cgroup = TAKE_PTR(raw);
1447         else {
1448                 char *n;
1449
1450                 n = strdup(c);
1451                 if (!n)
1452                         return -ENOMEM;
1453
1454                 *cgroup = n;
1455         }
1456         log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1457
1458         return 0;
1459 }
1460
1461 int cg_path_decode_unit(const char *cgroup, char **unit) {
1462         char *c, *s;
1463         size_t n;
1464
1465         assert(cgroup);
1466         assert(unit);
1467
1468 #if 0 /// elogind has a different naming: <controller>:/<session id>. So prefix is always len < 3
1469         n = strcspn(cgroup, "/");
1470         if (n < 3)
1471                 return -ENXIO;
1472 #else
1473         n = strspn(cgroup, "/") + 1;
1474 #endif // 0
1475
1476         c = strndupa(cgroup, n);
1477         c = cg_unescape(c);
1478
1479 #if 0 /// elogind session ids are never valid unit names.
1480         if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1481                 return -ENXIO;
1482 #endif // 0
1483
1484         s = strdup(c);
1485         if (!s)
1486                 return -ENOMEM;
1487
1488         *unit = s;
1489         return 0;
1490 }
1491
1492 static bool valid_slice_name(const char *p, size_t n) {
1493
1494         if (!p)
1495                 return false;
1496
1497         if (n < STRLEN("x.slice"))
1498                 return false;
1499
1500         if (memcmp(p + n - 6, ".slice", 6) == 0) {
1501                 char buf[n+1], *c;
1502
1503                 memcpy(buf, p, n);
1504                 buf[n] = 0;
1505
1506                 c = cg_unescape(buf);
1507
1508                 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1509         }
1510
1511         return false;
1512 }
1513
1514 static const char *skip_slices(const char *p) {
1515         assert(p);
1516
1517         /* Skips over all slice assignments */
1518
1519         for (;;) {
1520                 size_t n;
1521
1522                 p += strspn(p, "/");
1523
1524                 n = strcspn(p, "/");
1525                 if (!valid_slice_name(p, n))
1526                         return p;
1527
1528                 p += n;
1529         }
1530 }
1531
1532 int cg_path_get_unit(const char *path, char **ret) {
1533         const char *e;
1534         char *unit;
1535         int r;
1536
1537         assert(path);
1538         assert(ret);
1539
1540         e = skip_slices(path);
1541
1542         r = cg_path_decode_unit(e, &unit);
1543         if (r < 0)
1544                 return r;
1545
1546         /* We skipped over the slices, don't accept any now */
1547         if (endswith(unit, ".slice")) {
1548                 free(unit);
1549                 return -ENXIO;
1550         }
1551
1552         *ret = unit;
1553         return 0;
1554 }
1555
1556 int cg_pid_get_unit(pid_t pid, char **unit) {
1557         _cleanup_free_ char *cgroup = NULL;
1558         int r;
1559
1560         assert(unit);
1561
1562         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1563         if (r < 0)
1564                 return r;
1565
1566         return cg_path_get_unit(cgroup, unit);
1567 }
1568
1569 #if 0 /// UNNEEDED by elogind
1570 /**
1571  * Skip session-*.scope, but require it to be there.
1572  */
1573 static const char *skip_session(const char *p) {
1574         size_t n;
1575
1576         if (isempty(p))
1577                 return NULL;
1578
1579         p += strspn(p, "/");
1580
1581         n = strcspn(p, "/");
1582         if (n < STRLEN("session-x.scope"))
1583                 return NULL;
1584
1585         if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1586                 char buf[n - 8 - 6 + 1];
1587
1588                 memcpy(buf, p + 8, n - 8 - 6);
1589                 buf[n - 8 - 6] = 0;
1590
1591                 /* Note that session scopes never need unescaping,
1592                  * since they cannot conflict with the kernel's own
1593                  * names, hence we don't need to call cg_unescape()
1594                  * here. */
1595
1596                 if (!session_id_valid(buf))
1597                         return false;
1598
1599                 p += n;
1600                 p += strspn(p, "/");
1601                 return p;
1602         }
1603
1604         return NULL;
1605 }
1606
1607 /**
1608  * Skip user@*.service, but require it to be there.
1609  */
1610 static const char *skip_user_manager(const char *p) {
1611         size_t n;
1612
1613         if (isempty(p))
1614                 return NULL;
1615
1616         p += strspn(p, "/");
1617
1618         n = strcspn(p, "/");
1619         if (n < STRLEN("user@x.service"))
1620                 return NULL;
1621
1622         if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1623                 char buf[n - 5 - 8 + 1];
1624
1625                 memcpy(buf, p + 5, n - 5 - 8);
1626                 buf[n - 5 - 8] = 0;
1627
1628                 /* Note that user manager services never need unescaping,
1629                  * since they cannot conflict with the kernel's own
1630                  * names, hence we don't need to call cg_unescape()
1631                  * here. */
1632
1633                 if (parse_uid(buf, NULL) < 0)
1634                         return NULL;
1635
1636                 p += n;
1637                 p += strspn(p, "/");
1638
1639                 return p;
1640         }
1641
1642         return NULL;
1643 }
1644
1645 static const char *skip_user_prefix(const char *path) {
1646         const char *e, *t;
1647
1648         assert(path);
1649
1650         /* Skip slices, if there are any */
1651         e = skip_slices(path);
1652
1653         /* Skip the user manager, if it's in the path now... */
1654         t = skip_user_manager(e);
1655         if (t)
1656                 return t;
1657
1658         /* Alternatively skip the user session if it is in the path... */
1659         return skip_session(e);
1660 }
1661
1662 int cg_path_get_user_unit(const char *path, char **ret) {
1663         const char *t;
1664
1665         assert(path);
1666         assert(ret);
1667
1668         t = skip_user_prefix(path);
1669         if (!t)
1670                 return -ENXIO;
1671
1672         /* And from here on it looks pretty much the same as for a
1673          * system unit, hence let's use the same parser from here
1674          * on. */
1675         return cg_path_get_unit(t, ret);
1676 }
1677
1678 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1679         _cleanup_free_ char *cgroup = NULL;
1680         int r;
1681
1682         assert(unit);
1683
1684         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1685         if (r < 0)
1686                 return r;
1687
1688         return cg_path_get_user_unit(cgroup, unit);
1689 }
1690
1691 int cg_path_get_machine_name(const char *path, char **machine) {
1692         _cleanup_free_ char *u = NULL;
1693         const char *sl;
1694         int r;
1695
1696         r = cg_path_get_unit(path, &u);
1697         if (r < 0)
1698                 return r;
1699
1700         sl = strjoina("/run/systemd/machines/unit:", u);
1701         return readlink_malloc(sl, machine);
1702 }
1703
1704 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1705         _cleanup_free_ char *cgroup = NULL;
1706         int r;
1707
1708         assert(machine);
1709
1710         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1711         if (r < 0)
1712                 return r;
1713
1714         return cg_path_get_machine_name(cgroup, machine);
1715 }
1716 #endif // 0
1717
1718 int cg_path_get_session(const char *path, char **session) {
1719 #if 0 /// UNNEEDED by elogind
1720         _cleanup_free_ char *unit = NULL;
1721         char *start, *end;
1722         int r;
1723
1724         assert(path);
1725
1726         r = cg_path_get_unit(path, &unit);
1727         if (r < 0)
1728                 return r;
1729
1730         start = startswith(unit, "session-");
1731         if (!start)
1732                 return -ENXIO;
1733         end = endswith(start, ".scope");
1734         if (!end)
1735                 return -ENXIO;
1736
1737         *end = 0;
1738         if (!session_id_valid(start))
1739                 return -ENXIO;
1740 #else
1741         /* Elogind uses a flat hierarchy, just "/SESSION".  The only
1742            wrinkle is that SESSION might be escaped.  */
1743         const char *e, *n, *start;
1744
1745         assert(path);
1746         log_debug_elogind("path is \"%s\"", path);
1747         assert(path[0] == '/');
1748
1749         e = path + 1;
1750         n = strchrnul(e, '/');
1751         if (e == n)
1752                 return -ENOENT;
1753
1754         start = strndupa(e, n - e);
1755         start = cg_unescape(start);
1756
1757         if (!start[0])
1758                 return -ENOENT;
1759 #endif // 0
1760
1761         if (session) {
1762                 char *rr;
1763
1764                 log_debug_elogind("found session: \"%s\"", start);
1765                 rr = strdup(start);
1766                 if (!rr)
1767                         return -ENOMEM;
1768
1769                 *session = rr;
1770         }
1771
1772         return 0;
1773 }
1774
1775 int cg_pid_get_session(pid_t pid, char **session) {
1776         _cleanup_free_ char *cgroup = NULL;
1777         int r;
1778
1779         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1780         if (r < 0)
1781                 return r;
1782
1783         return cg_path_get_session(cgroup, session);
1784 }
1785
1786 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1787 #if 0 /// elogind needs one more value
1788         _cleanup_free_ char *slice = NULL;
1789         char *start, *end;
1790 #else
1791         _cleanup_free_ char *slice = NULL, *p = NULL, *s = NULL;
1792 #endif // 0
1793         int r;
1794
1795         assert(path);
1796
1797         r = cg_path_get_slice(path, &slice);
1798         if (r < 0)
1799                 return r;
1800
1801 #if 0 /// elogind does not support systemd slices
1802         start = startswith(slice, "user-");
1803         if (!start)
1804                 return -ENXIO;
1805         end = endswith(start, ".slice");
1806         if (!end)
1807                 return -ENXIO;
1808
1809         *end = 0;
1810         if (parse_uid(start, uid) < 0)
1811                 return -ENXIO;
1812 #else
1813         p = strappend("/run/systemd/sessions/", slice);
1814
1815         r = parse_env_file(p, NEWLINE, "UID", &s, NULL);
1816         if (r == -ENOENT)
1817                 return -ENXIO;
1818         if (r < 0)
1819                 return r;
1820         if (isempty(s))
1821                 return -EIO;
1822
1823         if (parse_uid(s, uid) < 0)
1824                 return -ENXIO;
1825 #endif // 0
1826
1827         return 0;
1828 }
1829
1830 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1831         _cleanup_free_ char *cgroup = NULL;
1832         int r;
1833
1834         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1835         if (r < 0)
1836                 return r;
1837
1838         return cg_path_get_owner_uid(cgroup, uid);
1839 }
1840
1841 int cg_path_get_slice(const char *p, char **slice) {
1842         const char *e = NULL;
1843
1844         assert(p);
1845         assert(slice);
1846
1847 #if 0 /// elogind does not support systemd slices
1848         /* Finds the right-most slice unit from the beginning, but
1849          * stops before we come to the first non-slice unit. */
1850
1851         for (;;) {
1852                 size_t n;
1853
1854                 p += strspn(p, "/");
1855
1856                 n = strcspn(p, "/");
1857                 if (!valid_slice_name(p, n)) {
1858
1859                         if (!e) {
1860                                 char *s;
1861
1862                                 s = strdup(SPECIAL_ROOT_SLICE);
1863                                 if (!s)
1864                                         return -ENOMEM;
1865
1866                                 *slice = s;
1867                                 return 0;
1868                         }
1869
1870                         return cg_path_decode_unit(e, slice);
1871                 }
1872
1873                 e = p;
1874                 p += n;
1875         }
1876 #else
1877         /* In elogind, what is reported here, is the location of
1878          * the session. This is derived from /proc/<self|PID>/cgroup.
1879          * In there we look at the controller, which will look something
1880          * like "1:name=openrc:/3".
1881          * The last part gets extracted (and is now p), which is "/3" in
1882          * this case. The three is the session id, and that can be mapped.
1883          */
1884         e = startswith(p, "/");
1885
1886         if (e)
1887                 *slice = strdup(e);
1888         else
1889                 *slice = strdup(p);
1890
1891         return 0;
1892 #endif // 0
1893 }
1894
1895 int cg_pid_get_slice(pid_t pid, char **slice) {
1896         _cleanup_free_ char *cgroup = NULL;
1897         int r;
1898
1899         assert(slice);
1900
1901         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1902         log_debug_elogind("Found cgroup %s for pid %u (result %d)",
1903                           cgroup, pid, r);
1904         if (r < 0)
1905                 return r;
1906
1907         return cg_path_get_slice(cgroup, slice);
1908 }
1909
1910 int cg_path_get_user_slice(const char *p, char **slice) {
1911 #if 0 /// UNNEEDED by elogind
1912         const char *t;
1913 #endif // 0
1914         assert(p);
1915         assert(slice);
1916
1917 #if 0 /// nothing to skip in elogind
1918         t = skip_user_prefix(p);
1919         if (!t)
1920                 return -ENXIO;
1921 #endif // 0
1922
1923 #if 0 /// UNNEEDED by elogind
1924         /* And now it looks pretty much the same as for a system
1925          * slice, so let's just use the same parser from here on. */
1926         return cg_path_get_slice(t, slice);
1927 #else
1928         /* In elogind there is nothing to skip, we can use the path
1929          * directly. Generally speaking this is always a session id
1930          * to user mapping. */
1931         return cg_path_get_slice(p, slice);
1932 #endif // 0
1933 }
1934
1935 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1936         _cleanup_free_ char *cgroup = NULL;
1937         int r;
1938
1939         assert(slice);
1940
1941         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1942         if (r < 0)
1943                 return r;
1944
1945         return cg_path_get_user_slice(cgroup, slice);
1946 }
1947
1948 char *cg_escape(const char *p) {
1949         bool need_prefix = false;
1950
1951         /* This implements very minimal escaping for names to be used
1952          * as file names in the cgroup tree: any name which might
1953          * conflict with a kernel name or is prefixed with '_' is
1954          * prefixed with a '_'. That way, when reading cgroup names it
1955          * is sufficient to remove a single prefixing underscore if
1956          * there is one. */
1957
1958         /* The return value of this function (unlike cg_unescape())
1959          * needs free()! */
1960
1961         if (IN_SET(p[0], 0, '_', '.') ||
1962             streq(p, "notify_on_release") ||
1963             streq(p, "release_agent") ||
1964             streq(p, "tasks") ||
1965             startswith(p, "cgroup."))
1966                 need_prefix = true;
1967         else {
1968                 const char *dot;
1969
1970                 dot = strrchr(p, '.');
1971                 if (dot) {
1972                         CGroupController c;
1973                         size_t l = dot - p;
1974
1975                         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1976                                 const char *n;
1977
1978                                 n = cgroup_controller_to_string(c);
1979
1980                                 if (l != strlen(n))
1981                                         continue;
1982
1983                                 if (memcmp(p, n, l) != 0)
1984                                         continue;
1985
1986                                 need_prefix = true;
1987                                 break;
1988                         }
1989                 }
1990         }
1991
1992         if (need_prefix)
1993                 return strappend("_", p);
1994
1995         return strdup(p);
1996 }
1997
1998 char *cg_unescape(const char *p) {
1999         assert(p);
2000
2001         /* The return value of this function (unlike cg_escape())
2002          * doesn't need free()! */
2003
2004         if (p[0] == '_')
2005                 return (char*) p+1;
2006
2007         return (char*) p;
2008 }
2009
2010 #define CONTROLLER_VALID                        \
2011         DIGITS LETTERS                          \
2012         "_"
2013
2014 bool cg_controller_is_valid(const char *p) {
2015         const char *t, *s;
2016
2017         if (!p)
2018                 return false;
2019
2020         if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
2021                 return true;
2022
2023         s = startswith(p, "name=");
2024         if (s)
2025                 p = s;
2026
2027         if (IN_SET(*p, 0, '_'))
2028                 return false;
2029
2030         for (t = p; *t; t++)
2031                 if (!strchr(CONTROLLER_VALID, *t))
2032                         return false;
2033
2034         if (t - p > FILENAME_MAX)
2035                 return false;
2036
2037         return true;
2038 }
2039
2040 #if 0 /// UNNEEDED by elogind
2041 int cg_slice_to_path(const char *unit, char **ret) {
2042         _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
2043         const char *dash;
2044         int r;
2045
2046         assert(unit);
2047         assert(ret);
2048
2049         if (streq(unit, SPECIAL_ROOT_SLICE)) {
2050                 char *x;
2051
2052                 x = strdup("");
2053                 if (!x)
2054                         return -ENOMEM;
2055                 *ret = x;
2056                 return 0;
2057         }
2058
2059         if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
2060                 return -EINVAL;
2061
2062         if (!endswith(unit, ".slice"))
2063                 return -EINVAL;
2064
2065         r = unit_name_to_prefix(unit, &p);
2066         if (r < 0)
2067                 return r;
2068
2069         dash = strchr(p, '-');
2070
2071         /* Don't allow initial dashes */
2072         if (dash == p)
2073                 return -EINVAL;
2074
2075         while (dash) {
2076                 _cleanup_free_ char *escaped = NULL;
2077                 char n[dash - p + sizeof(".slice")];
2078
2079 #if HAS_FEATURE_MEMORY_SANITIZER
2080                 /* msan doesn't instrument stpncpy, so it thinks
2081                  * n is later used unitialized:
2082                  * https://github.com/google/sanitizers/issues/926
2083                  */
2084                 zero(n);
2085 #endif
2086
2087                 /* Don't allow trailing or double dashes */
2088                 if (IN_SET(dash[1], 0, '-'))
2089                         return -EINVAL;
2090
2091                 strcpy(stpncpy(n, p, dash - p), ".slice");
2092                 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
2093                         return -EINVAL;
2094
2095                 escaped = cg_escape(n);
2096                 if (!escaped)
2097                         return -ENOMEM;
2098
2099                 if (!strextend(&s, escaped, "/", NULL))
2100                         return -ENOMEM;
2101
2102                 dash = strchr(dash+1, '-');
2103         }
2104
2105         e = cg_escape(unit);
2106         if (!e)
2107                 return -ENOMEM;
2108
2109         if (!strextend(&s, e, NULL))
2110                 return -ENOMEM;
2111
2112         *ret = TAKE_PTR(s);
2113
2114         return 0;
2115 }
2116 #endif // 0
2117
2118 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
2119         _cleanup_free_ char *p = NULL;
2120         int r;
2121
2122         r = cg_get_path(controller, path, attribute, &p);
2123         if (r < 0)
2124                 return r;
2125
2126         return write_string_file(p, value, 0);
2127 }
2128
2129 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
2130         _cleanup_free_ char *p = NULL;
2131         int r;
2132
2133         r = cg_get_path(controller, path, attribute, &p);
2134         if (r < 0)
2135                 return r;
2136
2137         return read_one_line_file(p, ret);
2138 }
2139
2140 #if 0 /// UNNEEDED by elogind
2141 int cg_get_keyed_attribute(
2142                 const char *controller,
2143                 const char *path,
2144                 const char *attribute,
2145                 char **keys,
2146                 char **ret_values) {
2147
2148         _cleanup_free_ char *filename = NULL, *contents = NULL;
2149         const char *p;
2150         size_t n, i, n_done = 0;
2151         char **v;
2152         int r;
2153
2154         /* Reads one or more fields of a cgroupsv2 keyed attribute file. The 'keys' parameter should be an strv with
2155          * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
2156          * entries as 'keys'. On success each entry will be set to the value of the matching key.
2157          *
2158          * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
2159
2160         r = cg_get_path(controller, path, attribute, &filename);
2161         if (r < 0)
2162                 return r;
2163
2164         r = read_full_file(filename, &contents, NULL);
2165         if (r < 0)
2166                 return r;
2167
2168         n = strv_length(keys);
2169         if (n == 0) /* No keys to retrieve? That's easy, we are done then */
2170                 return 0;
2171
2172         /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
2173         v = newa0(char*, n);
2174
2175         for (p = contents; *p;) {
2176                 const char *w = NULL;
2177
2178                 for (i = 0; i < n; i++)
2179                         if (!v[i]) {
2180                                 w = first_word(p, keys[i]);
2181                                 if (w)
2182                                         break;
2183                         }
2184
2185                 if (w) {
2186                         size_t l;
2187
2188                         l = strcspn(w, NEWLINE);
2189                         v[i] = strndup(w, l);
2190                         if (!v[i]) {
2191                                 r = -ENOMEM;
2192                                 goto fail;
2193                         }
2194
2195                         n_done++;
2196                         if (n_done >= n)
2197                                 goto done;
2198
2199                         p = w + l;
2200                 } else
2201                         p += strcspn(p, NEWLINE);
2202
2203                 p += strspn(p, NEWLINE);
2204         }
2205
2206         r = -ENXIO;
2207
2208 fail:
2209         for (i = 0; i < n; i++)
2210                 free(v[i]);
2211
2212         return r;
2213
2214 done:
2215         memcpy(ret_values, v, sizeof(char*) * n);
2216         return 0;
2217
2218 }
2219
2220 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2221         CGroupController c;
2222         bool created;
2223         int r;
2224
2225         /* This one will create a cgroup in our private tree, but also
2226          * duplicate it in the trees specified in mask, and remove it
2227          * in all others.
2228          *
2229          * Returns 0 if the group already existed in the systemd hierarchy,
2230          * 1 on success, negative otherwise.
2231          */
2232
2233         /* First create the cgroup in our own hierarchy. */
2234         r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2235         if (r < 0)
2236                 return r;
2237         created = !!r;
2238
2239         /* If we are in the unified hierarchy, we are done now */
2240         r = cg_all_unified();
2241         if (r < 0)
2242                 return r;
2243         if (r > 0)
2244                 return created;
2245
2246         /* Otherwise, do the same in the other hierarchies */
2247         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2248                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2249                 const char *n;
2250
2251                 n = cgroup_controller_to_string(c);
2252
2253                 if (mask & bit)
2254                         (void) cg_create(n, path);
2255                 else if (supported & bit)
2256                         (void) cg_trim(n, path, true);
2257         }
2258
2259         return created;
2260 }
2261
2262 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2263         CGroupController c;
2264         int r;
2265
2266         r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2267         if (r < 0)
2268                 return r;
2269
2270         r = cg_all_unified();
2271         if (r < 0)
2272                 return r;
2273         if (r > 0)
2274                 return 0;
2275
2276         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2277                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2278                 const char *p = NULL;
2279
2280                 if (!(supported & bit))
2281                         continue;
2282
2283                 if (path_callback)
2284                         p = path_callback(bit, userdata);
2285
2286                 if (!p)
2287                         p = path;
2288
2289                 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2290         }
2291
2292         return 0;
2293 }
2294
2295 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2296         Iterator i;
2297         void *pidp;
2298         int r = 0;
2299
2300         SET_FOREACH(pidp, pids, i) {
2301                 pid_t pid = PTR_TO_PID(pidp);
2302                 int q;
2303
2304                 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2305                 if (q < 0 && r >= 0)
2306                         r = q;
2307         }
2308
2309         return r;
2310 }
2311
2312 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2313         CGroupController c;
2314         int r = 0, q;
2315
2316         if (!path_equal(from, to))  {
2317                 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2318                 if (r < 0)
2319                         return r;
2320         }
2321
2322         q = cg_all_unified();
2323         if (q < 0)
2324                 return q;
2325         if (q > 0)
2326                 return r;
2327
2328         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2329                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2330                 const char *p = NULL;
2331
2332                 if (!(supported & bit))
2333                         continue;
2334
2335                 if (to_callback)
2336                         p = to_callback(bit, userdata);
2337
2338                 if (!p)
2339                         p = to;
2340
2341                 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2342         }
2343
2344         return 0;
2345 }
2346
2347 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2348         CGroupController c;
2349         int r, q;
2350
2351         r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2352         if (r < 0)
2353                 return r;
2354
2355         q = cg_all_unified();
2356         if (q < 0)
2357                 return q;
2358         if (q > 0)
2359                 return r;
2360
2361         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2362                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2363
2364                 if (!(supported & bit))
2365                         continue;
2366
2367                 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2368         }
2369
2370         return 0;
2371 }
2372 #endif // 0
2373
2374 int cg_mask_to_string(CGroupMask mask, char **ret) {
2375         _cleanup_free_ char *s = NULL;
2376         size_t n = 0, allocated = 0;
2377         bool space = false;
2378         CGroupController c;
2379
2380         assert(ret);
2381
2382         if (mask == 0) {
2383                 *ret = NULL;
2384                 return 0;
2385         }
2386
2387         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2388                 const char *k;
2389                 size_t l;
2390
2391                 if (!(mask & CGROUP_CONTROLLER_TO_MASK(c)))
2392                         continue;
2393
2394                 k = cgroup_controller_to_string(c);
2395                 l = strlen(k);
2396
2397                 if (!GREEDY_REALLOC(s, allocated, n + space + l + 1))
2398                         return -ENOMEM;
2399
2400                 if (space)
2401                         s[n] = ' ';
2402                 memcpy(s + n + space, k, l);
2403                 n += space + l;
2404
2405                 space = true;
2406         }
2407
2408         assert(s);
2409
2410         s[n] = 0;
2411         *ret = TAKE_PTR(s);
2412
2413         return 0;
2414 }
2415
2416 int cg_mask_from_string(const char *value, CGroupMask *mask) {
2417         assert(mask);
2418         assert(value);
2419
2420         for (;;) {
2421                 _cleanup_free_ char *n = NULL;
2422                 CGroupController v;
2423                 int r;
2424
2425                 r = extract_first_word(&value, &n, NULL, 0);
2426                 if (r < 0)
2427                         return r;
2428                 if (r == 0)
2429                         break;
2430
2431                 v = cgroup_controller_from_string(n);
2432                 if (v < 0)
2433                         continue;
2434
2435                 *mask |= CGROUP_CONTROLLER_TO_MASK(v);
2436         }
2437         return 0;
2438 }
2439
2440 int cg_mask_supported(CGroupMask *ret) {
2441         CGroupMask mask = 0;
2442         int r;
2443
2444         /* Determines the mask of supported cgroup controllers. Only
2445          * includes controllers we can make sense of and that are
2446          * actually accessible. */
2447
2448         r = cg_all_unified();
2449         if (r < 0)
2450                 return r;
2451         if (r > 0) {
2452                 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2453
2454                 /* In the unified hierarchy we can read the supported
2455                  * and accessible controllers from a the top-level
2456                  * cgroup attribute */
2457
2458                 r = cg_get_root_path(&root);
2459                 if (r < 0)
2460                         return r;
2461
2462                 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2463                 if (r < 0)
2464                         return r;
2465
2466                 r = read_one_line_file(path, &controllers);
2467                 if (r < 0)
2468                         return r;
2469
2470                 r = cg_mask_from_string(controllers, &mask);
2471                 if (r < 0)
2472                         return r;
2473
2474                 /* Currently, we support the cpu, memory, io and pids
2475                  * controller in the unified hierarchy, mask
2476                  * everything else off. */
2477                 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2478
2479         } else {
2480                 CGroupController c;
2481
2482                 /* In the legacy hierarchy, we check whether which
2483                  * hierarchies are mounted. */
2484
2485                 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2486                         const char *n;
2487
2488                         n = cgroup_controller_to_string(c);
2489                         if (controller_is_accessible(n) >= 0)
2490                                 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2491                 }
2492         }
2493
2494         *ret = mask;
2495         return 0;
2496 }
2497
2498 #if 0 /// UNNEEDED by elogind
2499 int cg_kernel_controllers(Set **ret) {
2500         _cleanup_set_free_free_ Set *controllers = NULL;
2501         _cleanup_fclose_ FILE *f = NULL;
2502         int r;
2503
2504         assert(ret);
2505
2506         /* Determines the full list of kernel-known controllers. Might
2507          * include controllers we don't actually support, arbitrary
2508          * named hierarchies and controllers that aren't currently
2509          * accessible (because not mounted). */
2510
2511         controllers = set_new(&string_hash_ops);
2512         if (!controllers)
2513                 return -ENOMEM;
2514
2515         f = fopen("/proc/cgroups", "re");
2516         if (!f) {
2517                 if (errno == ENOENT) {
2518                         *ret = NULL;
2519                         return 0;
2520                 }
2521
2522                 return -errno;
2523         }
2524
2525         (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
2526
2527         /* Ignore the header line */
2528         (void) read_line(f, (size_t) -1, NULL);
2529
2530         for (;;) {
2531                 char *controller;
2532                 int enabled = 0;
2533
2534                 errno = 0;
2535                 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2536
2537                         if (feof(f))
2538                                 break;
2539
2540                         if (ferror(f) && errno > 0)
2541                                 return -errno;
2542
2543                         return -EBADMSG;
2544                 }
2545
2546                 if (!enabled) {
2547                         free(controller);
2548                         continue;
2549                 }
2550
2551                 if (!cg_controller_is_valid(controller)) {
2552                         free(controller);
2553                         return -EBADMSG;
2554                 }
2555
2556                 r = set_consume(controllers, controller);
2557                 if (r < 0)
2558                         return r;
2559         }
2560
2561         *ret = TAKE_PTR(controllers);
2562
2563         return 0;
2564 }
2565 #endif // 0
2566
2567 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2568
2569 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup v2 on /sys/fs/cgroup/systemd.  This
2570  * unfortunately broke other tools (such as docker) which expected the v1 "name=systemd" hierarchy on
2571  * /sys/fs/cgroup/systemd.  From v233 and on, the hybrid mode mountnbs v2 on /sys/fs/cgroup/unified and maintains
2572  * "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility with other tools.
2573  *
2574  * To keep live upgrade working, we detect and support v232 layout.  When v232 layout is detected, to keep cgroup v2
2575  * process management but disable the compat dual layout, we return %true on
2576  * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and %false on cg_hybrid_unified().
2577  */
2578 static thread_local bool unified_systemd_v232;
2579
2580 static int cg_unified_update(void) {
2581
2582         struct statfs fs;
2583
2584         /* Checks if we support the unified hierarchy. Returns an
2585          * error when the cgroup hierarchies aren't mounted yet or we
2586          * have any other trouble determining if the unified hierarchy
2587          * is supported. */
2588
2589         if (unified_cache >= CGROUP_UNIFIED_NONE)
2590                 return 0;
2591
2592         if (statfs("/sys/fs/cgroup/", &fs) < 0)
2593                 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/\") failed: %m");
2594
2595         if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2596                 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
2597                 unified_cache = CGROUP_UNIFIED_ALL;
2598 #if 0 /// The handling of cgroups is a bit different with elogind
2599         } else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2600                         log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2601 #else
2602         } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)
2603               || F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2604 #endif // 0
2605                 if (statfs("/sys/fs/cgroup/unified/", &fs) == 0 &&
2606                     F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2607                         unified_cache = CGROUP_UNIFIED_SYSTEMD;
2608                         unified_systemd_v232 = false;
2609                 } else {
2610 #if 0 /// There is no sub-grouping within elogind
2611                         if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2612                                 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2613
2614                         if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2615                                 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2616                                 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2617                                 unified_systemd_v232 = true;
2618                         } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)) {
2619                                 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2620                                 unified_cache = CGROUP_UNIFIED_NONE;
2621                         } else {
2622                                 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2623                                           (unsigned long long) fs.f_type);
2624                                 unified_cache = CGROUP_UNIFIED_NONE;
2625                         }
2626 #else
2627                         unified_cache = CGROUP_UNIFIED_NONE;
2628 #endif // 0
2629                 }
2630         } else {
2631                 log_debug("Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2632                           (unsigned long long) fs.f_type);
2633                 return -ENOMEDIUM;
2634         }
2635
2636         return 0;
2637 }
2638
2639 int cg_unified_controller(const char *controller) {
2640         int r;
2641
2642         r = cg_unified_update();
2643         if (r < 0)
2644                 return r;
2645
2646         if (unified_cache == CGROUP_UNIFIED_NONE)
2647                 return false;
2648
2649         if (unified_cache >= CGROUP_UNIFIED_ALL)
2650                 return true;
2651
2652 #if 0 /// only if elogind is the controller we can use cgroups2 in hybrid mode
2653         return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER);
2654 #else
2655         return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER_HYBRID);
2656 #endif // 0
2657 }
2658
2659 int cg_all_unified(void) {
2660         int r;
2661
2662         r = cg_unified_update();
2663         if (r < 0)
2664                 return r;
2665
2666         return unified_cache >= CGROUP_UNIFIED_ALL;
2667 }
2668
2669 int cg_hybrid_unified(void) {
2670         int r;
2671
2672         r = cg_unified_update();
2673         if (r < 0)
2674                 return r;
2675
2676         return unified_cache == CGROUP_UNIFIED_SYSTEMD && !unified_systemd_v232;
2677 }
2678
2679 int cg_unified_flush(void) {
2680         unified_cache = CGROUP_UNIFIED_UNKNOWN;
2681
2682         return cg_unified_update();
2683 }
2684
2685 #if 0 /// UNNEEDED by elogind
2686 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2687         _cleanup_fclose_ FILE *f = NULL;
2688         _cleanup_free_ char *fs = NULL;
2689         CGroupController c;
2690         int r;
2691
2692         assert(p);
2693
2694         if (supported == 0)
2695                 return 0;
2696
2697         r = cg_all_unified();
2698         if (r < 0)
2699                 return r;
2700         if (r == 0) /* on the legacy hiearchy there's no joining of controllers defined */
2701                 return 0;
2702
2703         r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2704         if (r < 0)
2705                 return r;
2706
2707         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2708                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2709                 const char *n;
2710
2711                 if (!(supported & bit))
2712                         continue;
2713
2714                 n = cgroup_controller_to_string(c);
2715                 {
2716                         char s[1 + strlen(n) + 1];
2717
2718                         s[0] = mask & bit ? '+' : '-';
2719                         strcpy(s + 1, n);
2720
2721                         if (!f) {
2722                                 f = fopen(fs, "we");
2723                                 if (!f) {
2724                                         log_debug_errno(errno, "Failed to open cgroup.subtree_control file of %s: %m", p);
2725                                         break;
2726                                 }
2727                         }
2728
2729                         r = write_string_stream(f, s, 0);
2730                         if (r < 0) {
2731                                 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2732                                 clearerr(f);
2733                         }
2734                 }
2735         }
2736
2737         return 0;
2738 }
2739 #endif // 0
2740
2741 bool cg_is_unified_wanted(void) {
2742         static thread_local int wanted = -1;
2743 #if 0 /// UNNEEDED by elogind
2744         int r;
2745         bool b;
2746 #endif // 0
2747         const bool is_default = DEFAULT_HIERARCHY == CGROUP_UNIFIED_ALL;
2748
2749         /* If we have a cached value, return that. */
2750         if (wanted >= 0)
2751                 return wanted;
2752
2753         /* If the hierarchy is already mounted, then follow whatever
2754          * was chosen for it. */
2755         if (cg_unified_flush() >= 0)
2756                 return (wanted = unified_cache >= CGROUP_UNIFIED_ALL);
2757
2758 #if 0 /// elogind is not init and has no business with kernel command line
2759         /* Otherwise, let's see what the kernel command line has to say.
2760          * Since checking is expensive, cache a non-error result. */
2761         r = proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b);
2762
2763         return (wanted = r > 0 ? b : is_default);
2764 #else
2765         return is_default;
2766 #endif // 0
2767 }
2768
2769 bool cg_is_legacy_wanted(void) {
2770         static thread_local int wanted = -1;
2771
2772         /* If we have a cached value, return that. */
2773         if (wanted >= 0)
2774                 return wanted;
2775
2776         /* Check if we have cgroups2 already mounted. */
2777         if (cg_unified_flush() >= 0 &&
2778             unified_cache == CGROUP_UNIFIED_ALL)
2779                 return (wanted = false);
2780
2781         /* Otherwise, assume that at least partial legacy is wanted,
2782          * since cgroups2 should already be mounted at this point. */
2783         return (wanted = true);
2784 }
2785
2786 bool cg_is_hybrid_wanted(void) {
2787         static thread_local int wanted = -1;
2788 #if 0 /// UNNEEDED by elogind
2789         int r;
2790         bool b;
2791 #endif // 0
2792         const bool is_default = DEFAULT_HIERARCHY >= CGROUP_UNIFIED_SYSTEMD;
2793         /* We default to true if the default is "hybrid", obviously,
2794          * but also when the default is "unified", because if we get
2795          * called, it means that unified hierarchy was not mounted. */
2796
2797         /* If we have a cached value, return that. */
2798         if (wanted >= 0)
2799                 return wanted;
2800
2801         /* If the hierarchy is already mounted, then follow whatever
2802          * was chosen for it. */
2803         if (cg_unified_flush() >= 0 &&
2804             unified_cache == CGROUP_UNIFIED_ALL)
2805                 return (wanted = false);
2806
2807 #if 0 /// elogind is not init and has no business with kernel command line
2808         /* Otherwise, let's see what the kernel command line has to say.
2809          * Since checking is expensive, cache a non-error result. */
2810         r = proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b);
2811
2812         /* The meaning of the kernel option is reversed wrt. to the return value
2813          * of this function, hence the negation. */
2814         return (wanted = r > 0 ? !b : is_default);
2815 #else
2816         return is_default;
2817 #endif // 0
2818 }
2819
2820 #if 0 /// UNNEEDED by elogind
2821 int cg_weight_parse(const char *s, uint64_t *ret) {
2822         uint64_t u;
2823         int r;
2824
2825         if (isempty(s)) {
2826                 *ret = CGROUP_WEIGHT_INVALID;
2827                 return 0;
2828         }
2829
2830         r = safe_atou64(s, &u);
2831         if (r < 0)
2832                 return r;
2833
2834         if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2835                 return -ERANGE;
2836
2837         *ret = u;
2838         return 0;
2839 }
2840
2841 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2842         [CGROUP_IO_RBPS_MAX]    = CGROUP_LIMIT_MAX,
2843         [CGROUP_IO_WBPS_MAX]    = CGROUP_LIMIT_MAX,
2844         [CGROUP_IO_RIOPS_MAX]   = CGROUP_LIMIT_MAX,
2845         [CGROUP_IO_WIOPS_MAX]   = CGROUP_LIMIT_MAX,
2846 };
2847
2848 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2849         [CGROUP_IO_RBPS_MAX]    = "IOReadBandwidthMax",
2850         [CGROUP_IO_WBPS_MAX]    = "IOWriteBandwidthMax",
2851         [CGROUP_IO_RIOPS_MAX]   = "IOReadIOPSMax",
2852         [CGROUP_IO_WIOPS_MAX]   = "IOWriteIOPSMax",
2853 };
2854
2855 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2856
2857 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2858         uint64_t u;
2859         int r;
2860
2861         if (isempty(s)) {
2862                 *ret = CGROUP_CPU_SHARES_INVALID;
2863                 return 0;
2864         }
2865
2866         r = safe_atou64(s, &u);
2867         if (r < 0)
2868                 return r;
2869
2870         if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2871                 return -ERANGE;
2872
2873         *ret = u;
2874         return 0;
2875 }
2876
2877 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2878         uint64_t u;
2879         int r;
2880
2881         if (isempty(s)) {
2882                 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2883                 return 0;
2884         }
2885
2886         r = safe_atou64(s, &u);
2887         if (r < 0)
2888                 return r;
2889
2890         if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2891                 return -ERANGE;
2892
2893         *ret = u;
2894         return 0;
2895 }
2896 #endif // 0
2897
2898 bool is_cgroup_fs(const struct statfs *s) {
2899         return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2900                is_fs_type(s, CGROUP2_SUPER_MAGIC);
2901 }
2902
2903 bool fd_is_cgroup_fs(int fd) {
2904         struct statfs s;
2905
2906         if (fstatfs(fd, &s) < 0)
2907                 return -errno;
2908
2909         return is_cgroup_fs(&s);
2910 }
2911
2912 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2913         [CGROUP_CONTROLLER_CPU] = "cpu",
2914         [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2915         [CGROUP_CONTROLLER_IO] = "io",
2916         [CGROUP_CONTROLLER_BLKIO] = "blkio",
2917         [CGROUP_CONTROLLER_MEMORY] = "memory",
2918         [CGROUP_CONTROLLER_DEVICES] = "devices",
2919         [CGROUP_CONTROLLER_PIDS] = "pids",
2920 };
2921
2922 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);