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_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
105 _cleanup_free_ char *fs = NULL;
111 /* This is not recursive! */
113 r = cg_get_path(controller, path, NULL, &fs);
125 int cg_read_subgroup(DIR *d, char **fn) {
131 FOREACH_DIRENT_ALL(de, d, return -errno) {
134 if (de->d_type != DT_DIR)
137 if (streq(de->d_name, ".") ||
138 streq(de->d_name, ".."))
141 b = strdup(de->d_name);
152 int cg_rmdir(const char *controller, const char *path) {
153 _cleanup_free_ char *p = NULL;
156 r = cg_get_path(controller, path, NULL, &p);
161 if (r < 0 && errno != ENOENT)
167 int cg_kill(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, Set *s) {
168 _cleanup_set_free_ Set *allocated_set = NULL;
175 /* This goes through the tasks list and kills them all. This
176 * is repeated until no further processes are added to the
177 * tasks list, to properly handle forking processes */
180 s = allocated_set = set_new(NULL);
188 _cleanup_fclose_ FILE *f = NULL;
192 r = cg_enumerate_processes(controller, path, &f);
194 if (ret >= 0 && r != -ENOENT)
200 while ((r = cg_read_pid(f, &pid)) > 0) {
202 if (ignore_self && pid == my_pid)
205 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
208 /* If we haven't killed this process yet, kill
210 if (kill(pid, sig) < 0) {
211 if (ret >= 0 && errno != ESRCH)
214 if (sigcont && sig != SIGKILL)
215 (void) kill(pid, SIGCONT);
223 r = set_put(s, PID_TO_PTR(pid));
239 /* To avoid racing against processes which fork
240 * quicker than we can kill them we repeat this until
241 * no new pids need to be killed. */
248 int cg_kill_recursive(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, bool rem, Set *s) {
249 _cleanup_set_free_ Set *allocated_set = NULL;
250 _cleanup_closedir_ DIR *d = NULL;
258 s = allocated_set = set_new(NULL);
263 ret = cg_kill(controller, path, sig, sigcont, ignore_self, s);
265 r = cg_enumerate_subgroups(controller, path, &d);
267 if (ret >= 0 && r != -ENOENT)
273 while ((r = cg_read_subgroup(d, &fn)) > 0) {
274 _cleanup_free_ char *p = NULL;
276 p = strjoin(path, "/", fn, NULL);
281 r = cg_kill_recursive(controller, p, sig, sigcont, ignore_self, rem, s);
282 if (r != 0 && ret >= 0)
286 if (ret >= 0 && r < 0)
290 r = cg_rmdir(controller, path);
291 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
298 int cg_migrate(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self) {
300 _cleanup_set_free_ Set *s = NULL;
315 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
316 cfrom, pfrom, cto, pto,
317 ignore_self ? "ignoring self" : "watching self");
320 _cleanup_fclose_ FILE *f = NULL;
324 r = cg_enumerate_processes(cfrom, pfrom, &f);
326 if (ret >= 0 && r != -ENOENT)
332 while ((r = cg_read_pid(f, &pid)) > 0) {
334 /* This might do weird stuff if we aren't a
335 * single-threaded program. However, we
336 * luckily know we are not */
337 if (ignore_self && pid == my_pid)
340 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
343 /* Ignore kernel threads. Since they can only
344 * exist in the root cgroup, we only check for
347 (isempty(pfrom) || path_equal(pfrom, "/")) &&
348 is_kernel_thread(pid) > 0)
351 r = cg_attach(cto, pto, pid);
353 if (ret >= 0 && r != -ESRCH)
360 r = set_put(s, PID_TO_PTR(pid));
380 int cg_migrate_recursive(
388 _cleanup_closedir_ DIR *d = NULL;
397 ret = cg_migrate(cfrom, pfrom, cto, pto, ignore_self);
399 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
401 if (ret >= 0 && r != -ENOENT)
407 while ((r = cg_read_subgroup(d, &fn)) > 0) {
408 _cleanup_free_ char *p = NULL;
410 p = strjoin(pfrom, "/", fn, NULL);
415 r = cg_migrate_recursive(cfrom, p, cto, pto, ignore_self, rem);
416 if (r != 0 && ret >= 0)
420 if (r < 0 && ret >= 0)
424 r = cg_rmdir(cfrom, pfrom);
425 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
432 int cg_migrate_recursive_fallback(
447 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, ignore_self, rem);
449 char prefix[strlen(pto) + 1];
451 /* This didn't work? Then let's try all prefixes of the destination */
453 PATH_FOREACH_PREFIX(prefix, pto) {
456 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, ignore_self, rem);
465 static const char *controller_to_dirname(const char *controller) {
470 /* Converts a controller name to the directory name below
471 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
472 * just cuts off the name= prefixed used for named
473 * hierarchies, if it is specified. */
475 e = startswith(controller, "name=");
482 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
489 dn = controller_to_dirname(controller);
491 if (isempty(path) && isempty(suffix))
492 t = strappend("/sys/fs/cgroup/", dn);
493 else if (isempty(path))
494 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
495 else if (isempty(suffix))
496 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
498 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
506 static int join_path_unified(const char *path, const char *suffix, char **fs) {
511 if (isempty(path) && isempty(suffix))
512 t = strdup("/sys/fs/cgroup");
513 else if (isempty(path))
514 t = strappend("/sys/fs/cgroup/", suffix);
515 else if (isempty(suffix))
516 t = strappend("/sys/fs/cgroup/", path);
518 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
526 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
534 /* If no controller is specified, we return the path
535 * *below* the controllers, without any prefix. */
537 if (!path && !suffix)
545 t = strjoin(path, "/", suffix, NULL);
549 *fs = path_kill_slashes(t);
553 if (!cg_controller_is_valid(controller))
556 unified = cg_unified();
561 r = join_path_unified(path, suffix, fs);
563 r = join_path_legacy(controller, path, suffix, fs);
567 path_kill_slashes(*fs);
571 static int controller_is_accessible(const char *controller) {
576 /* Checks whether a specific controller is accessible,
577 * i.e. its hierarchy mounted. In the unified hierarchy all
578 * controllers are considered accessible, except for the named
581 if (!cg_controller_is_valid(controller))
584 unified = cg_unified();
588 /* We don't support named hierarchies if we are using
589 * the unified hierarchy. */
591 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
594 if (startswith(controller, "name="))
600 dn = controller_to_dirname(controller);
601 cc = strjoina("/sys/fs/cgroup/", dn);
603 if (laccess(cc, F_OK) < 0)
610 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
616 /* Check if the specified controller is actually accessible */
617 r = controller_is_accessible(controller);
621 return cg_get_path(controller, path, suffix, fs);
624 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
629 if (typeflag != FTW_DP)
632 if (ftwbuf->level < 1)
639 int cg_trim(const char *controller, const char *path, bool delete_root) {
640 _cleanup_free_ char *fs = NULL;
645 r = cg_get_path(controller, path, NULL, &fs);
650 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
660 if (rmdir(fs) < 0 && errno != ENOENT)
667 int cg_create(const char *controller, const char *path) {
668 _cleanup_free_ char *fs = NULL;
671 r = cg_get_path_and_check(controller, path, NULL, &fs);
675 r = mkdir_parents(fs, 0755);
679 if (mkdir(fs, 0755) < 0) {
690 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
695 r = cg_create(controller, path);
699 q = cg_attach(controller, path, pid);
703 /* This does not remove the cgroup on failure */
707 int cg_attach(const char *controller, const char *path, pid_t pid) {
708 _cleanup_free_ char *fs = NULL;
709 char c[DECIMAL_STR_MAX(pid_t) + 2];
715 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
722 xsprintf(c, PID_FMT "\n", pid);
724 return write_string_file(fs, c, 0);
727 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
734 r = cg_attach(controller, path, pid);
736 char prefix[strlen(path) + 1];
738 /* This didn't work? Then let's try all prefixes of
741 PATH_FOREACH_PREFIX(prefix, path) {
744 q = cg_attach(controller, prefix, pid);
753 #if 0 /// UNNEEDED by elogind
754 int cg_set_group_access(
755 const char *controller,
761 _cleanup_free_ char *fs = NULL;
764 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
767 if (mode != MODE_INVALID)
770 r = cg_get_path(controller, path, NULL, &fs);
774 return chmod_and_chown(fs, mode, uid, gid);
777 int cg_set_task_access(
778 const char *controller,
784 _cleanup_free_ char *fs = NULL, *procs = NULL;
789 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
792 if (mode != MODE_INVALID)
795 r = cg_get_path(controller, path, "cgroup.procs", &fs);
799 r = chmod_and_chown(fs, mode, uid, gid);
803 unified = cg_unified();
809 /* Compatibility, Always keep values for "tasks" in sync with
811 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
812 (void) chmod_and_chown(procs, mode, uid, gid);
818 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
819 _cleanup_fclose_ FILE *f = NULL;
828 unified = cg_unified();
833 if (!cg_controller_is_valid(controller))
836 controller = SYSTEMD_CGROUP_CONTROLLER;
838 cs = strlen(controller);
841 fs = procfs_file_alloca(pid, "cgroup");
842 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
843 pid, fs, controller);
846 return errno == ENOENT ? -ESRCH : -errno;
848 FOREACH_LINE(line, f, return -errno) {
854 e = startswith(line, "0:");
864 const char *word, *state;
867 l = strchr(line, ':');
877 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
878 if (k == cs && memcmp(word, controller, cs) == 0) {
888 log_debug_elogind("Found %s:%s", line, e+1);
900 int cg_install_release_agent(const char *controller, const char *agent) {
901 _cleanup_free_ char *fs = NULL, *contents = NULL;
907 unified = cg_unified();
910 if (unified) /* doesn't apply to unified hierarchy */
913 r = cg_get_path(controller, NULL, "release_agent", &fs);
917 r = read_one_line_file(fs, &contents);
921 sc = strstrip(contents);
923 r = write_string_file(fs, agent, 0);
926 } else if (!path_equal(sc, agent))
930 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
934 contents = mfree(contents);
935 r = read_one_line_file(fs, &contents);
939 sc = strstrip(contents);
940 if (streq(sc, "0")) {
941 r = write_string_file(fs, "1", 0);
954 int cg_uninstall_release_agent(const char *controller) {
955 _cleanup_free_ char *fs = NULL;
958 unified = cg_unified();
961 if (unified) /* Doesn't apply to unified hierarchy */
964 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
968 r = write_string_file(fs, "0", 0);
974 r = cg_get_path(controller, NULL, "release_agent", &fs);
978 r = write_string_file(fs, "", 0);
985 int cg_is_empty(const char *controller, const char *path) {
986 _cleanup_fclose_ FILE *f = NULL;
992 r = cg_enumerate_processes(controller, path, &f);
998 r = cg_read_pid(f, &pid);
1005 int cg_is_empty_recursive(const char *controller, const char *path) {
1010 /* The root cgroup is always populated */
1011 if (controller && (isempty(path) || path_equal(path, "/")))
1014 unified = cg_unified();
1019 _cleanup_free_ char *populated = NULL, *t = NULL;
1021 /* On the unified hierarchy we can check empty state
1022 * via the "cgroup.populated" attribute. */
1024 r = cg_get_path(controller, path, "cgroup.populated", &populated);
1028 r = read_one_line_file(populated, &t);
1034 return streq(t, "0");
1036 _cleanup_closedir_ DIR *d = NULL;
1039 r = cg_is_empty(controller, path);
1043 r = cg_enumerate_subgroups(controller, path, &d);
1049 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1050 _cleanup_free_ char *p = NULL;
1052 p = strjoin(path, "/", fn, NULL);
1057 r = cg_is_empty_recursive(controller, p);
1068 int cg_split_spec(const char *spec, char **controller, char **path) {
1069 char *t = NULL, *u = NULL;
1075 if (!path_is_safe(spec))
1083 *path = path_kill_slashes(t);
1092 e = strchr(spec, ':');
1094 if (!cg_controller_is_valid(spec))
1111 t = strndup(spec, e-spec);
1114 if (!cg_controller_is_valid(t)) {
1128 if (!path_is_safe(u) ||
1129 !path_is_absolute(u)) {
1135 path_kill_slashes(u);
1151 int cg_mangle_path(const char *path, char **result) {
1152 _cleanup_free_ char *c = NULL, *p = NULL;
1159 /* First, check if it already is a filesystem path */
1160 if (path_startswith(path, "/sys/fs/cgroup")) {
1166 *result = path_kill_slashes(t);
1170 /* Otherwise, treat it as cg spec */
1171 r = cg_split_spec(path, &c, &p);
1175 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1178 int cg_get_root_path(char **path) {
1179 #if 0 /// elogind does not support systemd scopes and slices
1185 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1189 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1191 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1193 e = endswith(p, "/system"); /* even more legacy */
1201 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1205 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1206 _cleanup_free_ char *rt = NULL;
1214 /* If the root was specified let's use that, otherwise
1215 * let's determine it from PID 1 */
1217 r = cg_get_root_path(&rt);
1222 log_debug_elogind("Determined root path: \"%s\"", root);
1225 p = path_startswith(cgroup, root);
1226 if (p && p[0] && (p > cgroup))
1234 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1235 _cleanup_free_ char *raw = NULL;
1242 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1246 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1247 raw, pid, root ? root : "NULL");
1248 r = cg_shift_path(raw, root, &c);
1264 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1269 #if 0 /// UNNEEDED by elogind
1270 int cg_path_decode_unit(const char *cgroup, char **unit){
1277 n = strcspn(cgroup, "/");
1281 c = strndupa(cgroup, n);
1284 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1295 static bool valid_slice_name(const char *p, size_t n) {
1300 if (n < strlen("x.slice"))
1303 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1309 c = cg_unescape(buf);
1311 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1317 static const char *skip_slices(const char *p) {
1320 /* Skips over all slice assignments */
1325 p += strspn(p, "/");
1327 n = strcspn(p, "/");
1328 if (!valid_slice_name(p, n))
1335 int cg_path_get_unit(const char *path, char **ret) {
1343 e = skip_slices(path);
1345 r = cg_path_decode_unit(e, &unit);
1349 /* We skipped over the slices, don't accept any now */
1350 if (endswith(unit, ".slice")) {
1359 int cg_pid_get_unit(pid_t pid, char **unit) {
1360 _cleanup_free_ char *cgroup = NULL;
1365 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1369 return cg_path_get_unit(cgroup, unit);
1373 * Skip session-*.scope, but require it to be there.
1375 static const char *skip_session(const char *p) {
1381 p += strspn(p, "/");
1383 n = strcspn(p, "/");
1384 if (n < strlen("session-x.scope"))
1387 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1388 char buf[n - 8 - 6 + 1];
1390 memcpy(buf, p + 8, n - 8 - 6);
1393 /* Note that session scopes never need unescaping,
1394 * since they cannot conflict with the kernel's own
1395 * names, hence we don't need to call cg_unescape()
1398 if (!session_id_valid(buf))
1402 p += strspn(p, "/");
1410 * Skip user@*.service, but require it to be there.
1412 static const char *skip_user_manager(const char *p) {
1418 p += strspn(p, "/");
1420 n = strcspn(p, "/");
1421 if (n < strlen("user@x.service"))
1424 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1425 char buf[n - 5 - 8 + 1];
1427 memcpy(buf, p + 5, n - 5 - 8);
1430 /* Note that user manager services never need unescaping,
1431 * since they cannot conflict with the kernel's own
1432 * names, hence we don't need to call cg_unescape()
1435 if (parse_uid(buf, NULL) < 0)
1439 p += strspn(p, "/");
1447 static const char *skip_user_prefix(const char *path) {
1452 /* Skip slices, if there are any */
1453 e = skip_slices(path);
1455 /* Skip the user manager, if it's in the path now... */
1456 t = skip_user_manager(e);
1460 /* Alternatively skip the user session if it is in the path... */
1461 return skip_session(e);
1464 int cg_path_get_user_unit(const char *path, char **ret) {
1470 t = skip_user_prefix(path);
1474 /* And from here on it looks pretty much the same as for a
1475 * system unit, hence let's use the same parser from here
1477 return cg_path_get_unit(t, ret);
1480 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1481 _cleanup_free_ char *cgroup = NULL;
1486 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1490 return cg_path_get_user_unit(cgroup, unit);
1493 int cg_path_get_machine_name(const char *path, char **machine) {
1494 _cleanup_free_ char *u = NULL;
1498 r = cg_path_get_unit(path, &u);
1502 sl = strjoina("/run/systemd/machines/unit:", u);
1503 return readlink_malloc(sl, machine);
1506 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1507 _cleanup_free_ char *cgroup = NULL;
1512 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1516 return cg_path_get_machine_name(cgroup, machine);
1520 int cg_path_get_session(const char *path, char **session) {
1521 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1522 wrinkle is that SESSION might be escaped. */
1524 _cleanup_free_ char *unit = NULL;
1530 r = cg_path_get_unit(path, &unit);
1534 start = startswith(unit, "session-");
1537 end = endswith(start, ".scope");
1542 if (!session_id_valid(start))
1545 const char *e, *n, *start;
1548 log_debug_elogind("path is \"%s\"", path);
1549 assert(path[0] == '/');
1552 n = strchrnul(e, '/');
1556 start = strndupa(e, n - e);
1557 start = cg_unescape(start);
1566 log_debug_elogind("found session: \"%s\"", start);
1577 int cg_pid_get_session(pid_t pid, char **session) {
1578 _cleanup_free_ char *cgroup = NULL;
1581 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1585 return cg_path_get_session(cgroup, session);
1588 #if 0 /// UNNEEDED by elogind
1589 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1590 _cleanup_free_ char *slice = NULL;
1596 r = cg_path_get_slice(path, &slice);
1600 start = startswith(slice, "user-");
1603 end = endswith(start, ".slice");
1608 if (parse_uid(start, uid) < 0)
1614 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1615 _cleanup_free_ char *cgroup = NULL;
1618 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1622 return cg_path_get_owner_uid(cgroup, uid);
1625 int cg_path_get_slice(const char *p, char **slice) {
1626 const char *e = NULL;
1631 /* Finds the right-most slice unit from the beginning, but
1632 * stops before we come to the first non-slice unit. */
1637 p += strspn(p, "/");
1639 n = strcspn(p, "/");
1640 if (!valid_slice_name(p, n)) {
1645 s = strdup("-.slice");
1653 return cg_path_decode_unit(e, slice);
1661 int cg_pid_get_slice(pid_t pid, char **slice) {
1662 _cleanup_free_ char *cgroup = NULL;
1667 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1671 return cg_path_get_slice(cgroup, slice);
1674 int cg_path_get_user_slice(const char *p, char **slice) {
1679 t = skip_user_prefix(p);
1683 /* And now it looks pretty much the same as for a system
1684 * slice, so let's just use the same parser from here on. */
1685 return cg_path_get_slice(t, slice);
1688 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1689 _cleanup_free_ char *cgroup = NULL;
1694 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1698 return cg_path_get_user_slice(cgroup, slice);
1702 char *cg_escape(const char *p) {
1703 bool need_prefix = false;
1705 /* This implements very minimal escaping for names to be used
1706 * as file names in the cgroup tree: any name which might
1707 * conflict with a kernel name or is prefixed with '_' is
1708 * prefixed with a '_'. That way, when reading cgroup names it
1709 * is sufficient to remove a single prefixing underscore if
1712 /* The return value of this function (unlike cg_unescape())
1718 streq(p, "notify_on_release") ||
1719 streq(p, "release_agent") ||
1720 streq(p, "tasks") ||
1721 startswith(p, "cgroup."))
1726 dot = strrchr(p, '.');
1731 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1734 n = cgroup_controller_to_string(c);
1739 if (memcmp(p, n, l) != 0)
1749 return strappend("_", p);
1754 char *cg_unescape(const char *p) {
1757 /* The return value of this function (unlike cg_escape())
1758 * doesn't need free()! */
1766 #define CONTROLLER_VALID \
1770 bool cg_controller_is_valid(const char *p) {
1776 s = startswith(p, "name=");
1780 if (*p == 0 || *p == '_')
1783 for (t = p; *t; t++)
1784 if (!strchr(CONTROLLER_VALID, *t))
1787 if (t - p > FILENAME_MAX)
1793 #if 0 /// UNNEEDED by elogind
1794 int cg_slice_to_path(const char *unit, char **ret) {
1795 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1802 if (streq(unit, "-.slice")) {
1812 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1815 if (!endswith(unit, ".slice"))
1818 r = unit_name_to_prefix(unit, &p);
1822 dash = strchr(p, '-');
1824 /* Don't allow initial dashes */
1829 _cleanup_free_ char *escaped = NULL;
1830 char n[dash - p + sizeof(".slice")];
1832 /* Don't allow trailing or double dashes */
1833 if (dash[1] == 0 || dash[1] == '-')
1836 strcpy(stpncpy(n, p, dash - p), ".slice");
1837 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1840 escaped = cg_escape(n);
1844 if (!strextend(&s, escaped, "/", NULL))
1847 dash = strchr(dash+1, '-');
1850 e = cg_escape(unit);
1854 if (!strextend(&s, e, NULL))
1864 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1865 _cleanup_free_ char *p = NULL;
1868 r = cg_get_path(controller, path, attribute, &p);
1872 return write_string_file(p, value, 0);
1875 #if 0 /// UNNEEDED by elogind
1876 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1877 _cleanup_free_ char *p = NULL;
1880 r = cg_get_path(controller, path, attribute, &p);
1884 return read_one_line_file(p, ret);
1887 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1891 /* This one will create a cgroup in our private tree, but also
1892 * duplicate it in the trees specified in mask, and remove it
1895 /* First create the cgroup in our own hierarchy. */
1896 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1900 /* If we are in the unified hierarchy, we are done now */
1901 unified = cg_unified();
1907 /* Otherwise, do the same in the other hierarchies */
1908 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1909 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1912 n = cgroup_controller_to_string(c);
1915 (void) cg_create(n, path);
1916 else if (supported & bit)
1917 (void) cg_trim(n, path, true);
1923 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1927 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
1931 unified = cg_unified();
1937 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1938 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1939 const char *p = NULL;
1941 if (!(supported & bit))
1945 p = path_callback(bit, userdata);
1950 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
1956 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
1961 SET_FOREACH(pidp, pids, i) {
1962 pid_t pid = PTR_TO_PID(pidp);
1965 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
1966 if (q < 0 && r >= 0)
1973 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
1977 if (!path_equal(from, to)) {
1978 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, false, true);
1983 unified = cg_unified();
1989 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1990 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1991 const char *p = NULL;
1993 if (!(supported & bit))
1997 p = to_callback(bit, userdata);
2002 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, false, false);
2008 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2012 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2016 unified = cg_unified();
2022 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2023 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2025 if (!(supported & bit))
2028 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2035 int cg_mask_supported(CGroupMask *ret) {
2036 CGroupMask mask = 0;
2039 /* Determines the mask of supported cgroup controllers. Only
2040 * includes controllers we can make sense of and that are
2041 * actually accessible. */
2043 unified = cg_unified();
2047 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2050 /* In the unified hierarchy we can read the supported
2051 * and accessible controllers from a the top-level
2052 * cgroup attribute */
2054 r = cg_get_root_path(&root);
2058 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2062 r = read_one_line_file(path, &controllers);
2068 _cleanup_free_ char *n = NULL;
2071 r = extract_first_word(&c, &n, NULL, 0);
2077 v = cgroup_controller_from_string(n);
2081 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2084 /* Currently, we only support the memory and pids
2085 * controller in the unified hierarchy, mask
2086 * everything else off. */
2087 mask &= CGROUP_MASK_MEMORY | CGROUP_MASK_PIDS;
2092 /* In the legacy hierarchy, we check whether which
2093 * hierarchies are mounted. */
2095 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2098 n = cgroup_controller_to_string(c);
2099 if (controller_is_accessible(n) >= 0)
2100 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2108 #if 0 /// UNNEEDED by elogind
2109 int cg_kernel_controllers(Set *controllers) {
2110 _cleanup_fclose_ FILE *f = NULL;
2114 assert(controllers);
2116 /* Determines the full list of kernel-known controllers. Might
2117 * include controllers we don't actually support, arbitrary
2118 * named hierarchies and controllers that aren't currently
2119 * accessible (because not mounted). */
2121 f = fopen("/proc/cgroups", "re");
2123 if (errno == ENOENT)
2128 /* Ignore the header line */
2129 (void) fgets(buf, sizeof(buf), f);
2136 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2141 if (ferror(f) && errno > 0)
2152 if (!cg_controller_is_valid(controller)) {
2157 r = set_consume(controllers, controller);
2166 static thread_local int unified_cache = -1;
2168 int cg_unified(void) {
2171 /* Checks if we support the unified hierarchy. Returns an
2172 * error when the cgroup hierarchies aren't mounted yet or we
2173 * have any other trouble determining if the unified hierarchy
2176 if (unified_cache >= 0)
2177 return unified_cache;
2179 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2182 /// elogind can not support the unified hierarchy as a controller,
2183 /// so always assume a classical hierarchy.
2184 /// If, ond only *if*, someone really wants to substitute systemd-login
2185 /// in an environment managed by systemd with elogin, we might have to
2186 /// add such a support.
2188 if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC))
2189 unified_cache = true;
2190 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2192 if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2194 unified_cache = false;
2198 return unified_cache;
2201 #if 0 /// UNNEEDED by elogind
2202 void cg_unified_flush(void) {
2206 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2207 _cleanup_free_ char *fs = NULL;
2216 unified = cg_unified();
2219 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2222 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2226 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2227 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2230 if (!(supported & bit))
2233 n = cgroup_controller_to_string(c);
2235 char s[1 + strlen(n) + 1];
2237 s[0] = mask & bit ? '+' : '-';
2240 r = write_string_file(fs, s, 0);
2242 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2249 bool cg_is_unified_wanted(void) {
2250 static thread_local int wanted = -1;
2253 /* If the hierarchy is already mounted, then follow whatever
2254 * was chosen for it. */
2255 unified = cg_unified();
2259 /* Otherwise, let's see what the kernel command line has to
2260 * say. Since checking that is expensive, let's cache the
2265 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2267 return (wanted = true);
2269 _cleanup_free_ char *value = NULL;
2271 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2275 return (wanted = false);
2277 return (wanted = parse_boolean(value) > 0);
2281 bool cg_is_legacy_wanted(void) {
2282 return !cg_is_unified_wanted();
2285 bool cg_is_legacy_wanted(void) {
2290 #if 0 /// UNNEEDED by elogind
2291 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2296 *ret = CGROUP_CPU_SHARES_INVALID;
2300 r = safe_atou64(s, &u);
2304 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2311 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2316 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2320 r = safe_atou64(s, &u);
2324 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2332 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2333 [CGROUP_CONTROLLER_CPU] = "cpu",
2334 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2335 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2336 [CGROUP_CONTROLLER_MEMORY] = "memory",
2337 [CGROUP_CONTROLLER_DEVICES] = "devices",
2338 [CGROUP_CONTROLLER_PIDS] = "pids",
2341 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);