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>
31 #include <sys/xattr.h>
34 #include "alloc-util.h"
35 #include "cgroup-util.h"
37 #include "dirent-util.h"
38 #include "extract-word.h"
41 #include "format-util.h"
44 #include "login-util.h"
46 //#include "missing.h"
48 #include "parse-util.h"
49 #include "path-util.h"
50 #include "proc-cmdline.h"
51 #include "process-util.h"
53 //#include "special.h"
54 #include "stat-util.h"
55 #include "stdio-util.h"
56 #include "string-table.h"
57 #include "string-util.h"
58 #include "unit-name.h"
59 #include "user-util.h"
61 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
62 _cleanup_free_ char *fs = NULL;
68 r = cg_get_path(controller, path, "cgroup.procs", &fs);
80 int cg_read_pid(FILE *f, pid_t *_pid) {
83 /* Note that the cgroup.procs might contain duplicates! See
84 * cgroups.txt for details. */
90 if (fscanf(f, "%lu", &ul) != 1) {
95 return errno > 0 ? -errno : -EIO;
105 int cg_read_event(const char *controller, const char *path, const char *event,
108 _cleanup_free_ char *events = NULL, *content = NULL;
112 r = cg_get_path(controller, path, "cgroup.events", &events);
116 r = read_full_file(events, &content, NULL);
121 while ((line = strsep(&p, "\n"))) {
124 key = strsep(&line, " ");
128 if (strcmp(key, event))
138 #if 0 /// UNNEEDED by elogind
139 bool cg_ns_supported(void) {
140 static thread_local int enabled = -1;
145 if (access("/proc/self/ns/cgroup", F_OK) == 0)
154 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
155 _cleanup_free_ char *fs = NULL;
161 /* This is not recursive! */
163 r = cg_get_path(controller, path, NULL, &fs);
175 int cg_read_subgroup(DIR *d, char **fn) {
181 FOREACH_DIRENT_ALL(de, d, return -errno) {
184 if (de->d_type != DT_DIR)
187 if (dot_or_dot_dot(de->d_name))
190 b = strdup(de->d_name);
201 int cg_rmdir(const char *controller, const char *path) {
202 _cleanup_free_ char *p = NULL;
205 r = cg_get_path(controller, path, NULL, &p);
210 if (r < 0 && errno != ENOENT)
217 const char *controller,
222 cg_kill_log_func_t log_kill,
225 _cleanup_set_free_ Set *allocated_set = NULL;
232 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
233 * SIGCONT on SIGKILL. */
234 if (IN_SET(sig, SIGCONT, SIGKILL))
235 flags &= ~CGROUP_SIGCONT;
237 /* This goes through the tasks list and kills them all. This
238 * is repeated until no further processes are added to the
239 * tasks list, to properly handle forking processes */
242 s = allocated_set = set_new(NULL);
250 _cleanup_fclose_ FILE *f = NULL;
254 r = cg_enumerate_processes(controller, path, &f);
256 if (ret >= 0 && r != -ENOENT)
262 while ((r = cg_read_pid(f, &pid)) > 0) {
264 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
267 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
271 log_kill(pid, sig, userdata);
273 /* If we haven't killed this process yet, kill
275 if (kill(pid, sig) < 0) {
276 if (ret >= 0 && errno != ESRCH)
279 if (flags & CGROUP_SIGCONT)
280 (void) kill(pid, SIGCONT);
288 r = set_put(s, PID_TO_PTR(pid));
304 /* To avoid racing against processes which fork
305 * quicker than we can kill them we repeat this until
306 * no new pids need to be killed. */
313 int cg_kill_recursive(
314 const char *controller,
319 cg_kill_log_func_t log_kill,
322 _cleanup_set_free_ Set *allocated_set = NULL;
323 _cleanup_closedir_ DIR *d = NULL;
331 s = allocated_set = set_new(NULL);
336 ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
338 r = cg_enumerate_subgroups(controller, path, &d);
340 if (ret >= 0 && r != -ENOENT)
346 while ((r = cg_read_subgroup(d, &fn)) > 0) {
347 _cleanup_free_ char *p = NULL;
349 p = strjoin(path, "/", fn);
354 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
355 if (r != 0 && ret >= 0)
358 if (ret >= 0 && r < 0)
361 if (flags & CGROUP_REMOVE) {
362 r = cg_rmdir(controller, path);
363 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
378 _cleanup_set_free_ Set *s = NULL;
393 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
394 cfrom, pfrom, cto, pto,
395 (flags & CGROUP_IGNORE_SELF)
396 ? "ignoring self" : "watching self");
398 _cleanup_fclose_ FILE *f = NULL;
402 r = cg_enumerate_processes(cfrom, pfrom, &f);
404 if (ret >= 0 && r != -ENOENT)
410 while ((r = cg_read_pid(f, &pid)) > 0) {
412 /* This might do weird stuff if we aren't a
413 * single-threaded program. However, we
414 * luckily know we are not */
415 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
418 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
421 /* Ignore kernel threads. Since they can only
422 * exist in the root cgroup, we only check for
425 (isempty(pfrom) || path_equal(pfrom, "/")) &&
426 is_kernel_thread(pid) > 0)
429 r = cg_attach(cto, pto, pid);
431 if (ret >= 0 && r != -ESRCH)
438 r = set_put(s, PID_TO_PTR(pid));
458 int cg_migrate_recursive(
465 _cleanup_closedir_ DIR *d = NULL;
474 ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
476 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
478 if (ret >= 0 && r != -ENOENT)
484 while ((r = cg_read_subgroup(d, &fn)) > 0) {
485 _cleanup_free_ char *p = NULL;
487 p = strjoin(pfrom, "/", fn);
492 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
493 if (r != 0 && ret >= 0)
497 if (r < 0 && ret >= 0)
500 if (flags & CGROUP_REMOVE) {
501 r = cg_rmdir(cfrom, pfrom);
502 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
509 int cg_migrate_recursive_fallback(
523 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
525 char prefix[strlen(pto) + 1];
527 /* This didn't work? Then let's try all prefixes of the destination */
529 PATH_FOREACH_PREFIX(prefix, pto) {
532 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
541 static const char *controller_to_dirname(const char *controller) {
546 /* Converts a controller name to the directory name below
547 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
548 * just cuts off the name= prefixed used for named
549 * hierarchies, if it is specified. */
551 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
552 controller = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
554 e = startswith(controller, "name=");
561 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
568 dn = controller_to_dirname(controller);
570 if (isempty(path) && isempty(suffix))
571 t = strappend("/sys/fs/cgroup/", dn);
572 else if (isempty(path))
573 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix);
574 else if (isempty(suffix))
575 t = strjoin("/sys/fs/cgroup/", dn, "/", path);
577 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix);
585 static int join_path_unified(const char *path, const char *suffix, char **fs) {
590 if (isempty(path) && isempty(suffix))
591 t = strdup("/sys/fs/cgroup");
592 else if (isempty(path))
593 t = strappend("/sys/fs/cgroup/", suffix);
594 else if (isempty(suffix))
595 t = strappend("/sys/fs/cgroup/", path);
597 t = strjoin("/sys/fs/cgroup/", path, "/", suffix);
605 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
613 /* If no controller is specified, we return the path
614 * *below* the controllers, without any prefix. */
616 if (!path && !suffix)
624 t = strjoin(path, "/", suffix);
628 *fs = path_kill_slashes(t);
632 if (!cg_controller_is_valid(controller))
635 if (cg_all_unified())
636 r = join_path_unified(path, suffix, fs);
638 r = join_path_legacy(controller, path, suffix, fs);
642 path_kill_slashes(*fs);
646 static int controller_is_accessible(const char *controller) {
650 /* Checks whether a specific controller is accessible,
651 * i.e. its hierarchy mounted. In the unified hierarchy all
652 * controllers are considered accessible, except for the named
655 if (!cg_controller_is_valid(controller))
658 if (cg_all_unified()) {
659 /* We don't support named hierarchies if we are using
660 * the unified hierarchy. */
662 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
665 if (startswith(controller, "name="))
671 dn = controller_to_dirname(controller);
672 cc = strjoina("/sys/fs/cgroup/", dn);
674 if (laccess(cc, F_OK) < 0)
681 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
687 /* Check if the specified controller is actually accessible */
688 r = controller_is_accessible(controller);
692 return cg_get_path(controller, path, suffix, fs);
695 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
700 if (typeflag != FTW_DP)
703 if (ftwbuf->level < 1)
710 int cg_trim(const char *controller, const char *path, bool delete_root) {
711 _cleanup_free_ char *fs = NULL;
716 r = cg_get_path(controller, path, NULL, &fs);
721 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
731 if (rmdir(fs) < 0 && errno != ENOENT)
738 int cg_create(const char *controller, const char *path) {
739 _cleanup_free_ char *fs = NULL;
742 r = cg_get_path_and_check(controller, path, NULL, &fs);
746 r = mkdir_parents(fs, 0755);
750 if (mkdir(fs, 0755) < 0) {
761 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
766 r = cg_create(controller, path);
770 q = cg_attach(controller, path, pid);
774 /* This does not remove the cgroup on failure */
778 int cg_attach(const char *controller, const char *path, pid_t pid) {
779 _cleanup_free_ char *fs = NULL;
780 char c[DECIMAL_STR_MAX(pid_t) + 2];
786 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
793 xsprintf(c, PID_FMT "\n", pid);
795 return write_string_file(fs, c, 0);
798 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
805 r = cg_attach(controller, path, pid);
807 char prefix[strlen(path) + 1];
809 /* This didn't work? Then let's try all prefixes of
812 PATH_FOREACH_PREFIX(prefix, path) {
815 q = cg_attach(controller, prefix, pid);
824 #if 0 /// UNNEEDED by elogind
825 int cg_set_group_access(
826 const char *controller,
832 _cleanup_free_ char *fs = NULL;
835 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
838 if (mode != MODE_INVALID)
841 r = cg_get_path(controller, path, NULL, &fs);
845 return chmod_and_chown(fs, mode, uid, gid);
848 int cg_set_task_access(
849 const char *controller,
855 _cleanup_free_ char *fs = NULL, *procs = NULL;
860 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
863 if (mode != MODE_INVALID)
866 r = cg_get_path(controller, path, "cgroup.procs", &fs);
870 r = chmod_and_chown(fs, mode, uid, gid);
874 if (cg_unified(controller))
877 /* Compatibility, Always keep values for "tasks" in sync with
879 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
880 (void) chmod_and_chown(procs, mode, uid, gid);
885 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
886 _cleanup_free_ char *fs = NULL;
891 assert(value || size <= 0);
893 r = cg_get_path(controller, path, NULL, &fs);
897 if (setxattr(fs, name, value, size, flags) < 0)
903 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
904 _cleanup_free_ char *fs = NULL;
911 r = cg_get_path(controller, path, NULL, &fs);
915 n = getxattr(fs, name, value, size);
923 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
924 _cleanup_fclose_ FILE *f = NULL;
926 const char *fs, *controller_str;
934 if (!cg_controller_is_valid(controller))
937 controller = SYSTEMD_CGROUP_CONTROLLER;
939 unified = cg_unified(controller);
941 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
942 controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
944 controller_str = controller;
946 cs = strlen(controller_str);
949 fs = procfs_file_alloca(pid, "cgroup");
950 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
951 pid, fs, controller);
954 return errno == ENOENT ? -ESRCH : -errno;
956 FOREACH_LINE(line, f, return -errno) {
962 e = startswith(line, "0:");
972 const char *word, *state;
975 l = strchr(line, ':');
985 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
986 if (k == cs && memcmp(word, controller_str, cs) == 0) {
996 log_debug_elogind("Found %s:%s", line, e+1);
1008 int cg_install_release_agent(const char *controller, const char *agent) {
1009 _cleanup_free_ char *fs = NULL, *contents = NULL;
1015 if (cg_unified(controller)) /* doesn't apply to unified hierarchy */
1018 r = cg_get_path(controller, NULL, "release_agent", &fs);
1022 r = read_one_line_file(fs, &contents);
1026 sc = strstrip(contents);
1028 r = write_string_file(fs, agent, 0);
1031 } else if (!path_equal(sc, agent))
1035 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1039 contents = mfree(contents);
1040 r = read_one_line_file(fs, &contents);
1044 sc = strstrip(contents);
1045 if (streq(sc, "0")) {
1046 r = write_string_file(fs, "1", 0);
1053 if (!streq(sc, "1"))
1059 int cg_uninstall_release_agent(const char *controller) {
1060 _cleanup_free_ char *fs = NULL;
1063 if (cg_unified(controller)) /* Doesn't apply to unified hierarchy */
1066 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1070 r = write_string_file(fs, "0", 0);
1076 r = cg_get_path(controller, NULL, "release_agent", &fs);
1080 r = write_string_file(fs, "", 0);
1087 int cg_is_empty(const char *controller, const char *path) {
1088 _cleanup_fclose_ FILE *f = NULL;
1094 r = cg_enumerate_processes(controller, path, &f);
1100 r = cg_read_pid(f, &pid);
1107 int cg_is_empty_recursive(const char *controller, const char *path) {
1112 /* The root cgroup is always populated */
1113 if (controller && (isempty(path) || path_equal(path, "/")))
1116 if (cg_unified(controller)) {
1117 _cleanup_free_ char *t = NULL;
1119 /* On the unified hierarchy we can check empty state
1120 * via the "populated" attribute of "cgroup.events". */
1122 r = cg_read_event(controller, path, "populated", &t);
1126 return streq(t, "0");
1128 _cleanup_closedir_ DIR *d = NULL;
1131 r = cg_is_empty(controller, path);
1135 r = cg_enumerate_subgroups(controller, path, &d);
1141 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1142 _cleanup_free_ char *p = NULL;
1144 p = strjoin(path, "/", fn);
1149 r = cg_is_empty_recursive(controller, p);
1160 int cg_split_spec(const char *spec, char **controller, char **path) {
1161 char *t = NULL, *u = NULL;
1167 if (!path_is_safe(spec))
1175 *path = path_kill_slashes(t);
1184 e = strchr(spec, ':');
1186 if (!cg_controller_is_valid(spec))
1203 t = strndup(spec, e-spec);
1206 if (!cg_controller_is_valid(t)) {
1220 if (!path_is_safe(u) ||
1221 !path_is_absolute(u)) {
1227 path_kill_slashes(u);
1243 int cg_mangle_path(const char *path, char **result) {
1244 _cleanup_free_ char *c = NULL, *p = NULL;
1251 /* First, check if it already is a filesystem path */
1252 if (path_startswith(path, "/sys/fs/cgroup")) {
1258 *result = path_kill_slashes(t);
1262 /* Otherwise, treat it as cg spec */
1263 r = cg_split_spec(path, &c, &p);
1267 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1270 int cg_get_root_path(char **path) {
1271 #if 0 /// elogind does not support systemd scopes and slices
1277 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1281 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1283 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1285 e = endswith(p, "/system"); /* even more legacy */
1293 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1297 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1298 _cleanup_free_ char *rt = NULL;
1306 /* If the root was specified let's use that, otherwise
1307 * let's determine it from PID 1 */
1309 r = cg_get_root_path(&rt);
1314 log_debug_elogind("Determined root path: \"%s\"", root);
1317 p = path_startswith(cgroup, root);
1318 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1319 if (p && p > cgroup)
1321 if (p && p[0] && (p > cgroup))
1330 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1331 _cleanup_free_ char *raw = NULL;
1338 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1342 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1343 raw, pid, root ? root : "NULL");
1344 r = cg_shift_path(raw, root, &c);
1360 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1365 #if 0 /// UNNEEDED by elogind
1366 int cg_path_decode_unit(const char *cgroup, char **unit) {
1373 n = strcspn(cgroup, "/");
1377 c = strndupa(cgroup, n);
1380 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1391 static bool valid_slice_name(const char *p, size_t n) {
1396 if (n < strlen("x.slice"))
1399 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1405 c = cg_unescape(buf);
1407 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1413 static const char *skip_slices(const char *p) {
1416 /* Skips over all slice assignments */
1421 p += strspn(p, "/");
1423 n = strcspn(p, "/");
1424 if (!valid_slice_name(p, n))
1431 int cg_path_get_unit(const char *path, char **ret) {
1439 e = skip_slices(path);
1441 r = cg_path_decode_unit(e, &unit);
1445 /* We skipped over the slices, don't accept any now */
1446 if (endswith(unit, ".slice")) {
1455 int cg_pid_get_unit(pid_t pid, char **unit) {
1456 _cleanup_free_ char *cgroup = NULL;
1461 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1465 return cg_path_get_unit(cgroup, unit);
1469 * Skip session-*.scope, but require it to be there.
1471 static const char *skip_session(const char *p) {
1477 p += strspn(p, "/");
1479 n = strcspn(p, "/");
1480 if (n < strlen("session-x.scope"))
1483 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1484 char buf[n - 8 - 6 + 1];
1486 memcpy(buf, p + 8, n - 8 - 6);
1489 /* Note that session scopes never need unescaping,
1490 * since they cannot conflict with the kernel's own
1491 * names, hence we don't need to call cg_unescape()
1494 if (!session_id_valid(buf))
1498 p += strspn(p, "/");
1506 * Skip user@*.service, but require it to be there.
1508 static const char *skip_user_manager(const char *p) {
1514 p += strspn(p, "/");
1516 n = strcspn(p, "/");
1517 if (n < strlen("user@x.service"))
1520 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1521 char buf[n - 5 - 8 + 1];
1523 memcpy(buf, p + 5, n - 5 - 8);
1526 /* Note that user manager services never need unescaping,
1527 * since they cannot conflict with the kernel's own
1528 * names, hence we don't need to call cg_unescape()
1531 if (parse_uid(buf, NULL) < 0)
1535 p += strspn(p, "/");
1543 static const char *skip_user_prefix(const char *path) {
1548 /* Skip slices, if there are any */
1549 e = skip_slices(path);
1551 /* Skip the user manager, if it's in the path now... */
1552 t = skip_user_manager(e);
1556 /* Alternatively skip the user session if it is in the path... */
1557 return skip_session(e);
1560 int cg_path_get_user_unit(const char *path, char **ret) {
1566 t = skip_user_prefix(path);
1570 /* And from here on it looks pretty much the same as for a
1571 * system unit, hence let's use the same parser from here
1573 return cg_path_get_unit(t, ret);
1576 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1577 _cleanup_free_ char *cgroup = NULL;
1582 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1586 return cg_path_get_user_unit(cgroup, unit);
1589 int cg_path_get_machine_name(const char *path, char **machine) {
1590 _cleanup_free_ char *u = NULL;
1594 r = cg_path_get_unit(path, &u);
1598 sl = strjoina("/run/systemd/machines/unit:", u);
1599 return readlink_malloc(sl, machine);
1602 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1603 _cleanup_free_ char *cgroup = NULL;
1608 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1612 return cg_path_get_machine_name(cgroup, machine);
1616 int cg_path_get_session(const char *path, char **session) {
1617 #if 0 /// UNNEEDED by elogind
1618 _cleanup_free_ char *unit = NULL;
1624 r = cg_path_get_unit(path, &unit);
1628 start = startswith(unit, "session-");
1631 end = endswith(start, ".scope");
1636 if (!session_id_valid(start))
1639 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1640 wrinkle is that SESSION might be escaped. */
1641 const char *e, *n, *start;
1644 log_debug_elogind("path is \"%s\"", path);
1645 assert(path[0] == '/');
1648 n = strchrnul(e, '/');
1652 start = strndupa(e, n - e);
1653 start = cg_unescape(start);
1662 log_debug_elogind("found session: \"%s\"", start);
1673 int cg_pid_get_session(pid_t pid, char **session) {
1674 _cleanup_free_ char *cgroup = NULL;
1677 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1681 return cg_path_get_session(cgroup, session);
1684 #if 0 /// UNNEEDED by elogind
1685 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1686 _cleanup_free_ char *slice = NULL;
1692 r = cg_path_get_slice(path, &slice);
1696 start = startswith(slice, "user-");
1699 end = endswith(start, ".slice");
1704 if (parse_uid(start, uid) < 0)
1710 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1711 _cleanup_free_ char *cgroup = NULL;
1714 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1718 return cg_path_get_owner_uid(cgroup, uid);
1721 int cg_path_get_slice(const char *p, char **slice) {
1722 const char *e = NULL;
1727 /* Finds the right-most slice unit from the beginning, but
1728 * stops before we come to the first non-slice unit. */
1733 p += strspn(p, "/");
1735 n = strcspn(p, "/");
1736 if (!valid_slice_name(p, n)) {
1741 s = strdup(SPECIAL_ROOT_SLICE);
1749 return cg_path_decode_unit(e, slice);
1757 int cg_pid_get_slice(pid_t pid, char **slice) {
1758 _cleanup_free_ char *cgroup = NULL;
1763 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1767 return cg_path_get_slice(cgroup, slice);
1770 int cg_path_get_user_slice(const char *p, char **slice) {
1775 t = skip_user_prefix(p);
1779 /* And now it looks pretty much the same as for a system
1780 * slice, so let's just use the same parser from here on. */
1781 return cg_path_get_slice(t, slice);
1784 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1785 _cleanup_free_ char *cgroup = NULL;
1790 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1794 return cg_path_get_user_slice(cgroup, slice);
1798 char *cg_escape(const char *p) {
1799 bool need_prefix = false;
1801 /* This implements very minimal escaping for names to be used
1802 * as file names in the cgroup tree: any name which might
1803 * conflict with a kernel name or is prefixed with '_' is
1804 * prefixed with a '_'. That way, when reading cgroup names it
1805 * is sufficient to remove a single prefixing underscore if
1808 /* The return value of this function (unlike cg_unescape())
1814 streq(p, "notify_on_release") ||
1815 streq(p, "release_agent") ||
1816 streq(p, "tasks") ||
1817 startswith(p, "cgroup."))
1822 dot = strrchr(p, '.');
1827 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1830 n = cgroup_controller_to_string(c);
1835 if (memcmp(p, n, l) != 0)
1845 return strappend("_", p);
1850 char *cg_unescape(const char *p) {
1853 /* The return value of this function (unlike cg_escape())
1854 * doesn't need free()! */
1862 #define CONTROLLER_VALID \
1866 bool cg_controller_is_valid(const char *p) {
1872 if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
1875 s = startswith(p, "name=");
1879 if (*p == 0 || *p == '_')
1882 for (t = p; *t; t++)
1883 if (!strchr(CONTROLLER_VALID, *t))
1886 if (t - p > FILENAME_MAX)
1892 #if 0 /// UNNEEDED by elogind
1893 int cg_slice_to_path(const char *unit, char **ret) {
1894 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1901 if (streq(unit, SPECIAL_ROOT_SLICE)) {
1911 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1914 if (!endswith(unit, ".slice"))
1917 r = unit_name_to_prefix(unit, &p);
1921 dash = strchr(p, '-');
1923 /* Don't allow initial dashes */
1928 _cleanup_free_ char *escaped = NULL;
1929 char n[dash - p + sizeof(".slice")];
1931 /* Don't allow trailing or double dashes */
1932 if (dash[1] == 0 || dash[1] == '-')
1935 strcpy(stpncpy(n, p, dash - p), ".slice");
1936 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1939 escaped = cg_escape(n);
1943 if (!strextend(&s, escaped, "/", NULL))
1946 dash = strchr(dash+1, '-');
1949 e = cg_escape(unit);
1953 if (!strextend(&s, e, NULL))
1963 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1964 _cleanup_free_ char *p = NULL;
1967 r = cg_get_path(controller, path, attribute, &p);
1971 return write_string_file(p, value, 0);
1974 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1975 _cleanup_free_ char *p = NULL;
1978 r = cg_get_path(controller, path, attribute, &p);
1982 return read_one_line_file(p, ret);
1985 #if 0 /// UNNEEDED by elogind
1986 int cg_get_keyed_attribute(const char *controller, const char *path, const char *attribute, const char **keys, char **values) {
1987 _cleanup_free_ char *filename = NULL, *content = NULL;
1991 for (i = 0; keys[i]; i++)
1994 r = cg_get_path(controller, path, attribute, &filename);
1998 r = read_full_file(filename, &content, NULL);
2003 while ((line = strsep(&p, "\n"))) {
2006 key = strsep(&line, " ");
2008 for (i = 0; keys[i]; i++) {
2009 if (streq(key, keys[i])) {
2010 values[i] = strdup(line);
2016 for (i = 0; keys[i]; i++) {
2018 for (i = 0; keys[i]; i++) {
2029 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2033 /* This one will create a cgroup in our private tree, but also
2034 * duplicate it in the trees specified in mask, and remove it
2037 /* First create the cgroup in our own hierarchy. */
2038 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2042 /* If we are in the unified hierarchy, we are done now */
2043 if (cg_all_unified())
2046 /* Otherwise, do the same in the other hierarchies */
2047 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2048 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2051 n = cgroup_controller_to_string(c);
2054 (void) cg_create(n, path);
2055 else if (supported & bit)
2056 (void) cg_trim(n, path, true);
2062 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2066 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2070 if (cg_all_unified())
2073 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2074 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2075 const char *p = NULL;
2077 if (!(supported & bit))
2081 p = path_callback(bit, userdata);
2086 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2092 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2097 SET_FOREACH(pidp, pids, i) {
2098 pid_t pid = PTR_TO_PID(pidp);
2101 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2102 if (q < 0 && r >= 0)
2109 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2113 if (!path_equal(from, to)) {
2114 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2119 if (cg_all_unified())
2122 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2123 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2124 const char *p = NULL;
2126 if (!(supported & bit))
2130 p = to_callback(bit, userdata);
2135 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2141 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2145 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2149 if (cg_all_unified())
2152 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2153 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2155 if (!(supported & bit))
2158 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2165 int cg_mask_supported(CGroupMask *ret) {
2166 CGroupMask mask = 0;
2169 /* Determines the mask of supported cgroup controllers. Only
2170 * includes controllers we can make sense of and that are
2171 * actually accessible. */
2173 if (cg_all_unified()) {
2174 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2177 /* In the unified hierarchy we can read the supported
2178 * and accessible controllers from a the top-level
2179 * cgroup attribute */
2181 r = cg_get_root_path(&root);
2185 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2189 r = read_one_line_file(path, &controllers);
2195 _cleanup_free_ char *n = NULL;
2198 r = extract_first_word(&c, &n, NULL, 0);
2204 v = cgroup_controller_from_string(n);
2208 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2211 /* Currently, we support the cpu, memory, io and pids
2212 * controller in the unified hierarchy, mask
2213 * everything else off. */
2214 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2219 /* In the legacy hierarchy, we check whether which
2220 * hierarchies are mounted. */
2222 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2225 n = cgroup_controller_to_string(c);
2226 if (controller_is_accessible(n) >= 0)
2227 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2235 #if 0 /// UNNEEDED by elogind
2236 int cg_kernel_controllers(Set *controllers) {
2237 _cleanup_fclose_ FILE *f = NULL;
2241 assert(controllers);
2243 /* Determines the full list of kernel-known controllers. Might
2244 * include controllers we don't actually support, arbitrary
2245 * named hierarchies and controllers that aren't currently
2246 * accessible (because not mounted). */
2248 f = fopen("/proc/cgroups", "re");
2250 if (errno == ENOENT)
2255 /* Ignore the header line */
2256 (void) fgets(buf, sizeof(buf), f);
2263 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2268 if (ferror(f) && errno > 0)
2279 if (!cg_controller_is_valid(controller)) {
2284 r = set_consume(controllers, controller);
2293 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2295 static int cg_update_unified(void) {
2299 /* Checks if we support the unified hierarchy. Returns an
2300 * error when the cgroup hierarchies aren't mounted yet or we
2301 * have any other trouble determining if the unified hierarchy
2304 if (unified_cache >= CGROUP_UNIFIED_NONE)
2307 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2310 #if 0 /// UNNEEDED by elogind
2311 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2312 unified_cache = CGROUP_UNIFIED_ALL;
2313 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2314 if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2317 unified_cache = F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC) ?
2318 CGROUP_UNIFIED_SYSTEMD : CGROUP_UNIFIED_NONE;
2322 /* elogind can not support the unified hierarchy as a controller,
2323 * so always assume a classical hierarchy.
2324 * If, and only *if*, someone really wants to substitute systemd-login
2325 * in an environment managed by systemd with elogind, we might have to
2326 * add such a support. */
2327 unified_cache = CGROUP_UNIFIED_NONE;
2333 bool cg_unified(const char *controller) {
2335 assert(cg_update_unified() >= 0);
2337 if (streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER))
2338 return unified_cache >= CGROUP_UNIFIED_SYSTEMD;
2340 return unified_cache >= CGROUP_UNIFIED_ALL;
2343 bool cg_all_unified(void) {
2345 return cg_unified(NULL);
2348 #if 0 /// UNNEEDED by elogind
2349 int cg_unified_flush(void) {
2350 unified_cache = CGROUP_UNIFIED_UNKNOWN;
2352 return cg_update_unified();
2355 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2356 _cleanup_free_ char *fs = NULL;
2365 if (!cg_all_unified()) /* on the legacy hiearchy there's no joining of controllers defined */
2368 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2372 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2373 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2376 if (!(supported & bit))
2379 n = cgroup_controller_to_string(c);
2381 char s[1 + strlen(n) + 1];
2383 s[0] = mask & bit ? '+' : '-';
2386 r = write_string_file(fs, s, 0);
2388 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2395 bool cg_is_unified_wanted(void) {
2396 static thread_local int wanted = -1;
2400 /* If the hierarchy is already mounted, then follow whatever
2401 * was chosen for it. */
2402 if (cg_unified_flush() >= 0)
2403 return cg_all_unified();
2405 /* Otherwise, let's see what the kernel command line has to
2406 * say. Since checking that is expensive, let's cache the
2411 r = proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b);
2415 return (wanted = r > 0 ? b : false);
2418 bool cg_is_legacy_wanted(void) {
2419 return !cg_is_unified_wanted();
2422 bool cg_is_unified_systemd_controller_wanted(void) {
2423 static thread_local int wanted = -1;
2427 /* If the unified hierarchy is requested in full, no need to
2428 * bother with this. */
2429 if (cg_is_unified_wanted())
2432 /* If the hierarchy is already mounted, then follow whatever
2433 * was chosen for it. */
2434 if (cg_unified_flush() >= 0)
2435 return cg_unified(SYSTEMD_CGROUP_CONTROLLER);
2437 /* Otherwise, let's see what the kernel command line has to
2438 * say. Since checking that is expensive, let's cache the
2443 r = proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b);
2448 bool cg_is_legacy_wanted(void) {
2450 /* The meaning of the kernel option is reversed wrt. to the return value
2451 * of this function, hence the negation. */
2452 return (wanted = r > 0 ? !b : false);
2453 return (wanted = r > 0 ? b : false);
2456 bool cg_is_legacy_systemd_controller_wanted(void) {
2457 return cg_is_legacy_wanted() && !cg_is_unified_systemd_controller_wanted();
2458 return (wanted = r > 0 ? !b : is_default);
2462 #if 0 /// UNNEEDED by elogind
2463 int cg_weight_parse(const char *s, uint64_t *ret) {
2468 *ret = CGROUP_WEIGHT_INVALID;
2472 r = safe_atou64(s, &u);
2476 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2483 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2484 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2485 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2486 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2487 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2490 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2491 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2492 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2493 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2494 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2497 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2499 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2504 *ret = CGROUP_CPU_SHARES_INVALID;
2508 r = safe_atou64(s, &u);
2512 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2519 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2524 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2528 r = safe_atou64(s, &u);
2532 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2540 bool is_cgroup_fs(const struct statfs *s) {
2541 return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2542 is_fs_type(s, CGROUP2_SUPER_MAGIC);
2545 bool fd_is_cgroup_fs(int fd) {
2548 if (fstatfs(fd, &s) < 0)
2551 return is_cgroup_fs(&s);
2554 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2555 [CGROUP_CONTROLLER_CPU] = "cpu",
2556 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2557 [CGROUP_CONTROLLER_IO] = "io",
2558 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2559 [CGROUP_CONTROLLER_MEMORY] = "memory",
2560 [CGROUP_CONTROLLER_DEVICES] = "devices",
2561 [CGROUP_CONTROLLER_PIDS] = "pids",
2564 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);