1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 //#include <sys/statfs.h>
14 #include <sys/types.h>
15 #include <sys/xattr.h>
18 #include "alloc-util.h"
19 #include "cgroup-util.h"
21 #include "dirent-util.h"
22 #include "extract-word.h"
25 #include "format-util.h"
28 #include "login-util.h"
30 //#include "missing.h"
32 #include "parse-util.h"
33 #include "path-util.h"
34 #include "proc-cmdline.h"
35 #include "process-util.h"
37 //#include "special.h"
38 #include "stat-util.h"
39 #include "stdio-util.h"
40 #include "string-table.h"
41 #include "string-util.h"
43 #include "unit-name.h"
44 #include "user-util.h"
46 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
47 _cleanup_free_ char *fs = NULL;
53 r = cg_get_path(controller, path, "cgroup.procs", &fs);
65 int cg_read_pid(FILE *f, pid_t *_pid) {
68 /* Note that the cgroup.procs might contain duplicates! See
69 * cgroups.txt for details. */
75 if (fscanf(f, "%lu", &ul) != 1) {
80 return errno > 0 ? -errno : -EIO;
91 const char *controller,
96 _cleanup_free_ char *events = NULL, *content = NULL;
100 r = cg_get_path(controller, path, "cgroup.events", &events);
104 r = read_full_file(events, &content, NULL);
109 while ((line = strsep(&p, "\n"))) {
112 key = strsep(&line, " ");
116 if (strcmp(key, event))
126 #if 0 /// UNNEEDED by elogind
127 bool cg_ns_supported(void) {
128 static thread_local int enabled = -1;
133 if (access("/proc/self/ns/cgroup", F_OK) == 0)
142 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
143 _cleanup_free_ char *fs = NULL;
149 /* This is not recursive! */
151 r = cg_get_path(controller, path, NULL, &fs);
163 int cg_read_subgroup(DIR *d, char **fn) {
169 FOREACH_DIRENT_ALL(de, d, return -errno) {
172 if (de->d_type != DT_DIR)
175 if (dot_or_dot_dot(de->d_name))
178 b = strdup(de->d_name);
189 int cg_rmdir(const char *controller, const char *path) {
190 _cleanup_free_ char *p = NULL;
193 r = cg_get_path(controller, path, NULL, &p);
198 if (r < 0 && errno != ENOENT)
201 r = cg_hybrid_unified();
207 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
208 r = cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
210 log_warning_errno(r, "Failed to remove compat systemd cgroup %s: %m", path);
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);
247 my_pid = getpid_cached();
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 && !IN_SET(r, -ENOENT, -EBUSY))
378 _cleanup_set_free_ Set *s = NULL;
391 my_pid = getpid_cached();
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 empty_or_root(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 && !IN_SET(r, -ENOENT, -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 if (cg_hybrid_unified() > 0)
553 controller = SYSTEMD_CGROUP_CONTROLLER_HYBRID;
555 controller = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
558 e = startswith(controller, "name=");
565 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
572 dn = controller_to_dirname(controller);
574 if (isempty(path) && isempty(suffix))
575 t = strappend("/sys/fs/cgroup/", dn);
576 else if (isempty(path))
577 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix);
578 else if (isempty(suffix))
579 t = strjoin("/sys/fs/cgroup/", dn, "/", path);
581 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix);
589 static int join_path_unified(const char *path, const char *suffix, char **fs) {
594 if (isempty(path) && isempty(suffix))
595 t = strdup("/sys/fs/cgroup");
596 else if (isempty(path))
597 t = strappend("/sys/fs/cgroup/", suffix);
598 else if (isempty(suffix))
599 t = strappend("/sys/fs/cgroup/", path);
601 t = strjoin("/sys/fs/cgroup/", path, "/", suffix);
609 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
617 /* If no controller is specified, we return the path
618 * *below* the controllers, without any prefix. */
620 if (!path && !suffix)
628 t = strjoin(path, "/", suffix);
632 *fs = path_simplify(t, false);
636 if (!cg_controller_is_valid(controller))
639 r = cg_all_unified();
643 r = join_path_unified(path, suffix, fs);
645 r = join_path_legacy(controller, path, suffix, fs);
649 path_simplify(*fs, false);
653 static int controller_is_accessible(const char *controller) {
658 /* Checks whether a specific controller is accessible,
659 * i.e. its hierarchy mounted. In the unified hierarchy all
660 * controllers are considered accessible, except for the named
663 if (!cg_controller_is_valid(controller))
666 r = cg_all_unified();
670 /* We don't support named hierarchies if we are using
671 * the unified hierarchy. */
673 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
676 if (startswith(controller, "name="))
682 dn = controller_to_dirname(controller);
683 cc = strjoina("/sys/fs/cgroup/", dn);
685 if (laccess(cc, F_OK) < 0)
692 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
698 /* Check if the specified controller is actually accessible */
699 r = controller_is_accessible(controller);
703 return cg_get_path(controller, path, suffix, fs);
706 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
711 if (typeflag != FTW_DP)
714 if (ftwbuf->level < 1)
721 int cg_trim(const char *controller, const char *path, bool delete_root) {
722 _cleanup_free_ char *fs = NULL;
727 r = cg_get_path(controller, path, NULL, &fs);
732 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
742 if (rmdir(fs) < 0 && errno != ENOENT)
746 q = cg_hybrid_unified();
749 if (q > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
750 q = cg_trim(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, delete_root);
752 log_warning_errno(q, "Failed to trim compat systemd cgroup %s: %m", path);
758 /* Create a cgroup in the hierarchy of controller.
759 * Returns 0 if the group already existed, 1 on success, negative otherwise.
761 int cg_create(const char *controller, const char *path) {
762 _cleanup_free_ char *fs = NULL;
765 r = cg_get_path_and_check(controller, path, NULL, &fs);
769 r = mkdir_parents(fs, 0755);
773 r = mkdir_errno_wrapper(fs, 0755);
779 r = cg_hybrid_unified();
783 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
784 r = cg_create(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
786 log_warning_errno(r, "Failed to create compat systemd cgroup %s: %m", path);
792 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
797 r = cg_create(controller, path);
801 q = cg_attach(controller, path, pid);
805 /* This does not remove the cgroup on failure */
809 int cg_attach(const char *controller, const char *path, pid_t pid) {
810 _cleanup_free_ char *fs = NULL;
811 char c[DECIMAL_STR_MAX(pid_t) + 2];
817 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
822 pid = getpid_cached();
824 xsprintf(c, PID_FMT "\n", pid);
826 r = write_string_file(fs, c, 0);
830 r = cg_hybrid_unified();
834 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
835 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, pid);
837 log_warning_errno(r, "Failed to attach "PID_FMT" to compat systemd cgroup %s: %m", pid, path);
843 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
850 r = cg_attach(controller, path, pid);
852 char prefix[strlen(path) + 1];
854 /* This didn't work? Then let's try all prefixes of
857 PATH_FOREACH_PREFIX(prefix, path) {
860 q = cg_attach(controller, prefix, pid);
869 #if 0 /// UNNEEDED by elogind
871 const char *controller,
881 /* cgroupsv1, aka legacy/non-unified */
882 static const struct Attribute legacy_attributes[] = {
883 { "cgroup.procs", true },
885 { "cgroup.clone_children", false },
889 /* cgroupsv2, aka unified */
890 static const struct Attribute unified_attributes[] = {
891 { "cgroup.procs", true },
892 { "cgroup.subtree_control", true },
893 { "cgroup.threads", false },
897 static const struct Attribute* const attributes[] = {
898 [false] = legacy_attributes,
899 [true] = unified_attributes,
902 _cleanup_free_ char *fs = NULL;
903 const struct Attribute *i;
908 if (uid == UID_INVALID && gid == GID_INVALID)
911 unified = cg_unified_controller(controller);
915 /* Configure access to the cgroup itself */
916 r = cg_get_path(controller, path, NULL, &fs);
920 r = chmod_and_chown(fs, 0755, uid, gid);
924 /* Configure access to the cgroup's attributes */
925 for (i = attributes[unified]; i->name; i++) {
928 r = cg_get_path(controller, path, i->name, &fs);
932 r = chmod_and_chown(fs, 0644, uid, gid);
937 log_debug_errno(r, "Failed to set access on cgroup %s, ignoring: %m", fs);
941 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
942 r = cg_hybrid_unified();
946 /* Always propagate access mode from unified to legacy controller */
947 r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, uid, gid);
949 log_debug_errno(r, "Failed to set access on compatibility elogind cgroup %s, ignoring: %m", path);
956 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
957 _cleanup_free_ char *fs = NULL;
962 assert(value || size <= 0);
964 r = cg_get_path(controller, path, NULL, &fs);
968 if (setxattr(fs, name, value, size, flags) < 0)
974 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
975 _cleanup_free_ char *fs = NULL;
982 r = cg_get_path(controller, path, NULL, &fs);
986 n = getxattr(fs, name, value, size);
994 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
995 _cleanup_fclose_ FILE *f = NULL;
997 #if 0 /// At elogind we do not want that (false alarm) "maybe uninitialized" warning
998 const char *fs, *controller_str;
1000 const char *fs, *controller_str = NULL;
1009 if (!cg_controller_is_valid(controller))
1012 controller = SYSTEMD_CGROUP_CONTROLLER;
1014 unified = cg_unified_controller(controller);
1018 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
1019 controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
1021 controller_str = controller;
1023 cs = strlen(controller_str);
1026 fs = procfs_file_alloca(pid, "cgroup");
1027 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
1028 pid, fs, controller);
1029 f = fopen(fs, "re");
1031 return errno == ENOENT ? -ESRCH : -errno;
1033 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1035 FOREACH_LINE(line, f, return -errno) {
1041 e = startswith(line, "0:");
1051 const char *word, *state;
1054 l = strchr(line, ':');
1064 FOREACH_WORD_SEPARATOR(word, k, l, ",", state)
1065 if (k == cs && memcmp(word, controller_str, cs) == 0) {
1073 log_debug_elogind("Found %s:%s", line, e+1);
1078 /* Truncate suffix indicating the process is a zombie */
1079 e = endswith(p, " (deleted)");
1090 #if 0 /// UNNEEDED by elogind
1091 int cg_install_release_agent(const char *controller, const char *agent) {
1092 _cleanup_free_ char *fs = NULL, *contents = NULL;
1098 r = cg_unified_controller(controller);
1101 if (r > 0) /* doesn't apply to unified hierarchy */
1104 r = cg_get_path(controller, NULL, "release_agent", &fs);
1108 r = read_one_line_file(fs, &contents);
1112 sc = strstrip(contents);
1114 r = write_string_file(fs, agent, 0);
1117 } else if (!path_equal(sc, agent))
1121 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1125 contents = mfree(contents);
1126 r = read_one_line_file(fs, &contents);
1130 sc = strstrip(contents);
1131 if (streq(sc, "0")) {
1132 r = write_string_file(fs, "1", 0);
1139 if (!streq(sc, "1"))
1145 int cg_uninstall_release_agent(const char *controller) {
1146 _cleanup_free_ char *fs = NULL;
1149 r = cg_unified_controller(controller);
1152 if (r > 0) /* Doesn't apply to unified hierarchy */
1155 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1159 r = write_string_file(fs, "0", 0);
1165 r = cg_get_path(controller, NULL, "release_agent", &fs);
1169 r = write_string_file(fs, "", 0);
1177 int cg_is_empty(const char *controller, const char *path) {
1178 _cleanup_fclose_ FILE *f = NULL;
1184 r = cg_enumerate_processes(controller, path, &f);
1190 r = cg_read_pid(f, &pid);
1197 int cg_is_empty_recursive(const char *controller, const char *path) {
1202 /* The root cgroup is always populated */
1203 if (controller && empty_or_root(path))
1206 r = cg_unified_controller(controller);
1210 _cleanup_free_ char *t = NULL;
1212 /* On the unified hierarchy we can check empty state
1213 * via the "populated" attribute of "cgroup.events". */
1215 r = cg_read_event(controller, path, "populated", &t);
1219 return streq(t, "0");
1221 _cleanup_closedir_ DIR *d = NULL;
1224 r = cg_is_empty(controller, path);
1228 r = cg_enumerate_subgroups(controller, path, &d);
1234 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1235 _cleanup_free_ char *p = NULL;
1237 p = strjoin(path, "/", fn);
1242 r = cg_is_empty_recursive(controller, p);
1253 int cg_split_spec(const char *spec, char **controller, char **path) {
1254 char *t = NULL, *u = NULL;
1260 if (!path_is_normalized(spec))
1268 *path = path_simplify(t, false);
1277 e = strchr(spec, ':');
1279 if (!cg_controller_is_valid(spec))
1296 t = strndup(spec, e-spec);
1299 if (!cg_controller_is_valid(t)) {
1313 if (!path_is_normalized(u) ||
1314 !path_is_absolute(u)) {
1320 path_simplify(u, false);
1336 int cg_mangle_path(const char *path, char **result) {
1337 _cleanup_free_ char *c = NULL, *p = NULL;
1344 /* First, check if it already is a filesystem path */
1345 if (path_startswith(path, "/sys/fs/cgroup")) {
1351 *result = path_simplify(t, false);
1355 /* Otherwise, treat it as cg spec */
1356 r = cg_split_spec(path, &c, &p);
1360 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1363 int cg_get_root_path(char **path) {
1369 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1373 #if 0 /// elogind does not support systemd scopes and slices
1374 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1376 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1378 e = endswith(p, "/system"); /* even more legacy */
1380 e = endswith(p, "/elogind");
1389 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1390 _cleanup_free_ char *rt = NULL;
1398 /* If the root was specified let's use that, otherwise
1399 * let's determine it from PID 1 */
1401 r = cg_get_root_path(&rt);
1406 log_debug_elogind("Determined root path: \"%s\"", root);
1409 p = path_startswith(cgroup, root);
1410 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1411 if (p && p > cgroup)
1413 if (p && p[0] && (p > cgroup))
1422 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1423 _cleanup_free_ char *raw = NULL;
1430 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1434 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1435 raw, pid, root ? root : "NULL");
1436 r = cg_shift_path(raw, root, &c);
1441 *cgroup = TAKE_PTR(raw);
1451 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1456 int cg_path_decode_unit(const char *cgroup, char **unit) {
1463 #if 0 /// elogind has a different naming: <controller>:/<session id>. So prefix is always len < 3
1464 n = strcspn(cgroup, "/");
1468 n = strspn(cgroup, "/") + 1;
1471 c = strndupa(cgroup, n);
1474 #if 0 /// elogind session ids are never valid unit names.
1475 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1487 static bool valid_slice_name(const char *p, size_t n) {
1492 if (n < STRLEN("x.slice"))
1495 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1501 c = cg_unescape(buf);
1503 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1509 static const char *skip_slices(const char *p) {
1512 /* Skips over all slice assignments */
1517 p += strspn(p, "/");
1519 n = strcspn(p, "/");
1520 if (!valid_slice_name(p, n))
1527 int cg_path_get_unit(const char *path, char **ret) {
1535 e = skip_slices(path);
1537 r = cg_path_decode_unit(e, &unit);
1541 /* We skipped over the slices, don't accept any now */
1542 if (endswith(unit, ".slice")) {
1551 int cg_pid_get_unit(pid_t pid, char **unit) {
1552 _cleanup_free_ char *cgroup = NULL;
1557 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1561 return cg_path_get_unit(cgroup, unit);
1564 #if 0 /// UNNEEDED by elogind
1566 * Skip session-*.scope, but require it to be there.
1568 static const char *skip_session(const char *p) {
1574 p += strspn(p, "/");
1576 n = strcspn(p, "/");
1577 if (n < STRLEN("session-x.scope"))
1580 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1581 char buf[n - 8 - 6 + 1];
1583 memcpy(buf, p + 8, n - 8 - 6);
1586 /* Note that session scopes never need unescaping,
1587 * since they cannot conflict with the kernel's own
1588 * names, hence we don't need to call cg_unescape()
1591 if (!session_id_valid(buf))
1595 p += strspn(p, "/");
1603 * Skip user@*.service, but require it to be there.
1605 static const char *skip_user_manager(const char *p) {
1611 p += strspn(p, "/");
1613 n = strcspn(p, "/");
1614 if (n < STRLEN("user@x.service"))
1617 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1618 char buf[n - 5 - 8 + 1];
1620 memcpy(buf, p + 5, n - 5 - 8);
1623 /* Note that user manager services never need unescaping,
1624 * since they cannot conflict with the kernel's own
1625 * names, hence we don't need to call cg_unescape()
1628 if (parse_uid(buf, NULL) < 0)
1632 p += strspn(p, "/");
1640 static const char *skip_user_prefix(const char *path) {
1645 /* Skip slices, if there are any */
1646 e = skip_slices(path);
1648 /* Skip the user manager, if it's in the path now... */
1649 t = skip_user_manager(e);
1653 /* Alternatively skip the user session if it is in the path... */
1654 return skip_session(e);
1657 int cg_path_get_user_unit(const char *path, char **ret) {
1663 t = skip_user_prefix(path);
1667 /* And from here on it looks pretty much the same as for a
1668 * system unit, hence let's use the same parser from here
1670 return cg_path_get_unit(t, ret);
1673 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1674 _cleanup_free_ char *cgroup = NULL;
1679 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1683 return cg_path_get_user_unit(cgroup, unit);
1686 int cg_path_get_machine_name(const char *path, char **machine) {
1687 _cleanup_free_ char *u = NULL;
1691 r = cg_path_get_unit(path, &u);
1695 sl = strjoina("/run/systemd/machines/unit:", u);
1696 return readlink_malloc(sl, machine);
1699 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1700 _cleanup_free_ char *cgroup = NULL;
1705 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1709 return cg_path_get_machine_name(cgroup, machine);
1713 int cg_path_get_session(const char *path, char **session) {
1714 #if 0 /// UNNEEDED by elogind
1715 _cleanup_free_ char *unit = NULL;
1721 r = cg_path_get_unit(path, &unit);
1725 start = startswith(unit, "session-");
1728 end = endswith(start, ".scope");
1733 if (!session_id_valid(start))
1736 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1737 wrinkle is that SESSION might be escaped. */
1738 const char *e, *n, *start;
1741 log_debug_elogind("path is \"%s\"", path);
1742 assert(path[0] == '/');
1745 n = strchrnul(e, '/');
1749 start = strndupa(e, n - e);
1750 start = cg_unescape(start);
1759 log_debug_elogind("found session: \"%s\"", start);
1770 int cg_pid_get_session(pid_t pid, char **session) {
1771 _cleanup_free_ char *cgroup = NULL;
1774 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1778 return cg_path_get_session(cgroup, session);
1781 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1782 #if 0 /// elogind needs one more value
1783 _cleanup_free_ char *slice = NULL;
1786 _cleanup_free_ char *slice = NULL, *p = NULL, *s = NULL;
1792 r = cg_path_get_slice(path, &slice);
1796 #if 0 /// elogind does not support systemd slices
1797 start = startswith(slice, "user-");
1800 end = endswith(start, ".slice");
1805 if (parse_uid(start, uid) < 0)
1808 p = strappend("/run/systemd/sessions/", slice);
1810 r = parse_env_file(p, NEWLINE, "UID", &s, NULL);
1818 if (parse_uid(s, uid) < 0)
1825 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1826 _cleanup_free_ char *cgroup = NULL;
1829 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1833 return cg_path_get_owner_uid(cgroup, uid);
1836 int cg_path_get_slice(const char *p, char **slice) {
1837 const char *e = NULL;
1842 #if 0 /// elogind does not support systemd slices
1843 /* Finds the right-most slice unit from the beginning, but
1844 * stops before we come to the first non-slice unit. */
1849 p += strspn(p, "/");
1851 n = strcspn(p, "/");
1852 if (!valid_slice_name(p, n)) {
1857 s = strdup(SPECIAL_ROOT_SLICE);
1865 return cg_path_decode_unit(e, slice);
1872 /* In elogind, what is reported here, is the location of
1873 * the session. This is derived from /proc/<self|PID>/cgroup.
1874 * In there we look at the controller, which will look something
1875 * like "1:name=openrc:/3".
1876 * The last part gets extracted (and is now p), which is "/3" in
1877 * this case. The three is the session id, and that can be mapped.
1879 e = startswith(p, "/");
1890 int cg_pid_get_slice(pid_t pid, char **slice) {
1891 _cleanup_free_ char *cgroup = NULL;
1896 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1897 log_debug_elogind("Found cgroup %s for pid %u (result %d)",
1902 return cg_path_get_slice(cgroup, slice);
1905 int cg_path_get_user_slice(const char *p, char **slice) {
1906 #if 0 /// UNNEEDED by elogind
1912 #if 0 /// nothing to skip in elogind
1913 t = skip_user_prefix(p);
1918 #if 0 /// UNNEEDED by elogind
1919 /* And now it looks pretty much the same as for a system
1920 * slice, so let's just use the same parser from here on. */
1921 return cg_path_get_slice(t, slice);
1923 /* In elogind there is nothing to skip, we can use the path
1924 * directly. Generally speaking this is always a session id
1925 * to user mapping. */
1926 return cg_path_get_slice(p, slice);
1930 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1931 _cleanup_free_ char *cgroup = NULL;
1936 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1940 return cg_path_get_user_slice(cgroup, slice);
1943 char *cg_escape(const char *p) {
1944 bool need_prefix = false;
1946 /* This implements very minimal escaping for names to be used
1947 * as file names in the cgroup tree: any name which might
1948 * conflict with a kernel name or is prefixed with '_' is
1949 * prefixed with a '_'. That way, when reading cgroup names it
1950 * is sufficient to remove a single prefixing underscore if
1953 /* The return value of this function (unlike cg_unescape())
1956 if (IN_SET(p[0], 0, '_', '.') ||
1957 streq(p, "notify_on_release") ||
1958 streq(p, "release_agent") ||
1959 streq(p, "tasks") ||
1960 startswith(p, "cgroup."))
1965 dot = strrchr(p, '.');
1970 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1973 n = cgroup_controller_to_string(c);
1978 if (memcmp(p, n, l) != 0)
1988 return strappend("_", p);
1993 char *cg_unescape(const char *p) {
1996 /* The return value of this function (unlike cg_escape())
1997 * doesn't need free()! */
2005 #define CONTROLLER_VALID \
2009 bool cg_controller_is_valid(const char *p) {
2015 if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
2018 s = startswith(p, "name=");
2022 if (IN_SET(*p, 0, '_'))
2025 for (t = p; *t; t++)
2026 if (!strchr(CONTROLLER_VALID, *t))
2029 if (t - p > FILENAME_MAX)
2035 #if 0 /// UNNEEDED by elogind
2036 int cg_slice_to_path(const char *unit, char **ret) {
2037 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
2044 if (streq(unit, SPECIAL_ROOT_SLICE)) {
2054 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
2057 if (!endswith(unit, ".slice"))
2060 r = unit_name_to_prefix(unit, &p);
2064 dash = strchr(p, '-');
2066 /* Don't allow initial dashes */
2071 _cleanup_free_ char *escaped = NULL;
2072 char n[dash - p + sizeof(".slice")];
2074 #if HAS_FEATURE_MEMORY_SANITIZER
2075 /* msan doesn't instrument stpncpy, so it thinks
2076 * n is later used unitialized:
2077 * https://github.com/google/sanitizers/issues/926
2082 /* Don't allow trailing or double dashes */
2083 if (IN_SET(dash[1], 0, '-'))
2086 strcpy(stpncpy(n, p, dash - p), ".slice");
2087 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
2090 escaped = cg_escape(n);
2094 if (!strextend(&s, escaped, "/", NULL))
2097 dash = strchr(dash+1, '-');
2100 e = cg_escape(unit);
2104 if (!strextend(&s, e, NULL))
2113 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
2114 _cleanup_free_ char *p = NULL;
2117 r = cg_get_path(controller, path, attribute, &p);
2121 return write_string_file(p, value, 0);
2124 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
2125 _cleanup_free_ char *p = NULL;
2128 r = cg_get_path(controller, path, attribute, &p);
2132 return read_one_line_file(p, ret);
2135 #if 0 /// UNNEEDED by elogind
2136 int cg_get_keyed_attribute(
2137 const char *controller,
2139 const char *attribute,
2141 char **ret_values) {
2143 _cleanup_free_ char *filename = NULL, *contents = NULL;
2145 size_t n, i, n_done = 0;
2149 /* Reads one or more fields of a cgroupsv2 keyed attribute file. The 'keys' parameter should be an strv with
2150 * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
2151 * entries as 'keys'. On success each entry will be set to the value of the matching key.
2153 * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
2155 r = cg_get_path(controller, path, attribute, &filename);
2159 r = read_full_file(filename, &contents, NULL);
2163 n = strv_length(keys);
2164 if (n == 0) /* No keys to retrieve? That's easy, we are done then */
2167 /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
2168 v = newa0(char*, n);
2170 for (p = contents; *p;) {
2171 const char *w = NULL;
2173 for (i = 0; i < n; i++)
2175 w = first_word(p, keys[i]);
2183 l = strcspn(w, NEWLINE);
2184 v[i] = strndup(w, l);
2196 p += strcspn(p, NEWLINE);
2198 p += strspn(p, NEWLINE);
2204 for (i = 0; i < n; i++)
2210 memcpy(ret_values, v, sizeof(char*) * n);
2215 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2220 /* This one will create a cgroup in our private tree, but also
2221 * duplicate it in the trees specified in mask, and remove it
2224 * Returns 0 if the group already existed in the systemd hierarchy,
2225 * 1 on success, negative otherwise.
2228 /* First create the cgroup in our own hierarchy. */
2229 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2234 /* If we are in the unified hierarchy, we are done now */
2235 r = cg_all_unified();
2241 /* Otherwise, do the same in the other hierarchies */
2242 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2243 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2246 n = cgroup_controller_to_string(c);
2249 (void) cg_create(n, path);
2250 else if (supported & bit)
2251 (void) cg_trim(n, path, true);
2257 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2261 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2265 r = cg_all_unified();
2271 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2272 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2273 const char *p = NULL;
2275 if (!(supported & bit))
2279 p = path_callback(bit, userdata);
2284 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2290 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2295 SET_FOREACH(pidp, pids, i) {
2296 pid_t pid = PTR_TO_PID(pidp);
2299 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2300 if (q < 0 && r >= 0)
2307 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2311 if (!path_equal(from, to)) {
2312 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2317 q = cg_all_unified();
2323 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2324 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2325 const char *p = NULL;
2327 if (!(supported & bit))
2331 p = to_callback(bit, userdata);
2336 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2342 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2346 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2350 q = cg_all_unified();
2356 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2357 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2359 if (!(supported & bit))
2362 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2369 int cg_mask_to_string(CGroupMask mask, char **ret) {
2370 _cleanup_free_ char *s = NULL;
2371 size_t n = 0, allocated = 0;
2382 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2386 if (!(mask & CGROUP_CONTROLLER_TO_MASK(c)))
2389 k = cgroup_controller_to_string(c);
2392 if (!GREEDY_REALLOC(s, allocated, n + space + l + 1))
2397 memcpy(s + n + space, k, l);
2411 int cg_mask_from_string(const char *value, CGroupMask *mask) {
2416 _cleanup_free_ char *n = NULL;
2420 r = extract_first_word(&value, &n, NULL, 0);
2426 v = cgroup_controller_from_string(n);
2430 *mask |= CGROUP_CONTROLLER_TO_MASK(v);
2435 int cg_mask_supported(CGroupMask *ret) {
2436 CGroupMask mask = 0;
2439 /* Determines the mask of supported cgroup controllers. Only
2440 * includes controllers we can make sense of and that are
2441 * actually accessible. */
2443 r = cg_all_unified();
2447 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2449 /* In the unified hierarchy we can read the supported
2450 * and accessible controllers from a the top-level
2451 * cgroup attribute */
2453 r = cg_get_root_path(&root);
2457 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2461 r = read_one_line_file(path, &controllers);
2465 r = cg_mask_from_string(controllers, &mask);
2469 /* Currently, we support the cpu, memory, io and pids
2470 * controller in the unified hierarchy, mask
2471 * everything else off. */
2472 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2477 /* In the legacy hierarchy, we check whether which
2478 * hierarchies are mounted. */
2480 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2483 n = cgroup_controller_to_string(c);
2484 if (controller_is_accessible(n) >= 0)
2485 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2493 #if 0 /// UNNEEDED by elogind
2494 int cg_kernel_controllers(Set **ret) {
2495 _cleanup_set_free_free_ Set *controllers = NULL;
2496 _cleanup_fclose_ FILE *f = NULL;
2501 /* Determines the full list of kernel-known controllers. Might
2502 * include controllers we don't actually support, arbitrary
2503 * named hierarchies and controllers that aren't currently
2504 * accessible (because not mounted). */
2506 controllers = set_new(&string_hash_ops);
2510 f = fopen("/proc/cgroups", "re");
2512 if (errno == ENOENT) {
2520 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
2522 /* Ignore the header line */
2523 (void) read_line(f, (size_t) -1, NULL);
2530 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2535 if (ferror(f) && errno > 0)
2546 if (!cg_controller_is_valid(controller)) {
2551 r = set_consume(controllers, controller);
2556 *ret = TAKE_PTR(controllers);
2562 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2564 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup v2 on /sys/fs/cgroup/systemd. This
2565 * unfortunately broke other tools (such as docker) which expected the v1 "name=systemd" hierarchy on
2566 * /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mountnbs v2 on /sys/fs/cgroup/unified and maintains
2567 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility with other tools.
2569 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep cgroup v2
2570 * process management but disable the compat dual layout, we return %true on
2571 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and %false on cg_hybrid_unified().
2573 static thread_local bool unified_systemd_v232;
2575 static int cg_unified_update(void) {
2579 /* Checks if we support the unified hierarchy. Returns an
2580 * error when the cgroup hierarchies aren't mounted yet or we
2581 * have any other trouble determining if the unified hierarchy
2584 if (unified_cache >= CGROUP_UNIFIED_NONE)
2587 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2588 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/\") failed: %m");
2590 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2591 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
2592 unified_cache = CGROUP_UNIFIED_ALL;
2593 #if 0 /// The handling of cgroups is a bit different with elogind
2594 } else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2595 log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2597 } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)
2598 || F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2600 if (statfs("/sys/fs/cgroup/unified/", &fs) == 0 &&
2601 F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2602 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2603 unified_systemd_v232 = false;
2605 #if 0 /// There is no sub-grouping within elogind
2606 if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2607 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2609 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2610 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2611 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2612 unified_systemd_v232 = true;
2613 } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)) {
2614 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2615 unified_cache = CGROUP_UNIFIED_NONE;
2617 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2618 (unsigned long long) fs.f_type);
2619 unified_cache = CGROUP_UNIFIED_NONE;
2622 unified_cache = CGROUP_UNIFIED_NONE;
2626 log_debug("Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2627 (unsigned long long) fs.f_type);
2634 int cg_unified_controller(const char *controller) {
2637 r = cg_unified_update();
2641 if (unified_cache == CGROUP_UNIFIED_NONE)
2644 if (unified_cache >= CGROUP_UNIFIED_ALL)
2647 #if 0 /// only if elogind is the controller we can use cgroups2 in hybrid mode
2648 return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER);
2650 return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER_HYBRID);
2654 int cg_all_unified(void) {
2657 r = cg_unified_update();
2661 return unified_cache >= CGROUP_UNIFIED_ALL;
2664 int cg_hybrid_unified(void) {
2667 r = cg_unified_update();
2671 return unified_cache == CGROUP_UNIFIED_SYSTEMD && !unified_systemd_v232;
2674 int cg_unified_flush(void) {
2675 unified_cache = CGROUP_UNIFIED_UNKNOWN;
2677 return cg_unified_update();
2680 #if 0 /// UNNEEDED by elogind
2681 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2682 _cleanup_fclose_ FILE *f = NULL;
2683 _cleanup_free_ char *fs = NULL;
2692 r = cg_all_unified();
2695 if (r == 0) /* on the legacy hiearchy there's no joining of controllers defined */
2698 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2702 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2703 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2706 if (!(supported & bit))
2709 n = cgroup_controller_to_string(c);
2711 char s[1 + strlen(n) + 1];
2713 s[0] = mask & bit ? '+' : '-';
2717 f = fopen(fs, "we");
2719 log_debug_errno(errno, "Failed to open cgroup.subtree_control file of %s: %m", p);
2724 r = write_string_stream(f, s, 0);
2726 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2736 bool cg_is_unified_wanted(void) {
2737 static thread_local int wanted = -1;
2738 #if 0 /// UNNEEDED by elogind
2742 const bool is_default = DEFAULT_HIERARCHY == CGROUP_UNIFIED_ALL;
2744 /* If we have a cached value, return that. */
2748 /* If the hierarchy is already mounted, then follow whatever
2749 * was chosen for it. */
2750 if (cg_unified_flush() >= 0)
2751 return (wanted = unified_cache >= CGROUP_UNIFIED_ALL);
2753 #if 0 /// elogind is not init and has no business with kernel command line
2754 /* Otherwise, let's see what the kernel command line has to say.
2755 * Since checking is expensive, cache a non-error result. */
2756 r = proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b);
2758 return (wanted = r > 0 ? b : is_default);
2764 bool cg_is_legacy_wanted(void) {
2765 static thread_local int wanted = -1;
2767 /* If we have a cached value, return that. */
2771 /* Check if we have cgroups2 already mounted. */
2772 if (cg_unified_flush() >= 0 &&
2773 unified_cache == CGROUP_UNIFIED_ALL)
2774 return (wanted = false);
2776 /* Otherwise, assume that at least partial legacy is wanted,
2777 * since cgroups2 should already be mounted at this point. */
2778 return (wanted = true);
2781 bool cg_is_hybrid_wanted(void) {
2782 static thread_local int wanted = -1;
2783 #if 0 /// UNNEEDED by elogind
2787 const bool is_default = DEFAULT_HIERARCHY >= CGROUP_UNIFIED_SYSTEMD;
2788 /* We default to true if the default is "hybrid", obviously,
2789 * but also when the default is "unified", because if we get
2790 * called, it means that unified hierarchy was not mounted. */
2792 /* If we have a cached value, return that. */
2796 /* If the hierarchy is already mounted, then follow whatever
2797 * was chosen for it. */
2798 if (cg_unified_flush() >= 0 &&
2799 unified_cache == CGROUP_UNIFIED_ALL)
2800 return (wanted = false);
2802 #if 0 /// elogind is not init and has no business with kernel command line
2803 /* Otherwise, let's see what the kernel command line has to say.
2804 * Since checking is expensive, cache a non-error result. */
2805 r = proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b);
2807 /* The meaning of the kernel option is reversed wrt. to the return value
2808 * of this function, hence the negation. */
2809 return (wanted = r > 0 ? !b : is_default);
2815 #if 0 /// UNNEEDED by elogind
2816 int cg_weight_parse(const char *s, uint64_t *ret) {
2821 *ret = CGROUP_WEIGHT_INVALID;
2825 r = safe_atou64(s, &u);
2829 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2836 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2837 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2838 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2839 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2840 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2843 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2844 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2845 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2846 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2847 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2850 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2852 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2857 *ret = CGROUP_CPU_SHARES_INVALID;
2861 r = safe_atou64(s, &u);
2865 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2872 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2877 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2881 r = safe_atou64(s, &u);
2885 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2893 bool is_cgroup_fs(const struct statfs *s) {
2894 return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2895 is_fs_type(s, CGROUP2_SUPER_MAGIC);
2898 bool fd_is_cgroup_fs(int fd) {
2901 if (fstatfs(fd, &s) < 0)
2904 return is_cgroup_fs(&s);
2907 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2908 [CGROUP_CONTROLLER_CPU] = "cpu",
2909 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2910 [CGROUP_CONTROLLER_IO] = "io",
2911 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2912 [CGROUP_CONTROLLER_MEMORY] = "memory",
2913 [CGROUP_CONTROLLER_DEVICES] = "devices",
2914 [CGROUP_CONTROLLER_PIDS] = "pids",
2917 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);