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