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