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