1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 #include <sys/types.h>
35 #include "formats-util.h"
36 #include "process-util.h"
37 #include "path-util.h"
38 // #include "unit-name.h"
40 // #include "special.h"
42 #include "login-util.h"
43 #include "cgroup-util.h"
45 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
46 _cleanup_free_ char *fs = NULL;
52 r = cg_get_path(controller, path, "cgroup.procs", &fs);
64 int cg_read_pid(FILE *f, pid_t *_pid) {
67 /* Note that the cgroup.procs might contain duplicates! See
68 * cgroups.txt for details. */
74 if (fscanf(f, "%lu", &ul) != 1) {
79 return errno ? -errno : -EIO;
89 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
90 _cleanup_free_ char *fs = NULL;
96 /* This is not recursive! */
98 r = cg_get_path(controller, path, NULL, &fs);
110 int cg_read_subgroup(DIR *d, char **fn) {
116 FOREACH_DIRENT_ALL(de, d, return -errno) {
119 if (de->d_type != DT_DIR)
122 if (streq(de->d_name, ".") ||
123 streq(de->d_name, ".."))
126 b = strdup(de->d_name);
137 int cg_rmdir(const char *controller, const char *path) {
138 _cleanup_free_ char *p = NULL;
141 r = cg_get_path(controller, path, NULL, &p);
146 if (r < 0 && errno != ENOENT)
152 int cg_kill(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, Set *s) {
153 _cleanup_set_free_ Set *allocated_set = NULL;
160 /* This goes through the tasks list and kills them all. This
161 * is repeated until no further processes are added to the
162 * tasks list, to properly handle forking processes */
165 s = allocated_set = set_new(NULL);
173 _cleanup_fclose_ FILE *f = NULL;
177 r = cg_enumerate_processes(controller, path, &f);
179 if (ret >= 0 && r != -ENOENT)
185 while ((r = cg_read_pid(f, &pid)) > 0) {
187 if (ignore_self && pid == my_pid)
190 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
193 /* If we haven't killed this process yet, kill
195 if (kill(pid, sig) < 0) {
196 if (ret >= 0 && errno != ESRCH)
199 if (sigcont && sig != SIGKILL)
200 (void) kill(pid, SIGCONT);
208 r = set_put(s, PID_TO_PTR(pid));
224 /* To avoid racing against processes which fork
225 * quicker than we can kill them we repeat this until
226 * no new pids need to be killed. */
233 int cg_kill_recursive(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, bool rem, Set *s) {
234 _cleanup_set_free_ Set *allocated_set = NULL;
235 _cleanup_closedir_ DIR *d = NULL;
243 s = allocated_set = set_new(NULL);
248 ret = cg_kill(controller, path, sig, sigcont, ignore_self, s);
250 r = cg_enumerate_subgroups(controller, path, &d);
252 if (ret >= 0 && r != -ENOENT)
258 while ((r = cg_read_subgroup(d, &fn)) > 0) {
259 _cleanup_free_ char *p = NULL;
261 p = strjoin(path, "/", fn, NULL);
266 r = cg_kill_recursive(controller, p, sig, sigcont, ignore_self, rem, s);
267 if (r != 0 && ret >= 0)
271 if (ret >= 0 && r < 0)
275 r = cg_rmdir(controller, path);
276 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
283 int cg_migrate(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self) {
285 _cleanup_set_free_ Set *s = NULL;
300 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
301 cfrom, pfrom, cto, pto,
302 ignore_self ? "ignoring self" : "watching self");
305 _cleanup_fclose_ FILE *f = NULL;
309 r = cg_enumerate_processes(cfrom, pfrom, &f);
311 if (ret >= 0 && r != -ENOENT)
317 while ((r = cg_read_pid(f, &pid)) > 0) {
319 /* This might do weird stuff if we aren't a
320 * single-threaded program. However, we
321 * luckily know we are not */
322 if (ignore_self && pid == my_pid)
325 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
328 /* Ignore kernel threads. Since they can only
329 * exist in the root cgroup, we only check for
332 (isempty(pfrom) || path_equal(pfrom, "/")) &&
333 is_kernel_thread(pid) > 0)
336 r = cg_attach(cto, pto, pid);
338 if (ret >= 0 && r != -ESRCH)
345 r = set_put(s, PID_TO_PTR(pid));
365 int cg_migrate_recursive(
373 _cleanup_closedir_ DIR *d = NULL;
382 ret = cg_migrate(cfrom, pfrom, cto, pto, ignore_self);
384 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
386 if (ret >= 0 && r != -ENOENT)
392 while ((r = cg_read_subgroup(d, &fn)) > 0) {
393 _cleanup_free_ char *p = NULL;
395 p = strjoin(pfrom, "/", fn, NULL);
400 r = cg_migrate_recursive(cfrom, p, cto, pto, ignore_self, rem);
401 if (r != 0 && ret >= 0)
405 if (r < 0 && ret >= 0)
409 r = cg_rmdir(cfrom, pfrom);
410 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
417 int cg_migrate_recursive_fallback(
432 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, ignore_self, rem);
434 char prefix[strlen(pto) + 1];
436 /* This didn't work? Then let's try all prefixes of the destination */
438 PATH_FOREACH_PREFIX(prefix, pto) {
441 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, ignore_self, rem);
450 static const char *controller_to_dirname(const char *controller) {
455 /* Converts a controller name to the directory name below
456 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
457 * just cuts off the name= prefixed used for named
458 * hierarchies, if it is specified. */
460 e = startswith(controller, "name=");
467 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
474 dn = controller_to_dirname(controller);
476 if (isempty(path) && isempty(suffix))
477 t = strappend("/sys/fs/cgroup/", dn);
478 else if (isempty(path))
479 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
480 else if (isempty(suffix))
481 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
483 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
491 static int join_path_unified(const char *path, const char *suffix, char **fs) {
496 if (isempty(path) && isempty(suffix))
497 t = strdup("/sys/fs/cgroup");
498 else if (isempty(path))
499 t = strappend("/sys/fs/cgroup/", suffix);
500 else if (isempty(suffix))
501 t = strappend("/sys/fs/cgroup/", path);
503 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
511 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
519 /* If no controller is specified, we return the path
520 * *below* the controllers, without any prefix. */
522 if (!path && !suffix)
530 t = strjoin(path, "/", suffix, NULL);
534 *fs = path_kill_slashes(t);
538 if (!cg_controller_is_valid(controller))
541 unified = cg_unified();
546 r = join_path_unified(path, suffix, fs);
548 r = join_path_legacy(controller, path, suffix, fs);
552 path_kill_slashes(*fs);
556 static int controller_is_accessible(const char *controller) {
561 /* Checks whether a specific controller is accessible,
562 * i.e. its hierarchy mounted. In the unified hierarchy all
563 * controllers are considered accessible, except for the named
566 if (!cg_controller_is_valid(controller))
569 unified = cg_unified();
573 /* We don't support named hierarchies if we are using
574 * the unified hierarchy. */
576 if (streq(controller, ELOGIND_CGROUP_CONTROLLER))
579 if (startswith(controller, "name="))
585 dn = controller_to_dirname(controller);
586 cc = strjoina("/sys/fs/cgroup/", dn);
588 if (laccess(cc, F_OK) < 0)
595 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
601 /* Check if the specified controller is actually accessible */
602 r = controller_is_accessible(controller);
606 return cg_get_path(controller, path, suffix, fs);
609 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
614 if (typeflag != FTW_DP)
617 if (ftwbuf->level < 1)
624 int cg_trim(const char *controller, const char *path, bool delete_root) {
625 _cleanup_free_ char *fs = NULL;
630 r = cg_get_path(controller, path, NULL, &fs);
635 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
645 if (rmdir(fs) < 0 && errno != ENOENT)
652 int cg_create(const char *controller, const char *path) {
653 _cleanup_free_ char *fs = NULL;
656 r = cg_get_path_and_check(controller, path, NULL, &fs);
660 r = mkdir_parents(fs, 0755);
664 if (mkdir(fs, 0755) < 0) {
675 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
680 r = cg_create(controller, path);
684 q = cg_attach(controller, path, pid);
688 /* This does not remove the cgroup on failure */
692 int cg_attach(const char *controller, const char *path, pid_t pid) {
693 _cleanup_free_ char *fs = NULL;
694 char c[DECIMAL_STR_MAX(pid_t) + 2];
700 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
707 snprintf(c, sizeof(c), PID_FMT"\n", pid);
709 return write_string_file_no_create(fs, c);
712 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
719 r = cg_attach(controller, path, pid);
721 char prefix[strlen(path) + 1];
723 /* This didn't work? Then let's try all prefixes of
726 PATH_FOREACH_PREFIX(prefix, path) {
729 q = cg_attach(controller, prefix, pid);
738 /// UNNEEDED by elogind
740 int cg_set_group_access(
741 const char *controller,
747 _cleanup_free_ char *fs = NULL;
750 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
753 if (mode != MODE_INVALID)
756 r = cg_get_path(controller, path, NULL, &fs);
760 return chmod_and_chown(fs, mode, uid, gid);
763 int cg_set_task_access(
764 const char *controller,
770 _cleanup_free_ char *fs = NULL, *procs = NULL;
775 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
778 if (mode != MODE_INVALID)
781 r = cg_get_path(controller, path, "cgroup.procs", &fs);
785 r = chmod_and_chown(fs, mode, uid, gid);
789 unified = cg_unified();
795 /* Compatibility, Always keep values for "tasks" in sync with
797 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
798 (void) chmod_and_chown(procs, mode, uid, gid);
804 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
805 _cleanup_fclose_ FILE *f = NULL;
814 unified = cg_unified();
819 if (!cg_controller_is_valid(controller))
822 controller = ELOGIND_CGROUP_CONTROLLER;
824 cs = strlen(controller);
827 fs = procfs_file_alloca(pid, "cgroup");
830 return errno == ENOENT ? -ESRCH : -errno;
832 FOREACH_LINE(line, f, return -errno) {
838 e = startswith(line, "0:");
848 const char *word, *state;
851 l = strchr(line, ':');
861 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
862 if (k == cs && memcmp(word, controller, cs) == 0) {
883 int cg_install_release_agent(const char *controller, const char *agent) {
884 _cleanup_free_ char *fs = NULL, *contents = NULL;
890 unified = cg_unified();
893 if (unified) /* doesn't apply to unified hierarchy */
896 r = cg_get_path(controller, NULL, "release_agent", &fs);
900 r = read_one_line_file(fs, &contents);
904 sc = strstrip(contents);
906 r = write_string_file_no_create(fs, agent);
909 } else if (!path_equal(sc, agent))
913 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
917 contents = mfree(contents);
918 r = read_one_line_file(fs, &contents);
922 sc = strstrip(contents);
923 if (streq(sc, "0")) {
924 r = write_string_file_no_create(fs, "1");
937 int cg_uninstall_release_agent(const char *controller) {
938 _cleanup_free_ char *fs = NULL;
941 unified = cg_unified();
944 if (unified) /* Doesn't apply to unified hierarchy */
947 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
951 r = write_string_file_no_create(fs, "0");
957 r = cg_get_path(controller, NULL, "release_agent", &fs);
961 r = write_string_file_no_create(fs, "");
968 int cg_is_empty(const char *controller, const char *path) {
969 _cleanup_fclose_ FILE *f = NULL;
975 r = cg_enumerate_processes(controller, path, &f);
981 r = cg_read_pid(f, &pid);
988 int cg_is_empty_recursive(const char *controller, const char *path) {
993 /* The root cgroup is always populated */
994 if (controller && (isempty(path) || path_equal(path, "/")))
997 unified = cg_unified();
1002 _cleanup_free_ char *populated = NULL, *t = NULL;
1004 /* On the unified hierarchy we can check empty state
1005 * via the "cgroup.populated" attribute. */
1007 r = cg_get_path(controller, path, "cgroup.populated", &populated);
1011 r = read_one_line_file(populated, &t);
1017 return streq(t, "0");
1019 _cleanup_closedir_ DIR *d = NULL;
1022 r = cg_is_empty(controller, path);
1026 r = cg_enumerate_subgroups(controller, path, &d);
1032 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1033 _cleanup_free_ char *p = NULL;
1035 p = strjoin(path, "/", fn, NULL);
1040 r = cg_is_empty_recursive(controller, p);
1051 int cg_split_spec(const char *spec, char **controller, char **path) {
1052 char *t = NULL, *u = NULL;
1058 if (!path_is_safe(spec))
1066 *path = path_kill_slashes(t);
1075 e = strchr(spec, ':');
1077 if (!cg_controller_is_valid(spec))
1094 t = strndup(spec, e-spec);
1097 if (!cg_controller_is_valid(t)) {
1111 if (!path_is_safe(u) ||
1112 !path_is_absolute(u)) {
1118 path_kill_slashes(u);
1134 int cg_mangle_path(const char *path, char **result) {
1135 _cleanup_free_ char *c = NULL, *p = NULL;
1142 /* First, check if it already is a filesystem path */
1143 if (path_startswith(path, "/sys/fs/cgroup")) {
1149 *result = path_kill_slashes(t);
1153 /* Otherwise, treat it as cg spec */
1154 r = cg_split_spec(path, &c, &p);
1158 return cg_get_path(c ? c : ELOGIND_CGROUP_CONTROLLER, p ? p : "/", NULL, result);
1161 int cg_get_root_path(char **path) {
1162 /// elogind does not support systemd scopes and slices
1169 r = cg_pid_get_path(ELOGIND_CGROUP_CONTROLLER, 1, &p);
1173 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1175 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1177 e = endswith(p, "/system"); /* even more legacy */
1185 return cg_pid_get_path(ELOGIND_CGROUP_CONTROLLER, 1, path);
1189 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1190 _cleanup_free_ char *rt = NULL;
1198 /* If the root was specified let's use that, otherwise
1199 * let's determine it from PID 1 */
1201 r = cg_get_root_path(&rt);
1208 p = path_startswith(cgroup, root);
1209 if (p && p > cgroup)
1217 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1218 _cleanup_free_ char *raw = NULL;
1225 r = cg_pid_get_path(ELOGIND_CGROUP_CONTROLLER, pid, &raw);
1229 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1230 raw, pid, root ? root : "NULL");
1231 r = cg_shift_path(raw, root, &c);
1247 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1252 /// UNNEEDED by elogind
1254 int cg_path_decode_unit(const char *cgroup, char **unit){
1261 n = strcspn(cgroup, "/");
1265 c = strndupa(cgroup, n);
1268 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1279 static bool valid_slice_name(const char *p, size_t n) {
1284 if (n < strlen("x.slice"))
1287 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1293 c = cg_unescape(buf);
1295 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1301 static const char *skip_slices(const char *p) {
1304 /* Skips over all slice assignments */
1309 p += strspn(p, "/");
1311 n = strcspn(p, "/");
1312 if (!valid_slice_name(p, n))
1319 int cg_path_get_unit(const char *path, char **ret) {
1327 e = skip_slices(path);
1329 r = cg_path_decode_unit(e, &unit);
1333 /* We skipped over the slices, don't accept any now */
1334 if (endswith(unit, ".slice")) {
1343 int cg_pid_get_unit(pid_t pid, char **unit) {
1344 _cleanup_free_ char *cgroup = NULL;
1349 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1353 return cg_path_get_unit(cgroup, unit);
1357 * Skip session-*.scope, but require it to be there.
1359 static const char *skip_session(const char *p) {
1365 p += strspn(p, "/");
1367 n = strcspn(p, "/");
1368 if (n < strlen("session-x.scope"))
1371 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1372 char buf[n - 8 - 6 + 1];
1374 memcpy(buf, p + 8, n - 8 - 6);
1377 /* Note that session scopes never need unescaping,
1378 * since they cannot conflict with the kernel's own
1379 * names, hence we don't need to call cg_unescape()
1382 if (!session_id_valid(buf))
1386 p += strspn(p, "/");
1394 * Skip user@*.service, but require it to be there.
1396 static const char *skip_user_manager(const char *p) {
1402 p += strspn(p, "/");
1404 n = strcspn(p, "/");
1405 if (n < strlen("user@x.service"))
1408 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1409 char buf[n - 5 - 8 + 1];
1411 memcpy(buf, p + 5, n - 5 - 8);
1414 /* Note that user manager services never need unescaping,
1415 * since they cannot conflict with the kernel's own
1416 * names, hence we don't need to call cg_unescape()
1419 if (parse_uid(buf, NULL) < 0)
1423 p += strspn(p, "/");
1431 static const char *skip_user_prefix(const char *path) {
1436 /* Skip slices, if there are any */
1437 e = skip_slices(path);
1439 /* Skip the user manager, if it's in the path now... */
1440 t = skip_user_manager(e);
1444 /* Alternatively skip the user session if it is in the path... */
1445 return skip_session(e);
1448 int cg_path_get_user_unit(const char *path, char **ret) {
1454 t = skip_user_prefix(path);
1458 /* And from here on it looks pretty much the same as for a
1459 * system unit, hence let's use the same parser from here
1461 return cg_path_get_unit(t, ret);
1464 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1465 _cleanup_free_ char *cgroup = NULL;
1470 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1474 return cg_path_get_user_unit(cgroup, unit);
1477 int cg_path_get_machine_name(const char *path, char **machine) {
1478 _cleanup_free_ char *u = NULL;
1482 r = cg_path_get_unit(path, &u);
1486 sl = strjoina("/run/systemd/machines/unit:", u);
1487 return readlink_malloc(sl, machine);
1490 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1491 _cleanup_free_ char *cgroup = NULL;
1496 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1500 return cg_path_get_machine_name(cgroup, machine);
1504 int cg_path_get_session(const char *path, char **session) {
1505 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1506 wrinkle is that SESSION might be escaped. */
1508 _cleanup_free_ char *unit = NULL;
1514 r = cg_path_get_unit(path, &unit);
1518 start = startswith(unit, "session-");
1521 end = endswith(start, ".scope");
1526 if (!session_id_valid(start))
1529 const char *e, *n, *start;
1532 log_debug_elogind("path is \"%s\"", path);
1533 assert(path[0] == '/');
1536 n = strchrnul(e, '/');
1540 start = strndupa(e, n - e);
1541 start = cg_unescape(start);
1550 log_debug_elogind("found session: \"%s\"", start);
1561 int cg_pid_get_session(pid_t pid, char **session) {
1562 _cleanup_free_ char *cgroup = NULL;
1565 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1569 return cg_path_get_session(cgroup, session);
1572 /// UNNEEDED by elogind
1574 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1575 _cleanup_free_ char *slice = NULL;
1581 r = cg_path_get_slice(path, &slice);
1585 start = startswith(slice, "user-");
1588 end = endswith(start, ".slice");
1593 if (parse_uid(start, uid) < 0)
1599 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1600 _cleanup_free_ char *cgroup = NULL;
1603 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1607 return cg_path_get_owner_uid(cgroup, uid);
1610 int cg_path_get_slice(const char *p, char **slice) {
1611 const char *e = NULL;
1616 /* Finds the right-most slice unit from the beginning, but
1617 * stops before we come to the first non-slice unit. */
1622 p += strspn(p, "/");
1624 n = strcspn(p, "/");
1625 if (!valid_slice_name(p, n)) {
1630 s = strdup("-.slice");
1638 return cg_path_decode_unit(e, slice);
1646 int cg_pid_get_slice(pid_t pid, char **slice) {
1647 _cleanup_free_ char *cgroup = NULL;
1652 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1656 return cg_path_get_slice(cgroup, slice);
1659 int cg_path_get_user_slice(const char *p, char **slice) {
1664 t = skip_user_prefix(p);
1668 /* And now it looks pretty much the same as for a system
1669 * slice, so let's just use the same parser from here on. */
1670 return cg_path_get_slice(t, slice);
1673 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1674 _cleanup_free_ char *cgroup = NULL;
1679 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1683 return cg_path_get_user_slice(cgroup, slice);
1687 char *cg_escape(const char *p) {
1688 bool need_prefix = false;
1690 /* This implements very minimal escaping for names to be used
1691 * as file names in the cgroup tree: any name which might
1692 * conflict with a kernel name or is prefixed with '_' is
1693 * prefixed with a '_'. That way, when reading cgroup names it
1694 * is sufficient to remove a single prefixing underscore if
1697 /* The return value of this function (unlike cg_unescape())
1703 streq(p, "notify_on_release") ||
1704 streq(p, "release_agent") ||
1705 streq(p, "tasks") ||
1706 startswith(p, "cgroup."))
1711 dot = strrchr(p, '.');
1716 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1719 n = cgroup_controller_to_string(c);
1724 if (memcmp(p, n, l) != 0)
1734 return strappend("_", p);
1739 char *cg_unescape(const char *p) {
1742 /* The return value of this function (unlike cg_escape())
1743 * doesn't need free()! */
1751 #define CONTROLLER_VALID \
1755 bool cg_controller_is_valid(const char *p) {
1761 s = startswith(p, "name=");
1765 if (*p == 0 || *p == '_')
1768 for (t = p; *t; t++)
1769 if (!strchr(CONTROLLER_VALID, *t))
1772 if (t - p > FILENAME_MAX)
1778 /// UNNEEDED by elogind
1780 int cg_slice_to_path(const char *unit, char **ret) {
1781 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1788 if (streq(unit, "-.slice")) {
1798 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1801 if (!endswith(unit, ".slice"))
1804 r = unit_name_to_prefix(unit, &p);
1808 dash = strchr(p, '-');
1810 /* Don't allow initial dashes */
1815 _cleanup_free_ char *escaped = NULL;
1816 char n[dash - p + sizeof(".slice")];
1818 /* Don't allow trailing or double dashes */
1819 if (dash[1] == 0 || dash[1] == '-')
1822 strcpy(stpncpy(n, p, dash - p), ".slice");
1823 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1826 escaped = cg_escape(n);
1830 if (!strextend(&s, escaped, "/", NULL))
1833 dash = strchr(dash+1, '-');
1836 e = cg_escape(unit);
1840 if (!strextend(&s, e, NULL))
1850 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1851 _cleanup_free_ char *p = NULL;
1854 r = cg_get_path(controller, path, attribute, &p);
1858 return write_string_file_no_create(p, value);
1861 /// UNNEEDED by elogind
1863 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1864 _cleanup_free_ char *p = NULL;
1867 r = cg_get_path(controller, path, attribute, &p);
1871 return read_one_line_file(p, ret);
1874 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1878 /* This one will create a cgroup in our private tree, but also
1879 * duplicate it in the trees specified in mask, and remove it
1882 /* First create the cgroup in our own hierarchy. */
1883 r = cg_create(ELOGIND_CGROUP_CONTROLLER, path);
1887 /* If we are in the unified hierarchy, we are done now */
1888 unified = cg_unified();
1894 /* Otherwise, do the same in the other hierarchies */
1895 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1896 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1899 n = cgroup_controller_to_string(c);
1902 (void) cg_create(n, path);
1903 else if (supported & bit)
1904 (void) cg_trim(n, path, true);
1911 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1915 r = cg_attach(ELOGIND_CGROUP_CONTROLLER, path, pid);
1919 unified = cg_unified();
1925 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1926 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1927 const char *p = NULL;
1929 if (!(supported & bit))
1933 p = path_callback(bit, userdata);
1938 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
1944 /// UNNEEDED by elogind
1946 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
1951 SET_FOREACH(pidp, pids, i) {
1952 pid_t pid = PTR_TO_PID(pidp);
1955 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
1956 if (q < 0 && r >= 0)
1963 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
1967 if (!path_equal(from, to)) {
1968 r = cg_migrate_recursive(ELOGIND_CGROUP_CONTROLLER, from, ELOGIND_CGROUP_CONTROLLER, to, false, true);
1973 unified = cg_unified();
1979 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1980 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1981 const char *p = NULL;
1983 if (!(supported & bit))
1987 p = to_callback(bit, userdata);
1992 (void) cg_migrate_recursive_fallback(ELOGIND_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, false, false);
1998 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2002 r = cg_trim(ELOGIND_CGROUP_CONTROLLER, path, delete_root);
2006 unified = cg_unified();
2012 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2013 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2015 if (!(supported & bit))
2018 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2025 int cg_mask_supported(CGroupMask *ret) {
2026 CGroupMask mask = 0;
2029 /* Determines the mask of supported cgroup controllers. Only
2030 * includes controllers we can make sense of and that are
2031 * actually accessible. */
2033 unified = cg_unified();
2037 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2040 /* In the unified hierarchy we can read the supported
2041 * and accessible controllers from a the top-level
2042 * cgroup attribute */
2044 r = cg_get_root_path(&root);
2048 r = cg_get_path(ELOGIND_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2052 r = read_one_line_file(path, &controllers);
2058 _cleanup_free_ char *n = NULL;
2061 r = extract_first_word(&c, &n, NULL, 0);
2067 v = cgroup_controller_from_string(n);
2071 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2074 /* Currently, we only support the memory controller in
2075 * the unified hierarchy, mask everything else off. */
2076 mask &= CGROUP_MASK_MEMORY;
2081 /* In the legacy hierarchy, we check whether which
2082 * hierarchies are mounted. */
2084 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2087 n = cgroup_controller_to_string(c);
2088 if (controller_is_accessible(n) >= 0)
2089 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2097 /// UNNEEDED by elogind
2099 int cg_kernel_controllers(Set *controllers) {
2100 _cleanup_fclose_ FILE *f = NULL;
2104 assert(controllers);
2106 /* Determines the full list of kernel-known controllers. Might
2107 * include controllers we don't actually support, arbitrary
2108 * named hierarchies and controllers that aren't currently
2109 * accessible (because not mounted). */
2111 f = fopen("/proc/cgroups", "re");
2113 if (errno == ENOENT)
2118 /* Ignore the header line */
2119 (void) fgets(buf, sizeof(buf), f);
2126 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2131 if (ferror(f) && errno != 0)
2142 if (!cg_controller_is_valid(controller)) {
2147 r = set_consume(controllers, controller);
2156 static thread_local int unified_cache = -1;
2158 int cg_unified(void) {
2161 /* Checks if we support the unified hierarchy. Returns an
2162 * error when the cgroup hierarchies aren't mounted yet or we
2163 * have any other trouble determining if the unified hierarchy
2166 if (unified_cache >= 0)
2167 return unified_cache;
2169 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2172 /// elogind can not support the unified hierarchy as a controller,
2173 /// so always assume a classical hierarchy.
2174 /// If, ond only *if*, someone really wants to substitute systemd-login
2175 /// in an environment managed by systemd with elogin, we might have to
2176 /// add such a support.
2178 if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC))
2179 unified_cache = true;
2180 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2182 if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2184 unified_cache = false;
2188 return unified_cache;
2191 /// UNNEEDED by elogind
2193 void cg_unified_flush(void) {
2197 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2198 _cleanup_free_ char *fs = NULL;
2207 unified = cg_unified();
2210 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2213 r = cg_get_path(ELOGIND_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2217 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2218 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2221 if (!(supported & bit))
2224 n = cgroup_controller_to_string(c);
2226 char s[1 + strlen(n) + 1];
2228 s[0] = mask & bit ? '+' : '-';
2231 r = write_string_file(fs, s, 0);
2233 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2241 bool cg_is_unified_wanted(void) {
2242 static thread_local int wanted = -1;
2245 /* If the hierarchy is already mounted, then follow whatever
2246 * was chosen for it. */
2247 unified = cg_unified();
2251 /* Otherwise, let's see what the kernel command line has to
2252 * say. Since checking that is expensive, let's cache the
2257 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2259 return (wanted = true);
2261 _cleanup_free_ char *value = NULL;
2263 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2267 return (wanted = false);
2269 return (wanted = parse_boolean(value) > 0);
2273 /// UNNEEDED by elogind
2275 bool cg_is_legacy_wanted(void) {
2276 return !cg_is_unified_wanted();
2280 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2281 [CGROUP_CONTROLLER_CPU] = "cpu",
2282 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2283 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2284 [CGROUP_CONTROLLER_MEMORY] = "memory",
2285 [CGROUP_CONTROLLER_DEVICE] = "devices",
2288 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);