2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
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.
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.
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/>.
29 //#include <sys/statfs.h>
30 #include <sys/types.h>
33 #include "alloc-util.h"
34 #include "cgroup-util.h"
36 #include "dirent-util.h"
37 #include "extract-word.h"
40 #include "formats-util.h"
43 #include "login-util.h"
45 //#include "missing.h"
47 #include "parse-util.h"
48 #include "path-util.h"
49 #include "proc-cmdline.h"
50 #include "process-util.h"
52 //#include "special.h"
53 #include "stat-util.h"
54 #include "stdio-util.h"
55 #include "string-table.h"
56 #include "string-util.h"
57 #include "unit-name.h"
58 #include "user-util.h"
60 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
61 _cleanup_free_ char *fs = NULL;
67 r = cg_get_path(controller, path, "cgroup.procs", &fs);
79 int cg_read_pid(FILE *f, pid_t *_pid) {
82 /* Note that the cgroup.procs might contain duplicates! See
83 * cgroups.txt for details. */
89 if (fscanf(f, "%lu", &ul) != 1) {
94 return errno > 0 ? -errno : -EIO;
104 int cg_read_event(const char *controller, const char *path, const char *event,
107 _cleanup_free_ char *events = NULL, *content = NULL;
111 r = cg_get_path(controller, path, "cgroup.events", &events);
115 r = read_full_file(events, &content, NULL);
120 while ((line = strsep(&p, "\n"))) {
123 key = strsep(&line, " ");
127 if (strcmp(key, event))
137 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
138 _cleanup_free_ char *fs = NULL;
144 /* This is not recursive! */
146 r = cg_get_path(controller, path, NULL, &fs);
158 int cg_read_subgroup(DIR *d, char **fn) {
164 FOREACH_DIRENT_ALL(de, d, return -errno) {
167 if (de->d_type != DT_DIR)
170 if (streq(de->d_name, ".") ||
171 streq(de->d_name, ".."))
174 b = strdup(de->d_name);
185 int cg_rmdir(const char *controller, const char *path) {
186 _cleanup_free_ char *p = NULL;
189 r = cg_get_path(controller, path, NULL, &p);
194 if (r < 0 && errno != ENOENT)
200 int cg_kill(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, Set *s) {
201 _cleanup_set_free_ Set *allocated_set = NULL;
208 /* This goes through the tasks list and kills them all. This
209 * is repeated until no further processes are added to the
210 * tasks list, to properly handle forking processes */
213 s = allocated_set = set_new(NULL);
221 _cleanup_fclose_ FILE *f = NULL;
225 r = cg_enumerate_processes(controller, path, &f);
227 if (ret >= 0 && r != -ENOENT)
233 while ((r = cg_read_pid(f, &pid)) > 0) {
235 if (ignore_self && pid == my_pid)
238 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
241 /* If we haven't killed this process yet, kill
243 if (kill(pid, sig) < 0) {
244 if (ret >= 0 && errno != ESRCH)
247 if (sigcont && sig != SIGKILL)
248 (void) kill(pid, SIGCONT);
256 r = set_put(s, PID_TO_PTR(pid));
272 /* To avoid racing against processes which fork
273 * quicker than we can kill them we repeat this until
274 * no new pids need to be killed. */
281 int cg_kill_recursive(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, bool rem, Set *s) {
282 _cleanup_set_free_ Set *allocated_set = NULL;
283 _cleanup_closedir_ DIR *d = NULL;
291 s = allocated_set = set_new(NULL);
296 ret = cg_kill(controller, path, sig, sigcont, ignore_self, s);
298 r = cg_enumerate_subgroups(controller, path, &d);
300 if (ret >= 0 && r != -ENOENT)
306 while ((r = cg_read_subgroup(d, &fn)) > 0) {
307 _cleanup_free_ char *p = NULL;
309 p = strjoin(path, "/", fn, NULL);
314 r = cg_kill_recursive(controller, p, sig, sigcont, ignore_self, rem, s);
315 if (r != 0 && ret >= 0)
319 if (ret >= 0 && r < 0)
323 r = cg_rmdir(controller, path);
324 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
331 int cg_migrate(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self) {
333 _cleanup_set_free_ Set *s = NULL;
348 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
349 cfrom, pfrom, cto, pto,
350 ignore_self ? "ignoring self" : "watching self");
352 _cleanup_fclose_ FILE *f = NULL;
356 r = cg_enumerate_processes(cfrom, pfrom, &f);
358 if (ret >= 0 && r != -ENOENT)
364 while ((r = cg_read_pid(f, &pid)) > 0) {
366 /* This might do weird stuff if we aren't a
367 * single-threaded program. However, we
368 * luckily know we are not */
369 if (ignore_self && pid == my_pid)
372 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
375 /* Ignore kernel threads. Since they can only
376 * exist in the root cgroup, we only check for
379 (isempty(pfrom) || path_equal(pfrom, "/")) &&
380 is_kernel_thread(pid) > 0)
383 r = cg_attach(cto, pto, pid);
385 if (ret >= 0 && r != -ESRCH)
392 r = set_put(s, PID_TO_PTR(pid));
412 int cg_migrate_recursive(
420 _cleanup_closedir_ DIR *d = NULL;
429 ret = cg_migrate(cfrom, pfrom, cto, pto, ignore_self);
431 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
433 if (ret >= 0 && r != -ENOENT)
439 while ((r = cg_read_subgroup(d, &fn)) > 0) {
440 _cleanup_free_ char *p = NULL;
442 p = strjoin(pfrom, "/", fn, NULL);
447 r = cg_migrate_recursive(cfrom, p, cto, pto, ignore_self, rem);
448 if (r != 0 && ret >= 0)
452 if (r < 0 && ret >= 0)
456 r = cg_rmdir(cfrom, pfrom);
457 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
464 int cg_migrate_recursive_fallback(
479 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, ignore_self, rem);
481 char prefix[strlen(pto) + 1];
483 /* This didn't work? Then let's try all prefixes of the destination */
485 PATH_FOREACH_PREFIX(prefix, pto) {
488 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, ignore_self, rem);
497 static const char *controller_to_dirname(const char *controller) {
502 /* Converts a controller name to the directory name below
503 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
504 * just cuts off the name= prefixed used for named
505 * hierarchies, if it is specified. */
507 e = startswith(controller, "name=");
514 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
521 dn = controller_to_dirname(controller);
523 if (isempty(path) && isempty(suffix))
524 t = strappend("/sys/fs/cgroup/", dn);
525 else if (isempty(path))
526 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
527 else if (isempty(suffix))
528 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
530 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
538 static int join_path_unified(const char *path, const char *suffix, char **fs) {
543 if (isempty(path) && isempty(suffix))
544 t = strdup("/sys/fs/cgroup");
545 else if (isempty(path))
546 t = strappend("/sys/fs/cgroup/", suffix);
547 else if (isempty(suffix))
548 t = strappend("/sys/fs/cgroup/", path);
550 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
558 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
566 /* If no controller is specified, we return the path
567 * *below* the controllers, without any prefix. */
569 if (!path && !suffix)
577 t = strjoin(path, "/", suffix, NULL);
581 *fs = path_kill_slashes(t);
585 if (!cg_controller_is_valid(controller))
588 unified = cg_unified();
593 r = join_path_unified(path, suffix, fs);
595 r = join_path_legacy(controller, path, suffix, fs);
599 path_kill_slashes(*fs);
603 static int controller_is_accessible(const char *controller) {
608 /* Checks whether a specific controller is accessible,
609 * i.e. its hierarchy mounted. In the unified hierarchy all
610 * controllers are considered accessible, except for the named
613 if (!cg_controller_is_valid(controller))
616 unified = cg_unified();
620 /* We don't support named hierarchies if we are using
621 * the unified hierarchy. */
623 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
626 if (startswith(controller, "name="))
632 dn = controller_to_dirname(controller);
633 cc = strjoina("/sys/fs/cgroup/", dn);
635 if (laccess(cc, F_OK) < 0)
642 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
648 /* Check if the specified controller is actually accessible */
649 r = controller_is_accessible(controller);
653 return cg_get_path(controller, path, suffix, fs);
656 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
661 if (typeflag != FTW_DP)
664 if (ftwbuf->level < 1)
671 int cg_trim(const char *controller, const char *path, bool delete_root) {
672 _cleanup_free_ char *fs = NULL;
677 r = cg_get_path(controller, path, NULL, &fs);
682 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
692 if (rmdir(fs) < 0 && errno != ENOENT)
699 int cg_create(const char *controller, const char *path) {
700 _cleanup_free_ char *fs = NULL;
703 r = cg_get_path_and_check(controller, path, NULL, &fs);
707 r = mkdir_parents(fs, 0755);
711 if (mkdir(fs, 0755) < 0) {
722 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
727 r = cg_create(controller, path);
731 q = cg_attach(controller, path, pid);
735 /* This does not remove the cgroup on failure */
739 int cg_attach(const char *controller, const char *path, pid_t pid) {
740 _cleanup_free_ char *fs = NULL;
741 char c[DECIMAL_STR_MAX(pid_t) + 2];
747 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
754 xsprintf(c, PID_FMT "\n", pid);
756 return write_string_file(fs, c, 0);
759 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
766 r = cg_attach(controller, path, pid);
768 char prefix[strlen(path) + 1];
770 /* This didn't work? Then let's try all prefixes of
773 PATH_FOREACH_PREFIX(prefix, path) {
776 q = cg_attach(controller, prefix, pid);
785 #if 0 /// UNNEEDED by elogind
786 int cg_set_group_access(
787 const char *controller,
793 _cleanup_free_ char *fs = NULL;
796 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
799 if (mode != MODE_INVALID)
802 r = cg_get_path(controller, path, NULL, &fs);
806 return chmod_and_chown(fs, mode, uid, gid);
809 int cg_set_task_access(
810 const char *controller,
816 _cleanup_free_ char *fs = NULL, *procs = NULL;
821 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
824 if (mode != MODE_INVALID)
827 r = cg_get_path(controller, path, "cgroup.procs", &fs);
831 r = chmod_and_chown(fs, mode, uid, gid);
835 unified = cg_unified();
841 /* Compatibility, Always keep values for "tasks" in sync with
843 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
844 (void) chmod_and_chown(procs, mode, uid, gid);
850 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
851 _cleanup_fclose_ FILE *f = NULL;
860 unified = cg_unified();
865 if (!cg_controller_is_valid(controller))
868 controller = SYSTEMD_CGROUP_CONTROLLER;
870 cs = strlen(controller);
873 fs = procfs_file_alloca(pid, "cgroup");
874 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
875 pid, fs, controller);
878 return errno == ENOENT ? -ESRCH : -errno;
880 FOREACH_LINE(line, f, return -errno) {
886 e = startswith(line, "0:");
896 const char *word, *state;
899 l = strchr(line, ':');
909 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
910 if (k == cs && memcmp(word, controller, cs) == 0) {
920 log_debug_elogind("Found %s:%s", line, e+1);
932 int cg_install_release_agent(const char *controller, const char *agent) {
933 _cleanup_free_ char *fs = NULL, *contents = NULL;
939 unified = cg_unified();
942 if (unified) /* doesn't apply to unified hierarchy */
945 r = cg_get_path(controller, NULL, "release_agent", &fs);
949 r = read_one_line_file(fs, &contents);
953 sc = strstrip(contents);
955 r = write_string_file(fs, agent, 0);
958 } else if (!path_equal(sc, agent))
962 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
966 contents = mfree(contents);
967 r = read_one_line_file(fs, &contents);
971 sc = strstrip(contents);
972 if (streq(sc, "0")) {
973 r = write_string_file(fs, "1", 0);
986 int cg_uninstall_release_agent(const char *controller) {
987 _cleanup_free_ char *fs = NULL;
990 unified = cg_unified();
993 if (unified) /* Doesn't apply to unified hierarchy */
996 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1000 r = write_string_file(fs, "0", 0);
1006 r = cg_get_path(controller, NULL, "release_agent", &fs);
1010 r = write_string_file(fs, "", 0);
1017 int cg_is_empty(const char *controller, const char *path) {
1018 _cleanup_fclose_ FILE *f = NULL;
1024 r = cg_enumerate_processes(controller, path, &f);
1030 r = cg_read_pid(f, &pid);
1037 int cg_is_empty_recursive(const char *controller, const char *path) {
1042 /* The root cgroup is always populated */
1043 if (controller && (isempty(path) || path_equal(path, "/")))
1046 unified = cg_unified();
1051 _cleanup_free_ char *t = NULL;
1053 /* On the unified hierarchy we can check empty state
1054 * via the "populated" attribute of "cgroup.events". */
1056 r = cg_read_event(controller, path, "populated", &t);
1060 return streq(t, "0");
1062 _cleanup_closedir_ DIR *d = NULL;
1065 r = cg_is_empty(controller, path);
1069 r = cg_enumerate_subgroups(controller, path, &d);
1075 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1076 _cleanup_free_ char *p = NULL;
1078 p = strjoin(path, "/", fn, NULL);
1083 r = cg_is_empty_recursive(controller, p);
1094 int cg_split_spec(const char *spec, char **controller, char **path) {
1095 char *t = NULL, *u = NULL;
1101 if (!path_is_safe(spec))
1109 *path = path_kill_slashes(t);
1118 e = strchr(spec, ':');
1120 if (!cg_controller_is_valid(spec))
1137 t = strndup(spec, e-spec);
1140 if (!cg_controller_is_valid(t)) {
1154 if (!path_is_safe(u) ||
1155 !path_is_absolute(u)) {
1161 path_kill_slashes(u);
1177 int cg_mangle_path(const char *path, char **result) {
1178 _cleanup_free_ char *c = NULL, *p = NULL;
1185 /* First, check if it already is a filesystem path */
1186 if (path_startswith(path, "/sys/fs/cgroup")) {
1192 *result = path_kill_slashes(t);
1196 /* Otherwise, treat it as cg spec */
1197 r = cg_split_spec(path, &c, &p);
1201 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1204 int cg_get_root_path(char **path) {
1205 #if 0 /// elogind does not support systemd scopes and slices
1211 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1215 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1217 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1219 e = endswith(p, "/system"); /* even more legacy */
1227 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1231 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1232 _cleanup_free_ char *rt = NULL;
1240 /* If the root was specified let's use that, otherwise
1241 * let's determine it from PID 1 */
1243 r = cg_get_root_path(&rt);
1248 log_debug_elogind("Determined root path: \"%s\"", root);
1251 p = path_startswith(cgroup, root);
1252 if (p && p[0] && (p > cgroup))
1260 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1261 _cleanup_free_ char *raw = NULL;
1268 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1272 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1273 raw, pid, root ? root : "NULL");
1274 r = cg_shift_path(raw, root, &c);
1290 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1295 #if 0 /// UNNEEDED by elogind
1296 int cg_path_decode_unit(const char *cgroup, char **unit) {
1303 n = strcspn(cgroup, "/");
1307 c = strndupa(cgroup, n);
1310 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1321 static bool valid_slice_name(const char *p, size_t n) {
1326 if (n < strlen("x.slice"))
1329 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1335 c = cg_unescape(buf);
1337 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1343 static const char *skip_slices(const char *p) {
1346 /* Skips over all slice assignments */
1351 p += strspn(p, "/");
1353 n = strcspn(p, "/");
1354 if (!valid_slice_name(p, n))
1361 int cg_path_get_unit(const char *path, char **ret) {
1369 e = skip_slices(path);
1371 r = cg_path_decode_unit(e, &unit);
1375 /* We skipped over the slices, don't accept any now */
1376 if (endswith(unit, ".slice")) {
1385 int cg_pid_get_unit(pid_t pid, char **unit) {
1386 _cleanup_free_ char *cgroup = NULL;
1391 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1395 return cg_path_get_unit(cgroup, unit);
1399 * Skip session-*.scope, but require it to be there.
1401 static const char *skip_session(const char *p) {
1407 p += strspn(p, "/");
1409 n = strcspn(p, "/");
1410 if (n < strlen("session-x.scope"))
1413 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1414 char buf[n - 8 - 6 + 1];
1416 memcpy(buf, p + 8, n - 8 - 6);
1419 /* Note that session scopes never need unescaping,
1420 * since they cannot conflict with the kernel's own
1421 * names, hence we don't need to call cg_unescape()
1424 if (!session_id_valid(buf))
1428 p += strspn(p, "/");
1436 * Skip user@*.service, but require it to be there.
1438 static const char *skip_user_manager(const char *p) {
1444 p += strspn(p, "/");
1446 n = strcspn(p, "/");
1447 if (n < strlen("user@x.service"))
1450 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1451 char buf[n - 5 - 8 + 1];
1453 memcpy(buf, p + 5, n - 5 - 8);
1456 /* Note that user manager services never need unescaping,
1457 * since they cannot conflict with the kernel's own
1458 * names, hence we don't need to call cg_unescape()
1461 if (parse_uid(buf, NULL) < 0)
1465 p += strspn(p, "/");
1473 static const char *skip_user_prefix(const char *path) {
1478 /* Skip slices, if there are any */
1479 e = skip_slices(path);
1481 /* Skip the user manager, if it's in the path now... */
1482 t = skip_user_manager(e);
1486 /* Alternatively skip the user session if it is in the path... */
1487 return skip_session(e);
1490 int cg_path_get_user_unit(const char *path, char **ret) {
1496 t = skip_user_prefix(path);
1500 /* And from here on it looks pretty much the same as for a
1501 * system unit, hence let's use the same parser from here
1503 return cg_path_get_unit(t, ret);
1506 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1507 _cleanup_free_ char *cgroup = NULL;
1512 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1516 return cg_path_get_user_unit(cgroup, unit);
1519 int cg_path_get_machine_name(const char *path, char **machine) {
1520 _cleanup_free_ char *u = NULL;
1524 r = cg_path_get_unit(path, &u);
1528 sl = strjoina("/run/systemd/machines/unit:", u);
1529 return readlink_malloc(sl, machine);
1532 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1533 _cleanup_free_ char *cgroup = NULL;
1538 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1542 return cg_path_get_machine_name(cgroup, machine);
1546 int cg_path_get_session(const char *path, char **session) {
1547 #if 0 /// UNNEEDED by elogind
1548 _cleanup_free_ char *unit = NULL;
1554 r = cg_path_get_unit(path, &unit);
1558 start = startswith(unit, "session-");
1561 end = endswith(start, ".scope");
1566 if (!session_id_valid(start))
1569 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1570 wrinkle is that SESSION might be escaped. */
1571 const char *e, *n, *start;
1574 log_debug_elogind("path is \"%s\"", path);
1575 assert(path[0] == '/');
1578 n = strchrnul(e, '/');
1582 start = strndupa(e, n - e);
1583 start = cg_unescape(start);
1592 log_debug_elogind("found session: \"%s\"", start);
1603 int cg_pid_get_session(pid_t pid, char **session) {
1604 _cleanup_free_ char *cgroup = NULL;
1607 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1611 return cg_path_get_session(cgroup, session);
1614 #if 0 /// UNNEEDED by elogind
1615 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1616 _cleanup_free_ char *slice = NULL;
1622 r = cg_path_get_slice(path, &slice);
1626 start = startswith(slice, "user-");
1629 end = endswith(start, ".slice");
1634 if (parse_uid(start, uid) < 0)
1640 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1641 _cleanup_free_ char *cgroup = NULL;
1644 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1648 return cg_path_get_owner_uid(cgroup, uid);
1651 int cg_path_get_slice(const char *p, char **slice) {
1652 const char *e = NULL;
1657 /* Finds the right-most slice unit from the beginning, but
1658 * stops before we come to the first non-slice unit. */
1663 p += strspn(p, "/");
1665 n = strcspn(p, "/");
1666 if (!valid_slice_name(p, n)) {
1671 s = strdup("-.slice");
1679 return cg_path_decode_unit(e, slice);
1687 int cg_pid_get_slice(pid_t pid, char **slice) {
1688 _cleanup_free_ char *cgroup = NULL;
1693 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1697 return cg_path_get_slice(cgroup, slice);
1700 int cg_path_get_user_slice(const char *p, char **slice) {
1705 t = skip_user_prefix(p);
1709 /* And now it looks pretty much the same as for a system
1710 * slice, so let's just use the same parser from here on. */
1711 return cg_path_get_slice(t, slice);
1714 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1715 _cleanup_free_ char *cgroup = NULL;
1720 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1724 return cg_path_get_user_slice(cgroup, slice);
1728 char *cg_escape(const char *p) {
1729 bool need_prefix = false;
1731 /* This implements very minimal escaping for names to be used
1732 * as file names in the cgroup tree: any name which might
1733 * conflict with a kernel name or is prefixed with '_' is
1734 * prefixed with a '_'. That way, when reading cgroup names it
1735 * is sufficient to remove a single prefixing underscore if
1738 /* The return value of this function (unlike cg_unescape())
1744 streq(p, "notify_on_release") ||
1745 streq(p, "release_agent") ||
1746 streq(p, "tasks") ||
1747 startswith(p, "cgroup."))
1752 dot = strrchr(p, '.');
1757 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1760 n = cgroup_controller_to_string(c);
1765 if (memcmp(p, n, l) != 0)
1775 return strappend("_", p);
1780 char *cg_unescape(const char *p) {
1783 /* The return value of this function (unlike cg_escape())
1784 * doesn't need free()! */
1792 #define CONTROLLER_VALID \
1796 bool cg_controller_is_valid(const char *p) {
1802 s = startswith(p, "name=");
1806 if (*p == 0 || *p == '_')
1809 for (t = p; *t; t++)
1810 if (!strchr(CONTROLLER_VALID, *t))
1813 if (t - p > FILENAME_MAX)
1819 #if 0 /// UNNEEDED by elogind
1820 int cg_slice_to_path(const char *unit, char **ret) {
1821 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1828 if (streq(unit, "-.slice")) {
1838 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1841 if (!endswith(unit, ".slice"))
1844 r = unit_name_to_prefix(unit, &p);
1848 dash = strchr(p, '-');
1850 /* Don't allow initial dashes */
1855 _cleanup_free_ char *escaped = NULL;
1856 char n[dash - p + sizeof(".slice")];
1858 /* Don't allow trailing or double dashes */
1859 if (dash[1] == 0 || dash[1] == '-')
1862 strcpy(stpncpy(n, p, dash - p), ".slice");
1863 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1866 escaped = cg_escape(n);
1870 if (!strextend(&s, escaped, "/", NULL))
1873 dash = strchr(dash+1, '-');
1876 e = cg_escape(unit);
1880 if (!strextend(&s, e, NULL))
1890 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1891 _cleanup_free_ char *p = NULL;
1894 r = cg_get_path(controller, path, attribute, &p);
1898 return write_string_file(p, value, 0);
1901 #if 0 /// UNNEEDED by elogind
1902 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1903 _cleanup_free_ char *p = NULL;
1906 r = cg_get_path(controller, path, attribute, &p);
1910 return read_one_line_file(p, ret);
1913 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1917 /* This one will create a cgroup in our private tree, but also
1918 * duplicate it in the trees specified in mask, and remove it
1921 /* First create the cgroup in our own hierarchy. */
1922 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1926 /* If we are in the unified hierarchy, we are done now */
1927 unified = cg_unified();
1933 /* Otherwise, do the same in the other hierarchies */
1934 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1935 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1938 n = cgroup_controller_to_string(c);
1941 (void) cg_create(n, path);
1942 else if (supported & bit)
1943 (void) cg_trim(n, path, true);
1949 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1953 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
1957 unified = cg_unified();
1963 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1964 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1965 const char *p = NULL;
1967 if (!(supported & bit))
1971 p = path_callback(bit, userdata);
1976 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
1982 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
1987 SET_FOREACH(pidp, pids, i) {
1988 pid_t pid = PTR_TO_PID(pidp);
1991 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
1992 if (q < 0 && r >= 0)
1999 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2003 if (!path_equal(from, to)) {
2004 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, false, true);
2009 unified = cg_unified();
2015 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2016 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2017 const char *p = NULL;
2019 if (!(supported & bit))
2023 p = to_callback(bit, userdata);
2028 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, false, false);
2034 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2038 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2042 unified = cg_unified();
2048 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2049 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2051 if (!(supported & bit))
2054 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2061 int cg_mask_supported(CGroupMask *ret) {
2062 CGroupMask mask = 0;
2065 /* Determines the mask of supported cgroup controllers. Only
2066 * includes controllers we can make sense of and that are
2067 * actually accessible. */
2069 unified = cg_unified();
2073 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2076 /* In the unified hierarchy we can read the supported
2077 * and accessible controllers from a the top-level
2078 * cgroup attribute */
2080 r = cg_get_root_path(&root);
2084 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2088 r = read_one_line_file(path, &controllers);
2094 _cleanup_free_ char *n = NULL;
2097 r = extract_first_word(&c, &n, NULL, 0);
2103 v = cgroup_controller_from_string(n);
2107 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2110 /* Currently, we only support the memory, io and pids
2111 * controller in the unified hierarchy, mask
2112 * everything else off. */
2113 mask &= CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2118 /* In the legacy hierarchy, we check whether which
2119 * hierarchies are mounted. */
2121 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2124 n = cgroup_controller_to_string(c);
2125 if (controller_is_accessible(n) >= 0)
2126 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2134 #if 0 /// UNNEEDED by elogind
2135 int cg_kernel_controllers(Set *controllers) {
2136 _cleanup_fclose_ FILE *f = NULL;
2140 assert(controllers);
2142 /* Determines the full list of kernel-known controllers. Might
2143 * include controllers we don't actually support, arbitrary
2144 * named hierarchies and controllers that aren't currently
2145 * accessible (because not mounted). */
2147 f = fopen("/proc/cgroups", "re");
2149 if (errno == ENOENT)
2154 /* Ignore the header line */
2155 (void) fgets(buf, sizeof(buf), f);
2162 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2167 if (ferror(f) && errno > 0)
2178 if (!cg_controller_is_valid(controller)) {
2183 r = set_consume(controllers, controller);
2192 static thread_local int unified_cache = -1;
2194 int cg_unified(void) {
2197 /* Checks if we support the unified hierarchy. Returns an
2198 * error when the cgroup hierarchies aren't mounted yet or we
2199 * have any other trouble determining if the unified hierarchy
2202 if (unified_cache >= 0)
2203 return unified_cache;
2205 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2208 #if 0 /// UNNEEDED by elogind
2209 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2210 unified_cache = true;
2211 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2213 /* elogind can not support the unified hierarchy as a controller,
2214 * so always assume a classical hierarchy.
2215 * If, ond only *if*, someone really wants to substitute systemd-login
2216 * in an environment managed by systemd with elogin, we might have to
2217 * add such a support. */
2218 if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2220 unified_cache = false;
2224 return unified_cache;
2227 #if 0 /// UNNEEDED by elogind
2228 void cg_unified_flush(void) {
2232 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2233 _cleanup_free_ char *fs = NULL;
2242 unified = cg_unified();
2245 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2248 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2252 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2253 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2256 if (!(supported & bit))
2259 n = cgroup_controller_to_string(c);
2261 char s[1 + strlen(n) + 1];
2263 s[0] = mask & bit ? '+' : '-';
2266 r = write_string_file(fs, s, 0);
2268 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2275 bool cg_is_unified_wanted(void) {
2276 static thread_local int wanted = -1;
2279 /* If the hierarchy is already mounted, then follow whatever
2280 * was chosen for it. */
2281 unified = cg_unified();
2285 /* Otherwise, let's see what the kernel command line has to
2286 * say. Since checking that is expensive, let's cache the
2291 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2293 return (wanted = true);
2295 _cleanup_free_ char *value = NULL;
2297 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2301 return (wanted = false);
2303 return (wanted = parse_boolean(value) > 0);
2307 bool cg_is_legacy_wanted(void) {
2308 return !cg_is_unified_wanted();
2311 bool cg_is_legacy_wanted(void) {
2316 #if 0 /// UNNEEDED by elogind
2317 int cg_weight_parse(const char *s, uint64_t *ret) {
2322 *ret = CGROUP_WEIGHT_INVALID;
2326 r = safe_atou64(s, &u);
2330 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2337 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2338 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2339 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2340 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2341 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2344 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2345 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2346 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2347 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2348 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2351 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2353 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2358 *ret = CGROUP_CPU_SHARES_INVALID;
2362 r = safe_atou64(s, &u);
2366 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2373 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2378 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2382 r = safe_atou64(s, &u);
2386 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2394 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2395 [CGROUP_CONTROLLER_CPU] = "cpu",
2396 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2397 [CGROUP_CONTROLLER_IO] = "io",
2398 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2399 [CGROUP_CONTROLLER_MEMORY] = "memory",
2400 [CGROUP_CONTROLLER_DEVICES] = "devices",
2401 [CGROUP_CONTROLLER_PIDS] = "pids",
2404 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);