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