chiark / gitweb /
cgroup-util: fix enabling of controllers (#8816)
[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_kill_slashes(t);
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_kill_slashes(*fs);
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 int cg_create(const char *controller, const char *path) {
764         _cleanup_free_ char *fs = NULL;
765         int r;
766
767         r = cg_get_path_and_check(controller, path, NULL, &fs);
768         if (r < 0)
769                 return r;
770
771         r = mkdir_parents(fs, 0755);
772         if (r < 0)
773                 return r;
774
775         r = mkdir_errno_wrapper(fs, 0755);
776         if (r == -EEXIST)
777                 return 0;
778         if (r < 0)
779                 return r;
780
781         r = cg_hybrid_unified();
782         if (r < 0)
783                 return r;
784
785         if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
786                 r = cg_create(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
787                 if (r < 0)
788                         log_warning_errno(r, "Failed to create compat systemd cgroup %s: %m", path);
789         }
790
791         return 1;
792 }
793
794 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
795         int r, q;
796
797         assert(pid >= 0);
798
799         r = cg_create(controller, path);
800         if (r < 0)
801                 return r;
802
803         q = cg_attach(controller, path, pid);
804         if (q < 0)
805                 return q;
806
807         /* This does not remove the cgroup on failure */
808         return r;
809 }
810
811 int cg_attach(const char *controller, const char *path, pid_t pid) {
812         _cleanup_free_ char *fs = NULL;
813         char c[DECIMAL_STR_MAX(pid_t) + 2];
814         int r;
815
816         assert(path);
817         assert(pid >= 0);
818
819         r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
820         if (r < 0)
821                 return r;
822
823         if (pid == 0)
824                 pid = getpid_cached();
825
826         xsprintf(c, PID_FMT "\n", pid);
827
828         r = write_string_file(fs, c, 0);
829         if (r < 0)
830                 return r;
831
832         r = cg_hybrid_unified();
833         if (r < 0)
834                 return r;
835
836         if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
837                 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, pid);
838                 if (r < 0)
839                         log_warning_errno(r, "Failed to attach "PID_FMT" to compat systemd cgroup %s: %m", pid, path);
840         }
841
842         return 0;
843 }
844
845 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
846         int r;
847
848         assert(controller);
849         assert(path);
850         assert(pid >= 0);
851
852         r = cg_attach(controller, path, pid);
853         if (r < 0) {
854                 char prefix[strlen(path) + 1];
855
856                 /* This didn't work? Then let's try all prefixes of
857                  * the destination */
858
859                 PATH_FOREACH_PREFIX(prefix, path) {
860                         int q;
861
862                         q = cg_attach(controller, prefix, pid);
863                         if (q >= 0)
864                                 return q;
865                 }
866         }
867
868         return r;
869 }
870
871 #if 0 /// UNNEEDED by elogind
872 int cg_set_access(
873                 const char *controller,
874                 const char *path,
875                 uid_t uid,
876                 gid_t gid) {
877
878         struct Attribute {
879                 const char *name;
880                 bool fatal;
881         };
882
883         /* cgroupsv1, aka legacy/non-unified */
884         static const struct Attribute legacy_attributes[] = {
885                 { "cgroup.procs",           true  },
886                 { "tasks",                  false },
887                 { "cgroup.clone_children",  false },
888                 {},
889         };
890
891         /* cgroupsv2, aka unified */
892         static const struct Attribute unified_attributes[] = {
893                 { "cgroup.procs",           true  },
894                 { "cgroup.subtree_control", true  },
895                 { "cgroup.threads",         false },
896                 {},
897         };
898
899         static const struct Attribute* const attributes[] = {
900                 [false] = legacy_attributes,
901                 [true]  = unified_attributes,
902         };
903
904         _cleanup_free_ char *fs = NULL;
905         const struct Attribute *i;
906         int r, unified;
907
908         assert(path);
909
910         if (uid == UID_INVALID && gid == GID_INVALID)
911                 return 0;
912
913         unified = cg_unified_controller(controller);
914         if (unified < 0)
915                 return unified;
916
917         /* Configure access to the cgroup itself */
918         r = cg_get_path(controller, path, NULL, &fs);
919         if (r < 0)
920                 return r;
921
922         r = chmod_and_chown(fs, 0755, uid, gid);
923         if (r < 0)
924                 return r;
925
926         /* Configure access to the cgroup's attributes */
927         for (i = attributes[unified]; i->name; i++) {
928                 fs = mfree(fs);
929
930                 r = cg_get_path(controller, path, i->name, &fs);
931                 if (r < 0)
932                         return r;
933
934                 r = chmod_and_chown(fs, 0644, uid, gid);
935                 if (r < 0) {
936                         if (i->fatal)
937                                 return r;
938
939                         log_debug_errno(r, "Failed to set access on cgroup %s, ignoring: %m", fs);
940                 }
941         }
942
943         if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
944                 r = cg_hybrid_unified();
945                 if (r < 0)
946                         return r;
947                 if (r > 0) {
948                         /* Always propagate access mode from unified to legacy controller */
949                         r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, uid, gid);
950                         if (r < 0)
951                                 log_debug_errno(r, "Failed to set access on compatibility elogind cgroup %s, ignoring: %m", path);
952                 }
953         }
954
955         return 0;
956 }
957
958 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
959         _cleanup_free_ char *fs = NULL;
960         int r;
961
962         assert(path);
963         assert(name);
964         assert(value || size <= 0);
965
966         r = cg_get_path(controller, path, NULL, &fs);
967         if (r < 0)
968                 return r;
969
970         if (setxattr(fs, name, value, size, flags) < 0)
971                 return -errno;
972
973         return 0;
974 }
975
976 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
977         _cleanup_free_ char *fs = NULL;
978         ssize_t n;
979         int r;
980
981         assert(path);
982         assert(name);
983
984         r = cg_get_path(controller, path, NULL, &fs);
985         if (r < 0)
986                 return r;
987
988         n = getxattr(fs, name, value, size);
989         if (n < 0)
990                 return -errno;
991
992         return (int) n;
993 }
994 #endif // 0
995
996 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
997         _cleanup_fclose_ FILE *f = NULL;
998         char line[LINE_MAX];
999 #if 0 /// At elogind we do not want that (false alarm) "maybe uninitialized" warning
1000         const char *fs, *controller_str;
1001 #else
1002         const char *fs, *controller_str = NULL;
1003 #endif // 0
1004         size_t cs = 0;
1005         int unified;
1006
1007         assert(path);
1008         assert(pid >= 0);
1009
1010         if (controller) {
1011                 if (!cg_controller_is_valid(controller))
1012                         return -EINVAL;
1013         } else
1014                 controller = SYSTEMD_CGROUP_CONTROLLER;
1015
1016         unified = cg_unified_controller(controller);
1017         if (unified < 0)
1018                 return unified;
1019         if (unified == 0) {
1020                 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
1021                         controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
1022                 else
1023                         controller_str = controller;
1024
1025                 cs = strlen(controller_str);
1026         }
1027
1028         fs = procfs_file_alloca(pid, "cgroup");
1029         log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
1030                           pid, fs, controller);
1031         f = fopen(fs, "re");
1032         if (!f)
1033                 return errno == ENOENT ? -ESRCH : -errno;
1034
1035         (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1036
1037         FOREACH_LINE(line, f, return -errno) {
1038                 char *e, *p;
1039
1040                 truncate_nl(line);
1041
1042                 if (unified) {
1043                         e = startswith(line, "0:");
1044                         if (!e)
1045                                 continue;
1046
1047                         e = strchr(e, ':');
1048                         if (!e)
1049                                 continue;
1050                 } else {
1051                         char *l;
1052                         size_t k;
1053                         const char *word, *state;
1054                         bool found = false;
1055
1056                         l = strchr(line, ':');
1057                         if (!l)
1058                                 continue;
1059
1060                         l++;
1061                         e = strchr(l, ':');
1062                         if (!e)
1063                                 continue;
1064
1065                         *e = 0;
1066                         FOREACH_WORD_SEPARATOR(word, k, l, ",", state)
1067                                 if (k == cs && memcmp(word, controller_str, cs) == 0) {
1068                                         found = true;
1069                                         break;
1070                                 }
1071                         if (!found)
1072                                 continue;
1073                 }
1074
1075                 log_debug_elogind("Found %s:%s", line, e+1);
1076                 p = strdup(e + 1);
1077                 if (!p)
1078                         return -ENOMEM;
1079
1080                 /* Truncate suffix indicating the process is a zombie */
1081                 e = endswith(p, " (deleted)");
1082                 if (e)
1083                         *e = 0;
1084
1085                 *path = p;
1086                 return 0;
1087         }
1088
1089         return -ENODATA;
1090 }
1091
1092 #if 0 /// UNNEEDED by elogind
1093 int cg_install_release_agent(const char *controller, const char *agent) {
1094         _cleanup_free_ char *fs = NULL, *contents = NULL;
1095         const char *sc;
1096         int r;
1097
1098         assert(agent);
1099
1100         r = cg_unified_controller(controller);
1101         if (r < 0)
1102                 return r;
1103         if (r > 0) /* doesn't apply to unified hierarchy */
1104                 return -EOPNOTSUPP;
1105
1106         r = cg_get_path(controller, NULL, "release_agent", &fs);
1107         if (r < 0)
1108                 return r;
1109
1110         r = read_one_line_file(fs, &contents);
1111         if (r < 0)
1112                 return r;
1113
1114         sc = strstrip(contents);
1115         if (isempty(sc)) {
1116                 r = write_string_file(fs, agent, 0);
1117                 if (r < 0)
1118                         return r;
1119         } else if (!path_equal(sc, agent))
1120                 return -EEXIST;
1121
1122         fs = mfree(fs);
1123         r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1124         if (r < 0)
1125                 return r;
1126
1127         contents = mfree(contents);
1128         r = read_one_line_file(fs, &contents);
1129         if (r < 0)
1130                 return r;
1131
1132         sc = strstrip(contents);
1133         if (streq(sc, "0")) {
1134                 r = write_string_file(fs, "1", 0);
1135                 if (r < 0)
1136                         return r;
1137
1138                 return 1;
1139         }
1140
1141         if (!streq(sc, "1"))
1142                 return -EIO;
1143
1144         return 0;
1145 }
1146
1147 int cg_uninstall_release_agent(const char *controller) {
1148         _cleanup_free_ char *fs = NULL;
1149         int r;
1150
1151         r = cg_unified_controller(controller);
1152         if (r < 0)
1153                 return r;
1154         if (r > 0) /* Doesn't apply to unified hierarchy */
1155                 return -EOPNOTSUPP;
1156
1157         r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1158         if (r < 0)
1159                 return r;
1160
1161         r = write_string_file(fs, "0", 0);
1162         if (r < 0)
1163                 return r;
1164
1165         fs = mfree(fs);
1166
1167         r = cg_get_path(controller, NULL, "release_agent", &fs);
1168         if (r < 0)
1169                 return r;
1170
1171         r = write_string_file(fs, "", 0);
1172         if (r < 0)
1173                 return r;
1174
1175         return 0;
1176 }
1177 #endif // 0
1178
1179 int cg_is_empty(const char *controller, const char *path) {
1180         _cleanup_fclose_ FILE *f = NULL;
1181         pid_t pid;
1182         int r;
1183
1184         assert(path);
1185
1186         r = cg_enumerate_processes(controller, path, &f);
1187         if (r == -ENOENT)
1188                 return 1;
1189         if (r < 0)
1190                 return r;
1191
1192         r = cg_read_pid(f, &pid);
1193         if (r < 0)
1194                 return r;
1195
1196         return r == 0;
1197 }
1198
1199 int cg_is_empty_recursive(const char *controller, const char *path) {
1200         int r;
1201
1202         assert(path);
1203
1204         /* The root cgroup is always populated */
1205         if (controller && empty_or_root(path))
1206                 return false;
1207
1208         r = cg_unified_controller(controller);
1209         if (r < 0)
1210                 return r;
1211         if (r > 0) {
1212                 _cleanup_free_ char *t = NULL;
1213
1214                 /* On the unified hierarchy we can check empty state
1215                  * via the "populated" attribute of "cgroup.events". */
1216
1217                 r = cg_read_event(controller, path, "populated", &t);
1218                 if (r < 0)
1219                         return r;
1220
1221                 return streq(t, "0");
1222         } else {
1223                 _cleanup_closedir_ DIR *d = NULL;
1224                 char *fn;
1225
1226                 r = cg_is_empty(controller, path);
1227                 if (r <= 0)
1228                         return r;
1229
1230                 r = cg_enumerate_subgroups(controller, path, &d);
1231                 if (r == -ENOENT)
1232                         return 1;
1233                 if (r < 0)
1234                         return r;
1235
1236                 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1237                         _cleanup_free_ char *p = NULL;
1238
1239                         p = strjoin(path, "/", fn);
1240                         free(fn);
1241                         if (!p)
1242                                 return -ENOMEM;
1243
1244                         r = cg_is_empty_recursive(controller, p);
1245                         if (r <= 0)
1246                                 return r;
1247                 }
1248                 if (r < 0)
1249                         return r;
1250
1251                 return true;
1252         }
1253 }
1254
1255 int cg_split_spec(const char *spec, char **controller, char **path) {
1256         char *t = NULL, *u = NULL;
1257         const char *e;
1258
1259         assert(spec);
1260
1261         if (*spec == '/') {
1262                 if (!path_is_normalized(spec))
1263                         return -EINVAL;
1264
1265                 if (path) {
1266                         t = strdup(spec);
1267                         if (!t)
1268                                 return -ENOMEM;
1269
1270                         *path = path_kill_slashes(t);
1271                 }
1272
1273                 if (controller)
1274                         *controller = NULL;
1275
1276                 return 0;
1277         }
1278
1279         e = strchr(spec, ':');
1280         if (!e) {
1281                 if (!cg_controller_is_valid(spec))
1282                         return -EINVAL;
1283
1284                 if (controller) {
1285                         t = strdup(spec);
1286                         if (!t)
1287                                 return -ENOMEM;
1288
1289                         *controller = t;
1290                 }
1291
1292                 if (path)
1293                         *path = NULL;
1294
1295                 return 0;
1296         }
1297
1298         t = strndup(spec, e-spec);
1299         if (!t)
1300                 return -ENOMEM;
1301         if (!cg_controller_is_valid(t)) {
1302                 free(t);
1303                 return -EINVAL;
1304         }
1305
1306         if (isempty(e+1))
1307                 u = NULL;
1308         else {
1309                 u = strdup(e+1);
1310                 if (!u) {
1311                         free(t);
1312                         return -ENOMEM;
1313                 }
1314
1315                 if (!path_is_normalized(u) ||
1316                     !path_is_absolute(u)) {
1317                         free(t);
1318                         free(u);
1319                         return -EINVAL;
1320                 }
1321
1322                 path_kill_slashes(u);
1323         }
1324
1325         if (controller)
1326                 *controller = t;
1327         else
1328                 free(t);
1329
1330         if (path)
1331                 *path = u;
1332         else
1333                 free(u);
1334
1335         return 0;
1336 }
1337
1338 int cg_mangle_path(const char *path, char **result) {
1339         _cleanup_free_ char *c = NULL, *p = NULL;
1340         char *t;
1341         int r;
1342
1343         assert(path);
1344         assert(result);
1345
1346         /* First, check if it already is a filesystem path */
1347         if (path_startswith(path, "/sys/fs/cgroup")) {
1348
1349                 t = strdup(path);
1350                 if (!t)
1351                         return -ENOMEM;
1352
1353                 *result = path_kill_slashes(t);
1354                 return 0;
1355         }
1356
1357         /* Otherwise, treat it as cg spec */
1358         r = cg_split_spec(path, &c, &p);
1359         if (r < 0)
1360                 return r;
1361
1362         return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1363 }
1364
1365 int cg_get_root_path(char **path) {
1366         char *p, *e;
1367         int r;
1368
1369         assert(path);
1370
1371         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1372         if (r < 0)
1373                 return r;
1374
1375 #if 0 /// elogind does not support systemd scopes and slices
1376         e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1377         if (!e)
1378                 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1379         if (!e)
1380                 e = endswith(p, "/system"); /* even more legacy */
1381 #else
1382         e = endswith(p, "/elogind");
1383 #endif // 0
1384         if (e)
1385                 *e = 0;
1386
1387         *path = p;
1388         return 0;
1389 }
1390
1391 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1392         _cleanup_free_ char *rt = NULL;
1393         char *p;
1394         int r;
1395
1396         assert(cgroup);
1397         assert(shifted);
1398
1399         if (!root) {
1400                 /* If the root was specified let's use that, otherwise
1401                  * let's determine it from PID 1 */
1402
1403                 r = cg_get_root_path(&rt);
1404                 if (r < 0)
1405                         return r;
1406
1407                 root = rt;
1408                 log_debug_elogind("Determined root path: \"%s\"", root);
1409         }
1410
1411         p = path_startswith(cgroup, root);
1412 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1413         if (p && p > cgroup)
1414 #else
1415         if (p && p[0] && (p > cgroup))
1416 #endif // 0
1417                 *shifted = p - 1;
1418         else
1419                 *shifted = cgroup;
1420
1421         return 0;
1422 }
1423
1424 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1425         _cleanup_free_ char *raw = NULL;
1426         const char *c;
1427         int r;
1428
1429         assert(pid >= 0);
1430         assert(cgroup);
1431
1432         r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1433         if (r < 0)
1434                 return r;
1435
1436         log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1437                           raw, pid, root ? root : "NULL");
1438         r = cg_shift_path(raw, root, &c);
1439         if (r < 0)
1440                 return r;
1441
1442         if (c == raw)
1443                 *cgroup = TAKE_PTR(raw);
1444         else {
1445                 char *n;
1446
1447                 n = strdup(c);
1448                 if (!n)
1449                         return -ENOMEM;
1450
1451                 *cgroup = n;
1452         }
1453         log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1454
1455         return 0;
1456 }
1457
1458 int cg_path_decode_unit(const char *cgroup, char **unit) {
1459         char *c, *s;
1460         size_t n;
1461
1462         assert(cgroup);
1463         assert(unit);
1464
1465 #if 0 /// elogind has a different naming: <controller>:/<session id>. So prefix is always len < 3
1466         n = strcspn(cgroup, "/");
1467         if (n < 3)
1468                 return -ENXIO;
1469 #else
1470         n = strspn(cgroup, "/") + 1;
1471 #endif // 0
1472
1473         c = strndupa(cgroup, n);
1474         c = cg_unescape(c);
1475
1476 #if 0 /// elogind session ids are never valid unit names.
1477         if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1478                 return -ENXIO;
1479 #endif // 0
1480
1481         s = strdup(c);
1482         if (!s)
1483                 return -ENOMEM;
1484
1485         *unit = s;
1486         return 0;
1487 }
1488
1489 static bool valid_slice_name(const char *p, size_t n) {
1490
1491         if (!p)
1492                 return false;
1493
1494         if (n < STRLEN("x.slice"))
1495                 return false;
1496
1497         if (memcmp(p + n - 6, ".slice", 6) == 0) {
1498                 char buf[n+1], *c;
1499
1500                 memcpy(buf, p, n);
1501                 buf[n] = 0;
1502
1503                 c = cg_unescape(buf);
1504
1505                 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1506         }
1507
1508         return false;
1509 }
1510
1511 static const char *skip_slices(const char *p) {
1512         assert(p);
1513
1514         /* Skips over all slice assignments */
1515
1516         for (;;) {
1517                 size_t n;
1518
1519                 p += strspn(p, "/");
1520
1521                 n = strcspn(p, "/");
1522                 if (!valid_slice_name(p, n))
1523                         return p;
1524
1525                 p += n;
1526         }
1527 }
1528
1529 int cg_path_get_unit(const char *path, char **ret) {
1530         const char *e;
1531         char *unit;
1532         int r;
1533
1534         assert(path);
1535         assert(ret);
1536
1537         e = skip_slices(path);
1538
1539         r = cg_path_decode_unit(e, &unit);
1540         if (r < 0)
1541                 return r;
1542
1543         /* We skipped over the slices, don't accept any now */
1544         if (endswith(unit, ".slice")) {
1545                 free(unit);
1546                 return -ENXIO;
1547         }
1548
1549         *ret = unit;
1550         return 0;
1551 }
1552
1553 int cg_pid_get_unit(pid_t pid, char **unit) {
1554         _cleanup_free_ char *cgroup = NULL;
1555         int r;
1556
1557         assert(unit);
1558
1559         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1560         if (r < 0)
1561                 return r;
1562
1563         return cg_path_get_unit(cgroup, unit);
1564 }
1565
1566 #if 0 /// UNNEEDED by elogind
1567 /**
1568  * Skip session-*.scope, but require it to be there.
1569  */
1570 static const char *skip_session(const char *p) {
1571         size_t n;
1572
1573         if (isempty(p))
1574                 return NULL;
1575
1576         p += strspn(p, "/");
1577
1578         n = strcspn(p, "/");
1579         if (n < STRLEN("session-x.scope"))
1580                 return NULL;
1581
1582         if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1583                 char buf[n - 8 - 6 + 1];
1584
1585                 memcpy(buf, p + 8, n - 8 - 6);
1586                 buf[n - 8 - 6] = 0;
1587
1588                 /* Note that session scopes never need unescaping,
1589                  * since they cannot conflict with the kernel's own
1590                  * names, hence we don't need to call cg_unescape()
1591                  * here. */
1592
1593                 if (!session_id_valid(buf))
1594                         return false;
1595
1596                 p += n;
1597                 p += strspn(p, "/");
1598                 return p;
1599         }
1600
1601         return NULL;
1602 }
1603
1604 /**
1605  * Skip user@*.service, but require it to be there.
1606  */
1607 static const char *skip_user_manager(const char *p) {
1608         size_t n;
1609
1610         if (isempty(p))
1611                 return NULL;
1612
1613         p += strspn(p, "/");
1614
1615         n = strcspn(p, "/");
1616         if (n < STRLEN("user@x.service"))
1617                 return NULL;
1618
1619         if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1620                 char buf[n - 5 - 8 + 1];
1621
1622                 memcpy(buf, p + 5, n - 5 - 8);
1623                 buf[n - 5 - 8] = 0;
1624
1625                 /* Note that user manager services never need unescaping,
1626                  * since they cannot conflict with the kernel's own
1627                  * names, hence we don't need to call cg_unescape()
1628                  * here. */
1629
1630                 if (parse_uid(buf, NULL) < 0)
1631                         return NULL;
1632
1633                 p += n;
1634                 p += strspn(p, "/");
1635
1636                 return p;
1637         }
1638
1639         return NULL;
1640 }
1641
1642 static const char *skip_user_prefix(const char *path) {
1643         const char *e, *t;
1644
1645         assert(path);
1646
1647         /* Skip slices, if there are any */
1648         e = skip_slices(path);
1649
1650         /* Skip the user manager, if it's in the path now... */
1651         t = skip_user_manager(e);
1652         if (t)
1653                 return t;
1654
1655         /* Alternatively skip the user session if it is in the path... */
1656         return skip_session(e);
1657 }
1658
1659 int cg_path_get_user_unit(const char *path, char **ret) {
1660         const char *t;
1661
1662         assert(path);
1663         assert(ret);
1664
1665         t = skip_user_prefix(path);
1666         if (!t)
1667                 return -ENXIO;
1668
1669         /* And from here on it looks pretty much the same as for a
1670          * system unit, hence let's use the same parser from here
1671          * on. */
1672         return cg_path_get_unit(t, ret);
1673 }
1674
1675 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1676         _cleanup_free_ char *cgroup = NULL;
1677         int r;
1678
1679         assert(unit);
1680
1681         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1682         if (r < 0)
1683                 return r;
1684
1685         return cg_path_get_user_unit(cgroup, unit);
1686 }
1687
1688 int cg_path_get_machine_name(const char *path, char **machine) {
1689         _cleanup_free_ char *u = NULL;
1690         const char *sl;
1691         int r;
1692
1693         r = cg_path_get_unit(path, &u);
1694         if (r < 0)
1695                 return r;
1696
1697         sl = strjoina("/run/systemd/machines/unit:", u);
1698         return readlink_malloc(sl, machine);
1699 }
1700
1701 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1702         _cleanup_free_ char *cgroup = NULL;
1703         int r;
1704
1705         assert(machine);
1706
1707         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1708         if (r < 0)
1709                 return r;
1710
1711         return cg_path_get_machine_name(cgroup, machine);
1712 }
1713 #endif // 0
1714
1715 int cg_path_get_session(const char *path, char **session) {
1716 #if 0 /// UNNEEDED by elogind
1717         _cleanup_free_ char *unit = NULL;
1718         char *start, *end;
1719         int r;
1720
1721         assert(path);
1722
1723         r = cg_path_get_unit(path, &unit);
1724         if (r < 0)
1725                 return r;
1726
1727         start = startswith(unit, "session-");
1728         if (!start)
1729                 return -ENXIO;
1730         end = endswith(start, ".scope");
1731         if (!end)
1732                 return -ENXIO;
1733
1734         *end = 0;
1735         if (!session_id_valid(start))
1736                 return -ENXIO;
1737 #else
1738         /* Elogind uses a flat hierarchy, just "/SESSION".  The only
1739            wrinkle is that SESSION might be escaped.  */
1740         const char *e, *n, *start;
1741
1742         assert(path);
1743         log_debug_elogind("path is \"%s\"", path);
1744         assert(path[0] == '/');
1745
1746         e = path + 1;
1747         n = strchrnul(e, '/');
1748         if (e == n)
1749                 return -ENOENT;
1750
1751         start = strndupa(e, n - e);
1752         start = cg_unescape(start);
1753
1754         if (!start[0])
1755                 return -ENOENT;
1756 #endif // 0
1757
1758         if (session) {
1759                 char *rr;
1760
1761                 log_debug_elogind("found session: \"%s\"", start);
1762                 rr = strdup(start);
1763                 if (!rr)
1764                         return -ENOMEM;
1765
1766                 *session = rr;
1767         }
1768
1769         return 0;
1770 }
1771
1772 int cg_pid_get_session(pid_t pid, char **session) {
1773         _cleanup_free_ char *cgroup = NULL;
1774         int r;
1775
1776         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1777         if (r < 0)
1778                 return r;
1779
1780         return cg_path_get_session(cgroup, session);
1781 }
1782
1783 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1784 #if 0 /// elogind needs one more value
1785         _cleanup_free_ char *slice = NULL;
1786         char *start, *end;
1787 #else
1788         _cleanup_free_ char *slice = NULL, *p = NULL, *s = NULL;
1789 #endif // 0
1790         int r;
1791
1792         assert(path);
1793
1794         r = cg_path_get_slice(path, &slice);
1795         if (r < 0)
1796                 return r;
1797
1798 #if 0 /// elogind does not support systemd slices
1799         start = startswith(slice, "user-");
1800         if (!start)
1801                 return -ENXIO;
1802         end = endswith(start, ".slice");
1803         if (!end)
1804                 return -ENXIO;
1805
1806         *end = 0;
1807         if (parse_uid(start, uid) < 0)
1808                 return -ENXIO;
1809 #else
1810         p = strappend("/run/systemd/sessions/", slice);
1811
1812         r = parse_env_file(p, NEWLINE, "UID", &s, NULL);
1813         if (r == -ENOENT)
1814                 return -ENXIO;
1815         if (r < 0)
1816                 return r;
1817         if (isempty(s))
1818                 return -EIO;
1819
1820         if (parse_uid(s, uid) < 0)
1821                 return -ENXIO;
1822 #endif // 0
1823
1824         return 0;
1825 }
1826
1827 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1828         _cleanup_free_ char *cgroup = NULL;
1829         int r;
1830
1831         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1832         if (r < 0)
1833                 return r;
1834
1835         return cg_path_get_owner_uid(cgroup, uid);
1836 }
1837
1838 int cg_path_get_slice(const char *p, char **slice) {
1839         const char *e = NULL;
1840
1841         assert(p);
1842         assert(slice);
1843
1844 #if 0 /// elogind does not support systemd slices
1845         /* Finds the right-most slice unit from the beginning, but
1846          * stops before we come to the first non-slice unit. */
1847
1848         for (;;) {
1849                 size_t n;
1850
1851                 p += strspn(p, "/");
1852
1853                 n = strcspn(p, "/");
1854                 if (!valid_slice_name(p, n)) {
1855
1856                         if (!e) {
1857                                 char *s;
1858
1859                                 s = strdup(SPECIAL_ROOT_SLICE);
1860                                 if (!s)
1861                                         return -ENOMEM;
1862
1863                                 *slice = s;
1864                                 return 0;
1865                         }
1866
1867                         return cg_path_decode_unit(e, slice);
1868                 }
1869
1870                 e = p;
1871                 p += n;
1872         }
1873 #else
1874         /* In elogind, what is reported here, is the location of
1875          * the session. This is derived from /proc/<self|PID>/cgroup.
1876          * In there we look at the controller, which will look something
1877          * like "1:name=openrc:/3".
1878          * The last part gets extracted (and is now p), which is "/3" in
1879          * this case. The three is the session id, and that can be mapped.
1880          */
1881         e = startswith(p, "/");
1882
1883         if (e)
1884                 *slice = strdup(e);
1885         else
1886                 *slice = strdup(p);
1887
1888         return 0;
1889 #endif // 0
1890 }
1891
1892 int cg_pid_get_slice(pid_t pid, char **slice) {
1893         _cleanup_free_ char *cgroup = NULL;
1894         int r;
1895
1896         assert(slice);
1897
1898         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1899         log_debug_elogind("Found cgroup %s for pid %u (result %d)",
1900                           cgroup, pid, r);
1901         if (r < 0)
1902                 return r;
1903
1904         return cg_path_get_slice(cgroup, slice);
1905 }
1906
1907 int cg_path_get_user_slice(const char *p, char **slice) {
1908 #if 0 /// UNNEEDED by elogind
1909         const char *t;
1910 #endif // 0
1911         assert(p);
1912         assert(slice);
1913
1914 #if 0 /// nothing to skip in elogind
1915         t = skip_user_prefix(p);
1916         if (!t)
1917                 return -ENXIO;
1918 #endif // 0
1919
1920 #if 0 /// UNNEEDED by elogind
1921         /* And now it looks pretty much the same as for a system
1922          * slice, so let's just use the same parser from here on. */
1923         return cg_path_get_slice(t, slice);
1924 #else
1925         /* In elogind there is nothing to skip, we can use the path
1926          * directly. Generally speaking this is always a session id
1927          * to user mapping. */
1928         return cg_path_get_slice(p, slice);
1929 #endif // 0
1930 }
1931
1932 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1933         _cleanup_free_ char *cgroup = NULL;
1934         int r;
1935
1936         assert(slice);
1937
1938         r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1939         if (r < 0)
1940                 return r;
1941
1942         return cg_path_get_user_slice(cgroup, slice);
1943 }
1944
1945 char *cg_escape(const char *p) {
1946         bool need_prefix = false;
1947
1948         /* This implements very minimal escaping for names to be used
1949          * as file names in the cgroup tree: any name which might
1950          * conflict with a kernel name or is prefixed with '_' is
1951          * prefixed with a '_'. That way, when reading cgroup names it
1952          * is sufficient to remove a single prefixing underscore if
1953          * there is one. */
1954
1955         /* The return value of this function (unlike cg_unescape())
1956          * needs free()! */
1957
1958         if (IN_SET(p[0], 0, '_', '.') ||
1959             streq(p, "notify_on_release") ||
1960             streq(p, "release_agent") ||
1961             streq(p, "tasks") ||
1962             startswith(p, "cgroup."))
1963                 need_prefix = true;
1964         else {
1965                 const char *dot;
1966
1967                 dot = strrchr(p, '.');
1968                 if (dot) {
1969                         CGroupController c;
1970                         size_t l = dot - p;
1971
1972                         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1973                                 const char *n;
1974
1975                                 n = cgroup_controller_to_string(c);
1976
1977                                 if (l != strlen(n))
1978                                         continue;
1979
1980                                 if (memcmp(p, n, l) != 0)
1981                                         continue;
1982
1983                                 need_prefix = true;
1984                                 break;
1985                         }
1986                 }
1987         }
1988
1989         if (need_prefix)
1990                 return strappend("_", p);
1991
1992         return strdup(p);
1993 }
1994
1995 char *cg_unescape(const char *p) {
1996         assert(p);
1997
1998         /* The return value of this function (unlike cg_escape())
1999          * doesn't need free()! */
2000
2001         if (p[0] == '_')
2002                 return (char*) p+1;
2003
2004         return (char*) p;
2005 }
2006
2007 #define CONTROLLER_VALID                        \
2008         DIGITS LETTERS                          \
2009         "_"
2010
2011 bool cg_controller_is_valid(const char *p) {
2012         const char *t, *s;
2013
2014         if (!p)
2015                 return false;
2016
2017         if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
2018                 return true;
2019
2020         s = startswith(p, "name=");
2021         if (s)
2022                 p = s;
2023
2024         if (IN_SET(*p, 0, '_'))
2025                 return false;
2026
2027         for (t = p; *t; t++)
2028                 if (!strchr(CONTROLLER_VALID, *t))
2029                         return false;
2030
2031         if (t - p > FILENAME_MAX)
2032                 return false;
2033
2034         return true;
2035 }
2036
2037 #if 0 /// UNNEEDED by elogind
2038 int cg_slice_to_path(const char *unit, char **ret) {
2039         _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
2040         const char *dash;
2041         int r;
2042
2043         assert(unit);
2044         assert(ret);
2045
2046         if (streq(unit, SPECIAL_ROOT_SLICE)) {
2047                 char *x;
2048
2049                 x = strdup("");
2050                 if (!x)
2051                         return -ENOMEM;
2052                 *ret = x;
2053                 return 0;
2054         }
2055
2056         if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
2057                 return -EINVAL;
2058
2059         if (!endswith(unit, ".slice"))
2060                 return -EINVAL;
2061
2062         r = unit_name_to_prefix(unit, &p);
2063         if (r < 0)
2064                 return r;
2065
2066         dash = strchr(p, '-');
2067
2068         /* Don't allow initial dashes */
2069         if (dash == p)
2070                 return -EINVAL;
2071
2072         while (dash) {
2073                 _cleanup_free_ char *escaped = NULL;
2074                 char n[dash - p + sizeof(".slice")];
2075
2076 #if HAS_FEATURE_MEMORY_SANITIZER
2077                 /* msan doesn't instrument stpncpy, so it thinks
2078                  * n is later used unitialized:
2079                  * https://github.com/google/sanitizers/issues/926
2080                  */
2081                 zero(n);
2082 #endif
2083
2084                 /* Don't allow trailing or double dashes */
2085                 if (IN_SET(dash[1], 0, '-'))
2086                         return -EINVAL;
2087
2088                 strcpy(stpncpy(n, p, dash - p), ".slice");
2089                 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
2090                         return -EINVAL;
2091
2092                 escaped = cg_escape(n);
2093                 if (!escaped)
2094                         return -ENOMEM;
2095
2096                 if (!strextend(&s, escaped, "/", NULL))
2097                         return -ENOMEM;
2098
2099                 dash = strchr(dash+1, '-');
2100         }
2101
2102         e = cg_escape(unit);
2103         if (!e)
2104                 return -ENOMEM;
2105
2106         if (!strextend(&s, e, NULL))
2107                 return -ENOMEM;
2108
2109         *ret = TAKE_PTR(s);
2110
2111         return 0;
2112 }
2113 #endif // 0
2114
2115 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
2116         _cleanup_free_ char *p = NULL;
2117         int r;
2118
2119         r = cg_get_path(controller, path, attribute, &p);
2120         if (r < 0)
2121                 return r;
2122
2123         return write_string_file(p, value, 0);
2124 }
2125
2126 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
2127         _cleanup_free_ char *p = NULL;
2128         int r;
2129
2130         r = cg_get_path(controller, path, attribute, &p);
2131         if (r < 0)
2132                 return r;
2133
2134         return read_one_line_file(p, ret);
2135 }
2136
2137 #if 0 /// UNNEEDED by elogind
2138 int cg_get_keyed_attribute(
2139                 const char *controller,
2140                 const char *path,
2141                 const char *attribute,
2142                 char **keys,
2143                 char **ret_values) {
2144
2145         _cleanup_free_ char *filename = NULL, *contents = NULL;
2146         const char *p;
2147         size_t n, i, n_done = 0;
2148         char **v;
2149         int r;
2150
2151         /* Reads one or more fields of a cgroupsv2 keyed attribute file. The 'keys' parameter should be an strv with
2152          * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
2153          * entries as 'keys'. On success each entry will be set to the value of the matching key.
2154          *
2155          * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
2156
2157         r = cg_get_path(controller, path, attribute, &filename);
2158         if (r < 0)
2159                 return r;
2160
2161         r = read_full_file(filename, &contents, NULL);
2162         if (r < 0)
2163                 return r;
2164
2165         n = strv_length(keys);
2166         if (n == 0) /* No keys to retrieve? That's easy, we are done then */
2167                 return 0;
2168
2169         /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
2170         v = newa0(char*, n);
2171
2172         for (p = contents; *p;) {
2173                 const char *w = NULL;
2174
2175                 for (i = 0; i < n; i++)
2176                         if (!v[i]) {
2177                                 w = first_word(p, keys[i]);
2178                                 if (w)
2179                                         break;
2180                         }
2181
2182                 if (w) {
2183                         size_t l;
2184
2185                         l = strcspn(w, NEWLINE);
2186                         v[i] = strndup(w, l);
2187                         if (!v[i]) {
2188                                 r = -ENOMEM;
2189                                 goto fail;
2190                         }
2191
2192                         n_done++;
2193                         if (n_done >= n)
2194                                 goto done;
2195
2196                         p = w + l;
2197                 } else
2198                         p += strcspn(p, NEWLINE);
2199
2200                 p += strspn(p, NEWLINE);
2201         }
2202
2203         r = -ENXIO;
2204
2205 fail:
2206         for (i = 0; i < n; i++)
2207                 free(v[i]);
2208
2209         return r;
2210
2211 done:
2212         memcpy(ret_values, v, sizeof(char*) * n);
2213         return 0;
2214
2215 }
2216
2217 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2218         CGroupController c;
2219         int r;
2220
2221         /* This one will create a cgroup in our private tree, but also
2222          * duplicate it in the trees specified in mask, and remove it
2223          * in all others */
2224
2225         /* First create the cgroup in our own hierarchy. */
2226         r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2227         if (r < 0)
2228                 return r;
2229
2230         /* If we are in the unified hierarchy, we are done now */
2231         r = cg_all_unified();
2232         if (r < 0)
2233                 return r;
2234         if (r > 0)
2235                 return 0;
2236
2237         /* Otherwise, do the same in the other hierarchies */
2238         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2239                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2240                 const char *n;
2241
2242                 n = cgroup_controller_to_string(c);
2243
2244                 if (mask & bit)
2245                         (void) cg_create(n, path);
2246                 else if (supported & bit)
2247                         (void) cg_trim(n, path, true);
2248         }
2249
2250         return 0;
2251 }
2252
2253 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2254         CGroupController c;
2255         int r;
2256
2257         r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2258         if (r < 0)
2259                 return r;
2260
2261         r = cg_all_unified();
2262         if (r < 0)
2263                 return r;
2264         if (r > 0)
2265                 return 0;
2266
2267         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2268                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2269                 const char *p = NULL;
2270
2271                 if (!(supported & bit))
2272                         continue;
2273
2274                 if (path_callback)
2275                         p = path_callback(bit, userdata);
2276
2277                 if (!p)
2278                         p = path;
2279
2280                 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2281         }
2282
2283         return 0;
2284 }
2285
2286 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2287         Iterator i;
2288         void *pidp;
2289         int r = 0;
2290
2291         SET_FOREACH(pidp, pids, i) {
2292                 pid_t pid = PTR_TO_PID(pidp);
2293                 int q;
2294
2295                 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2296                 if (q < 0 && r >= 0)
2297                         r = q;
2298         }
2299
2300         return r;
2301 }
2302
2303 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2304         CGroupController c;
2305         int r = 0, q;
2306
2307         if (!path_equal(from, to))  {
2308                 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2309                 if (r < 0)
2310                         return r;
2311         }
2312
2313         q = cg_all_unified();
2314         if (q < 0)
2315                 return q;
2316         if (q > 0)
2317                 return r;
2318
2319         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2320                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2321                 const char *p = NULL;
2322
2323                 if (!(supported & bit))
2324                         continue;
2325
2326                 if (to_callback)
2327                         p = to_callback(bit, userdata);
2328
2329                 if (!p)
2330                         p = to;
2331
2332                 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2333         }
2334
2335         return 0;
2336 }
2337
2338 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2339         CGroupController c;
2340         int r, q;
2341
2342         r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2343         if (r < 0)
2344                 return r;
2345
2346         q = cg_all_unified();
2347         if (q < 0)
2348                 return q;
2349         if (q > 0)
2350                 return r;
2351
2352         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2353                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2354
2355                 if (!(supported & bit))
2356                         continue;
2357
2358                 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2359         }
2360
2361         return 0;
2362 }
2363 #endif // 0
2364
2365 int cg_mask_to_string(CGroupMask mask, char **ret) {
2366         _cleanup_free_ char *s = NULL;
2367         size_t n = 0, allocated = 0;
2368         bool space = false;
2369         CGroupController c;
2370
2371         assert(ret);
2372
2373         if (mask == 0) {
2374                 *ret = NULL;
2375                 return 0;
2376         }
2377
2378         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2379                 const char *k;
2380                 size_t l;
2381
2382                 if (!(mask & CGROUP_CONTROLLER_TO_MASK(c)))
2383                         continue;
2384
2385                 k = cgroup_controller_to_string(c);
2386                 l = strlen(k);
2387
2388                 if (!GREEDY_REALLOC(s, allocated, n + space + l + 1))
2389                         return -ENOMEM;
2390
2391                 if (space)
2392                         s[n] = ' ';
2393                 memcpy(s + n + space, k, l);
2394                 n += space + l;
2395
2396                 space = true;
2397         }
2398
2399         assert(s);
2400
2401         s[n] = 0;
2402         *ret = TAKE_PTR(s);
2403
2404         return 0;
2405 }
2406
2407 int cg_mask_from_string(const char *value, CGroupMask *mask) {
2408         assert(mask);
2409         assert(value);
2410
2411         for (;;) {
2412                 _cleanup_free_ char *n = NULL;
2413                 CGroupController v;
2414                 int r;
2415
2416                 r = extract_first_word(&value, &n, NULL, 0);
2417                 if (r < 0)
2418                         return r;
2419                 if (r == 0)
2420                         break;
2421
2422                 v = cgroup_controller_from_string(n);
2423                 if (v < 0)
2424                         continue;
2425
2426                 *mask |= CGROUP_CONTROLLER_TO_MASK(v);
2427         }
2428         return 0;
2429 }
2430
2431 int cg_mask_supported(CGroupMask *ret) {
2432         CGroupMask mask = 0;
2433         int r;
2434
2435         /* Determines the mask of supported cgroup controllers. Only
2436          * includes controllers we can make sense of and that are
2437          * actually accessible. */
2438
2439         r = cg_all_unified();
2440         if (r < 0)
2441                 return r;
2442         if (r > 0) {
2443                 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2444
2445                 /* In the unified hierarchy we can read the supported
2446                  * and accessible controllers from a the top-level
2447                  * cgroup attribute */
2448
2449                 r = cg_get_root_path(&root);
2450                 if (r < 0)
2451                         return r;
2452
2453                 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2454                 if (r < 0)
2455                         return r;
2456
2457                 r = read_one_line_file(path, &controllers);
2458                 if (r < 0)
2459                         return r;
2460
2461                 r = cg_mask_from_string(controllers, &mask);
2462                 if (r < 0)
2463                         return r;
2464
2465                 /* Currently, we support the cpu, memory, io and pids
2466                  * controller in the unified hierarchy, mask
2467                  * everything else off. */
2468                 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2469
2470         } else {
2471                 CGroupController c;
2472
2473                 /* In the legacy hierarchy, we check whether which
2474                  * hierarchies are mounted. */
2475
2476                 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2477                         const char *n;
2478
2479                         n = cgroup_controller_to_string(c);
2480                         if (controller_is_accessible(n) >= 0)
2481                                 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2482                 }
2483         }
2484
2485         *ret = mask;
2486         return 0;
2487 }
2488
2489 #if 0 /// UNNEEDED by elogind
2490 int cg_kernel_controllers(Set **ret) {
2491         _cleanup_set_free_free_ Set *controllers = NULL;
2492         _cleanup_fclose_ FILE *f = NULL;
2493         int r;
2494
2495         assert(ret);
2496
2497         /* Determines the full list of kernel-known controllers. Might
2498          * include controllers we don't actually support, arbitrary
2499          * named hierarchies and controllers that aren't currently
2500          * accessible (because not mounted). */
2501
2502         controllers = set_new(&string_hash_ops);
2503         if (!controllers)
2504                 return -ENOMEM;
2505
2506         f = fopen("/proc/cgroups", "re");
2507         if (!f) {
2508                 if (errno == ENOENT) {
2509                         *ret = NULL;
2510                         return 0;
2511                 }
2512
2513                 return -errno;
2514         }
2515
2516         (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
2517
2518         /* Ignore the header line */
2519         (void) read_line(f, (size_t) -1, NULL);
2520
2521         for (;;) {
2522                 char *controller;
2523                 int enabled = 0;
2524
2525                 errno = 0;
2526                 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2527
2528                         if (feof(f))
2529                                 break;
2530
2531                         if (ferror(f) && errno > 0)
2532                                 return -errno;
2533
2534                         return -EBADMSG;
2535                 }
2536
2537                 if (!enabled) {
2538                         free(controller);
2539                         continue;
2540                 }
2541
2542                 if (!cg_controller_is_valid(controller)) {
2543                         free(controller);
2544                         return -EBADMSG;
2545                 }
2546
2547                 r = set_consume(controllers, controller);
2548                 if (r < 0)
2549                         return r;
2550         }
2551
2552         *ret = TAKE_PTR(controllers);
2553
2554         return 0;
2555 }
2556 #endif // 0
2557
2558 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2559
2560 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup v2 on /sys/fs/cgroup/systemd.  This
2561  * unfortunately broke other tools (such as docker) which expected the v1 "name=systemd" hierarchy on
2562  * /sys/fs/cgroup/systemd.  From v233 and on, the hybrid mode mountnbs v2 on /sys/fs/cgroup/unified and maintains
2563  * "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility with other tools.
2564  *
2565  * To keep live upgrade working, we detect and support v232 layout.  When v232 layout is detected, to keep cgroup v2
2566  * process management but disable the compat dual layout, we return %true on
2567  * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and %false on cg_hybrid_unified().
2568  */
2569 static thread_local bool unified_systemd_v232;
2570
2571 static int cg_unified_update(void) {
2572
2573         struct statfs fs;
2574
2575         /* Checks if we support the unified hierarchy. Returns an
2576          * error when the cgroup hierarchies aren't mounted yet or we
2577          * have any other trouble determining if the unified hierarchy
2578          * is supported. */
2579
2580         if (unified_cache >= CGROUP_UNIFIED_NONE)
2581                 return 0;
2582
2583         if (statfs("/sys/fs/cgroup/", &fs) < 0)
2584                 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/\") failed: %m");
2585
2586         if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2587                 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
2588                 unified_cache = CGROUP_UNIFIED_ALL;
2589 #if 0 /// The handling of cgroups is a bit different with elogind
2590         } else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2591                         log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2592 #else
2593         } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)
2594               || F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2595 #endif // 0
2596                 if (statfs("/sys/fs/cgroup/unified/", &fs) == 0 &&
2597                     F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2598                         unified_cache = CGROUP_UNIFIED_SYSTEMD;
2599                         unified_systemd_v232 = false;
2600                 } else {
2601 #if 0 /// There is no sub-grouping within elogind
2602                         if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2603                                 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2604
2605                         if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2606                                 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2607                                 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2608                                 unified_systemd_v232 = true;
2609                         } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)) {
2610                                 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2611                                 unified_cache = CGROUP_UNIFIED_NONE;
2612                         } else {
2613                                 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2614                                           (unsigned long long) fs.f_type);
2615                                 unified_cache = CGROUP_UNIFIED_NONE;
2616                         }
2617 #else
2618                         unified_cache = CGROUP_UNIFIED_NONE;
2619 #endif // 0
2620                 }
2621         } else {
2622                 log_debug("Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2623                           (unsigned long long) fs.f_type);
2624                 return -ENOMEDIUM;
2625         }
2626
2627         return 0;
2628 }
2629
2630 int cg_unified_controller(const char *controller) {
2631         int r;
2632
2633         r = cg_unified_update();
2634         if (r < 0)
2635                 return r;
2636
2637         if (unified_cache == CGROUP_UNIFIED_NONE)
2638                 return false;
2639
2640         if (unified_cache >= CGROUP_UNIFIED_ALL)
2641                 return true;
2642
2643 #if 0 /// only if elogind is the controller we can use cgroups2 in hybrid mode
2644         return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER);
2645 #else
2646         return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER_HYBRID);
2647 #endif // 0
2648 }
2649
2650 int cg_all_unified(void) {
2651         int r;
2652
2653         r = cg_unified_update();
2654         if (r < 0)
2655                 return r;
2656
2657         return unified_cache >= CGROUP_UNIFIED_ALL;
2658 }
2659
2660 int cg_hybrid_unified(void) {
2661         int r;
2662
2663         r = cg_unified_update();
2664         if (r < 0)
2665                 return r;
2666
2667         return unified_cache == CGROUP_UNIFIED_SYSTEMD && !unified_systemd_v232;
2668 }
2669
2670 int cg_unified_flush(void) {
2671         unified_cache = CGROUP_UNIFIED_UNKNOWN;
2672
2673         return cg_unified_update();
2674 }
2675
2676 #if 0 /// UNNEEDED by elogind
2677 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2678         _cleanup_fclose_ FILE *f = NULL;
2679         _cleanup_free_ char *fs = NULL;
2680         CGroupController c;
2681         int r;
2682
2683         assert(p);
2684
2685         if (supported == 0)
2686                 return 0;
2687
2688         r = cg_all_unified();
2689         if (r < 0)
2690                 return r;
2691         if (r == 0) /* on the legacy hiearchy there's no joining of controllers defined */
2692                 return 0;
2693
2694         r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2695         if (r < 0)
2696                 return r;
2697
2698         for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2699                 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2700                 const char *n;
2701
2702                 if (!(supported & bit))
2703                         continue;
2704
2705                 n = cgroup_controller_to_string(c);
2706                 {
2707                         char s[1 + strlen(n) + 1];
2708
2709                         s[0] = mask & bit ? '+' : '-';
2710                         strcpy(s + 1, n);
2711
2712                         if (!f) {
2713                                 f = fopen(fs, "we");
2714                                 if (!f) {
2715                                         log_debug_errno(errno, "Failed to open cgroup.subtree_control file of %s: %m", p);
2716                                         break;
2717                                 }
2718                         }
2719
2720                         r = write_string_stream(f, s, 0);
2721                         if (r < 0) {
2722                                 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2723                                 clearerr(f);
2724                         }
2725                 }
2726         }
2727
2728         return 0;
2729 }
2730 #endif // 0
2731
2732 bool cg_is_unified_wanted(void) {
2733         static thread_local int wanted = -1;
2734 #if 0 /// UNNEEDED by elogind
2735         int r;
2736         bool b;
2737 #endif // 0
2738         const bool is_default = DEFAULT_HIERARCHY == CGROUP_UNIFIED_ALL;
2739
2740         /* If we have a cached value, return that. */
2741         if (wanted >= 0)
2742                 return wanted;
2743
2744         /* If the hierarchy is already mounted, then follow whatever
2745          * was chosen for it. */
2746         if (cg_unified_flush() >= 0)
2747                 return (wanted = unified_cache >= CGROUP_UNIFIED_ALL);
2748
2749 #if 0 /// elogind is not init and has no business with kernel command line
2750         /* Otherwise, let's see what the kernel command line has to say.
2751          * Since checking is expensive, cache a non-error result. */
2752         r = proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b);
2753
2754         return (wanted = r > 0 ? b : is_default);
2755 #else
2756         return is_default;
2757 #endif // 0
2758 }
2759
2760 bool cg_is_legacy_wanted(void) {
2761         static thread_local int wanted = -1;
2762
2763         /* If we have a cached value, return that. */
2764         if (wanted >= 0)
2765                 return wanted;
2766
2767         /* Check if we have cgroups2 already mounted. */
2768         if (cg_unified_flush() >= 0 &&
2769             unified_cache == CGROUP_UNIFIED_ALL)
2770                 return (wanted = false);
2771
2772         /* Otherwise, assume that at least partial legacy is wanted,
2773          * since cgroups2 should already be mounted at this point. */
2774         return (wanted = true);
2775 }
2776
2777 bool cg_is_hybrid_wanted(void) {
2778         static thread_local int wanted = -1;
2779 #if 0 /// UNNEEDED by elogind
2780         int r;
2781         bool b;
2782 #endif // 0
2783         const bool is_default = DEFAULT_HIERARCHY >= CGROUP_UNIFIED_SYSTEMD;
2784         /* We default to true if the default is "hybrid", obviously,
2785          * but also when the default is "unified", because if we get
2786          * called, it means that unified hierarchy was not mounted. */
2787
2788         /* If we have a cached value, return that. */
2789         if (wanted >= 0)
2790                 return wanted;
2791
2792         /* If the hierarchy is already mounted, then follow whatever
2793          * was chosen for it. */
2794         if (cg_unified_flush() >= 0 &&
2795             unified_cache == CGROUP_UNIFIED_ALL)
2796                 return (wanted = false);
2797
2798 #if 0 /// elogind is not init and has no business with kernel command line
2799         /* Otherwise, let's see what the kernel command line has to say.
2800          * Since checking is expensive, cache a non-error result. */
2801         r = proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b);
2802
2803         /* The meaning of the kernel option is reversed wrt. to the return value
2804          * of this function, hence the negation. */
2805         return (wanted = r > 0 ? !b : is_default);
2806 #else
2807         return is_default;
2808 #endif // 0
2809 }
2810
2811 #if 0 /// UNNEEDED by elogind
2812 int cg_weight_parse(const char *s, uint64_t *ret) {
2813         uint64_t u;
2814         int r;
2815
2816         if (isempty(s)) {
2817                 *ret = CGROUP_WEIGHT_INVALID;
2818                 return 0;
2819         }
2820
2821         r = safe_atou64(s, &u);
2822         if (r < 0)
2823                 return r;
2824
2825         if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2826                 return -ERANGE;
2827
2828         *ret = u;
2829         return 0;
2830 }
2831
2832 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2833         [CGROUP_IO_RBPS_MAX]    = CGROUP_LIMIT_MAX,
2834         [CGROUP_IO_WBPS_MAX]    = CGROUP_LIMIT_MAX,
2835         [CGROUP_IO_RIOPS_MAX]   = CGROUP_LIMIT_MAX,
2836         [CGROUP_IO_WIOPS_MAX]   = CGROUP_LIMIT_MAX,
2837 };
2838
2839 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2840         [CGROUP_IO_RBPS_MAX]    = "IOReadBandwidthMax",
2841         [CGROUP_IO_WBPS_MAX]    = "IOWriteBandwidthMax",
2842         [CGROUP_IO_RIOPS_MAX]   = "IOReadIOPSMax",
2843         [CGROUP_IO_WIOPS_MAX]   = "IOWriteIOPSMax",
2844 };
2845
2846 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2847
2848 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2849         uint64_t u;
2850         int r;
2851
2852         if (isempty(s)) {
2853                 *ret = CGROUP_CPU_SHARES_INVALID;
2854                 return 0;
2855         }
2856
2857         r = safe_atou64(s, &u);
2858         if (r < 0)
2859                 return r;
2860
2861         if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2862                 return -ERANGE;
2863
2864         *ret = u;
2865         return 0;
2866 }
2867
2868 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2869         uint64_t u;
2870         int r;
2871
2872         if (isempty(s)) {
2873                 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2874                 return 0;
2875         }
2876
2877         r = safe_atou64(s, &u);
2878         if (r < 0)
2879                 return r;
2880
2881         if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2882                 return -ERANGE;
2883
2884         *ret = u;
2885         return 0;
2886 }
2887 #endif // 0
2888
2889 bool is_cgroup_fs(const struct statfs *s) {
2890         return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2891                is_fs_type(s, CGROUP2_SUPER_MAGIC);
2892 }
2893
2894 bool fd_is_cgroup_fs(int fd) {
2895         struct statfs s;
2896
2897         if (fstatfs(fd, &s) < 0)
2898                 return -errno;
2899
2900         return is_cgroup_fs(&s);
2901 }
2902
2903 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2904         [CGROUP_CONTROLLER_CPU] = "cpu",
2905         [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2906         [CGROUP_CONTROLLER_IO] = "io",
2907         [CGROUP_CONTROLLER_BLKIO] = "blkio",
2908         [CGROUP_CONTROLLER_MEMORY] = "memory",
2909         [CGROUP_CONTROLLER_DEVICES] = "devices",
2910         [CGROUP_CONTROLLER_PIDS] = "pids",
2911 };
2912
2913 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);