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)
213 r = cg_hybrid_unified();
219 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
220 r = cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
222 log_warning_errno(r, "Failed to remove compat systemd cgroup %s: %m", path);
229 const char *controller,
234 cg_kill_log_func_t log_kill,
237 _cleanup_set_free_ Set *allocated_set = NULL;
244 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
245 * SIGCONT on SIGKILL. */
246 if (IN_SET(sig, SIGCONT, SIGKILL))
247 flags &= ~CGROUP_SIGCONT;
249 /* This goes through the tasks list and kills them all. This
250 * is repeated until no further processes are added to the
251 * tasks list, to properly handle forking processes */
254 s = allocated_set = set_new(NULL);
262 _cleanup_fclose_ FILE *f = NULL;
266 r = cg_enumerate_processes(controller, path, &f);
268 if (ret >= 0 && r != -ENOENT)
274 while ((r = cg_read_pid(f, &pid)) > 0) {
276 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
279 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
283 log_kill(pid, sig, userdata);
285 /* If we haven't killed this process yet, kill
287 if (kill(pid, sig) < 0) {
288 if (ret >= 0 && errno != ESRCH)
291 if (flags & CGROUP_SIGCONT)
292 (void) kill(pid, SIGCONT);
300 r = set_put(s, PID_TO_PTR(pid));
316 /* To avoid racing against processes which fork
317 * quicker than we can kill them we repeat this until
318 * no new pids need to be killed. */
325 int cg_kill_recursive(
326 const char *controller,
331 cg_kill_log_func_t log_kill,
334 _cleanup_set_free_ Set *allocated_set = NULL;
335 _cleanup_closedir_ DIR *d = NULL;
343 s = allocated_set = set_new(NULL);
348 ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
350 r = cg_enumerate_subgroups(controller, path, &d);
352 if (ret >= 0 && r != -ENOENT)
358 while ((r = cg_read_subgroup(d, &fn)) > 0) {
359 _cleanup_free_ char *p = NULL;
361 p = strjoin(path, "/", fn);
366 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
367 if (r != 0 && ret >= 0)
370 if (ret >= 0 && r < 0)
373 if (flags & CGROUP_REMOVE) {
374 r = cg_rmdir(controller, path);
375 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
390 _cleanup_set_free_ Set *s = NULL;
405 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
406 cfrom, pfrom, cto, pto,
407 (flags & CGROUP_IGNORE_SELF)
408 ? "ignoring self" : "watching self");
410 _cleanup_fclose_ FILE *f = NULL;
414 r = cg_enumerate_processes(cfrom, pfrom, &f);
416 if (ret >= 0 && r != -ENOENT)
422 while ((r = cg_read_pid(f, &pid)) > 0) {
424 /* This might do weird stuff if we aren't a
425 * single-threaded program. However, we
426 * luckily know we are not */
427 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
430 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
433 /* Ignore kernel threads. Since they can only
434 * exist in the root cgroup, we only check for
437 (isempty(pfrom) || path_equal(pfrom, "/")) &&
438 is_kernel_thread(pid) > 0)
441 r = cg_attach(cto, pto, pid);
443 if (ret >= 0 && r != -ESRCH)
450 r = set_put(s, PID_TO_PTR(pid));
470 int cg_migrate_recursive(
477 _cleanup_closedir_ DIR *d = NULL;
486 ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
488 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
490 if (ret >= 0 && r != -ENOENT)
496 while ((r = cg_read_subgroup(d, &fn)) > 0) {
497 _cleanup_free_ char *p = NULL;
499 p = strjoin(pfrom, "/", fn);
504 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
505 if (r != 0 && ret >= 0)
509 if (r < 0 && ret >= 0)
512 if (flags & CGROUP_REMOVE) {
513 r = cg_rmdir(cfrom, pfrom);
514 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
521 int cg_migrate_recursive_fallback(
535 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
537 char prefix[strlen(pto) + 1];
539 /* This didn't work? Then let's try all prefixes of the destination */
541 PATH_FOREACH_PREFIX(prefix, pto) {
544 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
553 static const char *controller_to_dirname(const char *controller) {
558 /* Converts a controller name to the directory name below
559 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
560 * just cuts off the name= prefixed used for named
561 * hierarchies, if it is specified. */
563 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
564 if (cg_hybrid_unified() > 0)
565 controller = SYSTEMD_CGROUP_CONTROLLER_HYBRID;
567 controller = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
570 e = startswith(controller, "name=");
577 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
584 dn = controller_to_dirname(controller);
586 if (isempty(path) && isempty(suffix))
587 t = strappend("/sys/fs/cgroup/", dn);
588 else if (isempty(path))
589 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix);
590 else if (isempty(suffix))
591 t = strjoin("/sys/fs/cgroup/", dn, "/", path);
593 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix);
601 static int join_path_unified(const char *path, const char *suffix, char **fs) {
606 if (isempty(path) && isempty(suffix))
607 t = strdup("/sys/fs/cgroup");
608 else if (isempty(path))
609 t = strappend("/sys/fs/cgroup/", suffix);
610 else if (isempty(suffix))
611 t = strappend("/sys/fs/cgroup/", path);
613 t = strjoin("/sys/fs/cgroup/", path, "/", suffix);
621 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
629 /* If no controller is specified, we return the path
630 * *below* the controllers, without any prefix. */
632 if (!path && !suffix)
640 t = strjoin(path, "/", suffix);
644 *fs = path_kill_slashes(t);
648 if (!cg_controller_is_valid(controller))
651 r = cg_all_unified();
655 r = join_path_unified(path, suffix, fs);
657 r = join_path_legacy(controller, path, suffix, fs);
661 path_kill_slashes(*fs);
665 static int controller_is_accessible(const char *controller) {
670 /* Checks whether a specific controller is accessible,
671 * i.e. its hierarchy mounted. In the unified hierarchy all
672 * controllers are considered accessible, except for the named
675 if (!cg_controller_is_valid(controller))
678 r = cg_all_unified();
682 /* We don't support named hierarchies if we are using
683 * the unified hierarchy. */
685 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
688 if (startswith(controller, "name="))
694 dn = controller_to_dirname(controller);
695 cc = strjoina("/sys/fs/cgroup/", dn);
697 if (laccess(cc, F_OK) < 0)
704 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
710 /* Check if the specified controller is actually accessible */
711 r = controller_is_accessible(controller);
715 return cg_get_path(controller, path, suffix, fs);
718 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
723 if (typeflag != FTW_DP)
726 if (ftwbuf->level < 1)
733 int cg_trim(const char *controller, const char *path, bool delete_root) {
734 _cleanup_free_ char *fs = NULL;
739 r = cg_get_path(controller, path, NULL, &fs);
744 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
754 if (rmdir(fs) < 0 && errno != ENOENT)
758 q = cg_hybrid_unified();
761 if (q > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
762 q = cg_trim(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, delete_root);
764 log_warning_errno(q, "Failed to trim compat systemd cgroup %s: %m", path);
770 int cg_create(const char *controller, const char *path) {
771 _cleanup_free_ char *fs = NULL;
774 r = cg_get_path_and_check(controller, path, NULL, &fs);
778 r = mkdir_parents(fs, 0755);
782 if (mkdir(fs, 0755) < 0) {
790 r = cg_hybrid_unified();
794 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
795 r = cg_create(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
797 log_warning_errno(r, "Failed to create compat systemd cgroup %s: %m", path);
803 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
808 r = cg_create(controller, path);
812 q = cg_attach(controller, path, pid);
816 /* This does not remove the cgroup on failure */
820 int cg_attach(const char *controller, const char *path, pid_t pid) {
821 _cleanup_free_ char *fs = NULL;
822 char c[DECIMAL_STR_MAX(pid_t) + 2];
828 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
835 xsprintf(c, PID_FMT "\n", pid);
837 r = write_string_file(fs, c, 0);
841 r = cg_hybrid_unified();
845 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
846 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, pid);
848 log_warning_errno(r, "Failed to attach %d to compat systemd cgroup %s: %m", pid, path);
854 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
861 r = cg_attach(controller, path, pid);
863 char prefix[strlen(path) + 1];
865 /* This didn't work? Then let's try all prefixes of
868 PATH_FOREACH_PREFIX(prefix, path) {
871 q = cg_attach(controller, prefix, pid);
880 #if 0 /// UNNEEDED by elogind
881 int cg_set_group_access(
882 const char *controller,
888 _cleanup_free_ char *fs = NULL;
891 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
894 if (mode != MODE_INVALID)
897 r = cg_get_path(controller, path, NULL, &fs);
901 r = chmod_and_chown(fs, mode, uid, gid);
905 r = cg_hybrid_unified();
908 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
909 r = cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, mode, uid, gid);
911 log_warning_errno(r, "Failed to set group access on compat systemd cgroup %s: %m", path);
917 int cg_set_task_access(
918 const char *controller,
924 _cleanup_free_ char *fs = NULL, *procs = NULL;
929 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
932 if (mode != MODE_INVALID)
935 r = cg_get_path(controller, path, "cgroup.procs", &fs);
939 r = chmod_and_chown(fs, mode, uid, gid);
943 r = cg_unified_controller(controller);
947 /* Compatibility, Always keep values for "tasks" in sync with
949 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
950 (void) chmod_and_chown(procs, mode, uid, gid);
953 r = cg_hybrid_unified();
956 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
957 r = cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, mode, uid, gid);
959 log_warning_errno(r, "Failed to set task access on compat systemd cgroup %s: %m", path);
965 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
966 _cleanup_free_ char *fs = NULL;
971 assert(value || size <= 0);
973 r = cg_get_path(controller, path, NULL, &fs);
977 if (setxattr(fs, name, value, size, flags) < 0)
983 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
984 _cleanup_free_ char *fs = NULL;
991 r = cg_get_path(controller, path, NULL, &fs);
995 n = getxattr(fs, name, value, size);
1003 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
1004 _cleanup_fclose_ FILE *f = NULL;
1005 char line[LINE_MAX];
1006 const char *fs, *controller_str;
1014 if (!cg_controller_is_valid(controller))
1017 controller = SYSTEMD_CGROUP_CONTROLLER;
1019 unified = cg_unified_controller(controller);
1023 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
1024 controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
1026 controller_str = controller;
1028 cs = strlen(controller_str);
1031 fs = procfs_file_alloca(pid, "cgroup");
1032 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
1033 pid, fs, controller);
1034 f = fopen(fs, "re");
1036 return errno == ENOENT ? -ESRCH : -errno;
1038 FOREACH_LINE(line, f, return -errno) {
1044 e = startswith(line, "0:");
1054 const char *word, *state;
1057 l = strchr(line, ':');
1067 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
1068 if (k == cs && memcmp(word, controller_str, cs) == 0) {
1078 log_debug_elogind("Found %s:%s", line, e+1);
1090 int cg_install_release_agent(const char *controller, const char *agent) {
1091 _cleanup_free_ char *fs = NULL, *contents = NULL;
1097 r = cg_unified_controller(controller);
1100 if (r > 0) /* doesn't apply to unified hierarchy */
1103 r = cg_get_path(controller, NULL, "release_agent", &fs);
1107 r = read_one_line_file(fs, &contents);
1111 sc = strstrip(contents);
1113 r = write_string_file(fs, agent, 0);
1116 } else if (!path_equal(sc, agent))
1120 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1124 contents = mfree(contents);
1125 r = read_one_line_file(fs, &contents);
1129 sc = strstrip(contents);
1130 if (streq(sc, "0")) {
1131 r = write_string_file(fs, "1", 0);
1138 if (!streq(sc, "1"))
1144 int cg_uninstall_release_agent(const char *controller) {
1145 _cleanup_free_ char *fs = NULL;
1148 r = cg_unified_controller(controller);
1151 if (r > 0) /* Doesn't apply to unified hierarchy */
1154 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1158 r = write_string_file(fs, "0", 0);
1164 r = cg_get_path(controller, NULL, "release_agent", &fs);
1168 r = write_string_file(fs, "", 0);
1175 int cg_is_empty(const char *controller, const char *path) {
1176 _cleanup_fclose_ FILE *f = NULL;
1182 r = cg_enumerate_processes(controller, path, &f);
1188 r = cg_read_pid(f, &pid);
1195 int cg_is_empty_recursive(const char *controller, const char *path) {
1200 /* The root cgroup is always populated */
1201 if (controller && (isempty(path) || path_equal(path, "/")))
1204 r = cg_unified_controller(controller);
1208 _cleanup_free_ char *t = NULL;
1210 /* On the unified hierarchy we can check empty state
1211 * via the "populated" attribute of "cgroup.events". */
1213 r = cg_read_event(controller, path, "populated", &t);
1217 return streq(t, "0");
1219 _cleanup_closedir_ DIR *d = NULL;
1222 r = cg_is_empty(controller, path);
1226 r = cg_enumerate_subgroups(controller, path, &d);
1232 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1233 _cleanup_free_ char *p = NULL;
1235 p = strjoin(path, "/", fn);
1240 r = cg_is_empty_recursive(controller, p);
1251 int cg_split_spec(const char *spec, char **controller, char **path) {
1252 char *t = NULL, *u = NULL;
1258 if (!path_is_safe(spec))
1266 *path = path_kill_slashes(t);
1275 e = strchr(spec, ':');
1277 if (!cg_controller_is_valid(spec))
1294 t = strndup(spec, e-spec);
1297 if (!cg_controller_is_valid(t)) {
1311 if (!path_is_safe(u) ||
1312 !path_is_absolute(u)) {
1318 path_kill_slashes(u);
1334 int cg_mangle_path(const char *path, char **result) {
1335 _cleanup_free_ char *c = NULL, *p = NULL;
1342 /* First, check if it already is a filesystem path */
1343 if (path_startswith(path, "/sys/fs/cgroup")) {
1349 *result = path_kill_slashes(t);
1353 /* Otherwise, treat it as cg spec */
1354 r = cg_split_spec(path, &c, &p);
1358 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1361 int cg_get_root_path(char **path) {
1362 #if 0 /// elogind does not support systemd scopes and slices
1368 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1372 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1374 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1376 e = endswith(p, "/system"); /* even more legacy */
1384 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1388 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1389 _cleanup_free_ char *rt = NULL;
1397 /* If the root was specified let's use that, otherwise
1398 * let's determine it from PID 1 */
1400 r = cg_get_root_path(&rt);
1405 log_debug_elogind("Determined root path: \"%s\"", root);
1408 p = path_startswith(cgroup, root);
1409 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1410 if (p && p > cgroup)
1412 if (p && p[0] && (p > cgroup))
1421 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1422 _cleanup_free_ char *raw = NULL;
1429 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1433 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1434 raw, pid, root ? root : "NULL");
1435 r = cg_shift_path(raw, root, &c);
1451 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1456 #if 0 /// UNNEEDED by elogind
1457 int cg_path_decode_unit(const char *cgroup, char **unit) {
1464 n = strcspn(cgroup, "/");
1468 c = strndupa(cgroup, n);
1471 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1482 static bool valid_slice_name(const char *p, size_t n) {
1487 if (n < strlen("x.slice"))
1490 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1496 c = cg_unescape(buf);
1498 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1504 static const char *skip_slices(const char *p) {
1507 /* Skips over all slice assignments */
1512 p += strspn(p, "/");
1514 n = strcspn(p, "/");
1515 if (!valid_slice_name(p, n))
1522 int cg_path_get_unit(const char *path, char **ret) {
1530 e = skip_slices(path);
1532 r = cg_path_decode_unit(e, &unit);
1536 /* We skipped over the slices, don't accept any now */
1537 if (endswith(unit, ".slice")) {
1546 int cg_pid_get_unit(pid_t pid, char **unit) {
1547 _cleanup_free_ char *cgroup = NULL;
1552 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1556 return cg_path_get_unit(cgroup, unit);
1560 * Skip session-*.scope, but require it to be there.
1562 static const char *skip_session(const char *p) {
1568 p += strspn(p, "/");
1570 n = strcspn(p, "/");
1571 if (n < strlen("session-x.scope"))
1574 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1575 char buf[n - 8 - 6 + 1];
1577 memcpy(buf, p + 8, n - 8 - 6);
1580 /* Note that session scopes never need unescaping,
1581 * since they cannot conflict with the kernel's own
1582 * names, hence we don't need to call cg_unescape()
1585 if (!session_id_valid(buf))
1589 p += strspn(p, "/");
1597 * Skip user@*.service, but require it to be there.
1599 static const char *skip_user_manager(const char *p) {
1605 p += strspn(p, "/");
1607 n = strcspn(p, "/");
1608 if (n < strlen("user@x.service"))
1611 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1612 char buf[n - 5 - 8 + 1];
1614 memcpy(buf, p + 5, n - 5 - 8);
1617 /* Note that user manager services never need unescaping,
1618 * since they cannot conflict with the kernel's own
1619 * names, hence we don't need to call cg_unescape()
1622 if (parse_uid(buf, NULL) < 0)
1626 p += strspn(p, "/");
1634 static const char *skip_user_prefix(const char *path) {
1639 /* Skip slices, if there are any */
1640 e = skip_slices(path);
1642 /* Skip the user manager, if it's in the path now... */
1643 t = skip_user_manager(e);
1647 /* Alternatively skip the user session if it is in the path... */
1648 return skip_session(e);
1651 int cg_path_get_user_unit(const char *path, char **ret) {
1657 t = skip_user_prefix(path);
1661 /* And from here on it looks pretty much the same as for a
1662 * system unit, hence let's use the same parser from here
1664 return cg_path_get_unit(t, ret);
1667 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1668 _cleanup_free_ char *cgroup = NULL;
1673 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1677 return cg_path_get_user_unit(cgroup, unit);
1680 int cg_path_get_machine_name(const char *path, char **machine) {
1681 _cleanup_free_ char *u = NULL;
1685 r = cg_path_get_unit(path, &u);
1689 sl = strjoina("/run/systemd/machines/unit:", u);
1690 return readlink_malloc(sl, machine);
1693 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1694 _cleanup_free_ char *cgroup = NULL;
1699 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1703 return cg_path_get_machine_name(cgroup, machine);
1707 int cg_path_get_session(const char *path, char **session) {
1708 #if 0 /// UNNEEDED by elogind
1709 _cleanup_free_ char *unit = NULL;
1715 r = cg_path_get_unit(path, &unit);
1719 start = startswith(unit, "session-");
1722 end = endswith(start, ".scope");
1727 if (!session_id_valid(start))
1730 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1731 wrinkle is that SESSION might be escaped. */
1732 const char *e, *n, *start;
1735 log_debug_elogind("path is \"%s\"", path);
1736 assert(path[0] == '/');
1739 n = strchrnul(e, '/');
1743 start = strndupa(e, n - e);
1744 start = cg_unescape(start);
1753 log_debug_elogind("found session: \"%s\"", start);
1764 int cg_pid_get_session(pid_t pid, char **session) {
1765 _cleanup_free_ char *cgroup = NULL;
1768 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1772 return cg_path_get_session(cgroup, session);
1775 #if 0 /// UNNEEDED by elogind
1776 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1777 _cleanup_free_ char *slice = NULL;
1783 r = cg_path_get_slice(path, &slice);
1787 start = startswith(slice, "user-");
1790 end = endswith(start, ".slice");
1795 if (parse_uid(start, uid) < 0)
1801 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1802 _cleanup_free_ char *cgroup = NULL;
1805 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1809 return cg_path_get_owner_uid(cgroup, uid);
1812 int cg_path_get_slice(const char *p, char **slice) {
1813 const char *e = NULL;
1818 /* Finds the right-most slice unit from the beginning, but
1819 * stops before we come to the first non-slice unit. */
1824 p += strspn(p, "/");
1826 n = strcspn(p, "/");
1827 if (!valid_slice_name(p, n)) {
1832 s = strdup(SPECIAL_ROOT_SLICE);
1840 return cg_path_decode_unit(e, slice);
1848 int cg_pid_get_slice(pid_t pid, char **slice) {
1849 _cleanup_free_ char *cgroup = NULL;
1854 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1858 return cg_path_get_slice(cgroup, slice);
1861 int cg_path_get_user_slice(const char *p, char **slice) {
1866 t = skip_user_prefix(p);
1870 /* And now it looks pretty much the same as for a system
1871 * slice, so let's just use the same parser from here on. */
1872 return cg_path_get_slice(t, slice);
1875 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1876 _cleanup_free_ char *cgroup = NULL;
1881 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1885 return cg_path_get_user_slice(cgroup, slice);
1889 char *cg_escape(const char *p) {
1890 bool need_prefix = false;
1892 /* This implements very minimal escaping for names to be used
1893 * as file names in the cgroup tree: any name which might
1894 * conflict with a kernel name or is prefixed with '_' is
1895 * prefixed with a '_'. That way, when reading cgroup names it
1896 * is sufficient to remove a single prefixing underscore if
1899 /* The return value of this function (unlike cg_unescape())
1905 streq(p, "notify_on_release") ||
1906 streq(p, "release_agent") ||
1907 streq(p, "tasks") ||
1908 startswith(p, "cgroup."))
1913 dot = strrchr(p, '.');
1918 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1921 n = cgroup_controller_to_string(c);
1926 if (memcmp(p, n, l) != 0)
1936 return strappend("_", p);
1941 char *cg_unescape(const char *p) {
1944 /* The return value of this function (unlike cg_escape())
1945 * doesn't need free()! */
1953 #define CONTROLLER_VALID \
1957 bool cg_controller_is_valid(const char *p) {
1963 if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
1966 s = startswith(p, "name=");
1970 if (*p == 0 || *p == '_')
1973 for (t = p; *t; t++)
1974 if (!strchr(CONTROLLER_VALID, *t))
1977 if (t - p > FILENAME_MAX)
1983 #if 0 /// UNNEEDED by elogind
1984 int cg_slice_to_path(const char *unit, char **ret) {
1985 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1992 if (streq(unit, SPECIAL_ROOT_SLICE)) {
2002 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
2005 if (!endswith(unit, ".slice"))
2008 r = unit_name_to_prefix(unit, &p);
2012 dash = strchr(p, '-');
2014 /* Don't allow initial dashes */
2019 _cleanup_free_ char *escaped = NULL;
2020 char n[dash - p + sizeof(".slice")];
2022 /* Don't allow trailing or double dashes */
2023 if (dash[1] == 0 || dash[1] == '-')
2026 strcpy(stpncpy(n, p, dash - p), ".slice");
2027 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
2030 escaped = cg_escape(n);
2034 if (!strextend(&s, escaped, "/", NULL))
2037 dash = strchr(dash+1, '-');
2040 e = cg_escape(unit);
2044 if (!strextend(&s, e, NULL))
2054 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
2055 _cleanup_free_ char *p = NULL;
2058 r = cg_get_path(controller, path, attribute, &p);
2062 return write_string_file(p, value, 0);
2065 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
2066 _cleanup_free_ char *p = NULL;
2069 r = cg_get_path(controller, path, attribute, &p);
2073 return read_one_line_file(p, ret);
2076 #if 0 /// UNNEEDED by elogind
2077 int cg_get_keyed_attribute(const char *controller, const char *path, const char *attribute, const char **keys, char **values) {
2078 _cleanup_free_ char *filename = NULL, *content = NULL;
2082 for (i = 0; keys[i]; i++)
2085 r = cg_get_path(controller, path, attribute, &filename);
2089 r = read_full_file(filename, &content, NULL);
2094 while ((line = strsep(&p, "\n"))) {
2097 key = strsep(&line, " ");
2099 for (i = 0; keys[i]; i++) {
2100 if (streq(key, keys[i])) {
2101 values[i] = strdup(line);
2107 for (i = 0; keys[i]; i++) {
2109 for (i = 0; keys[i]; i++) {
2120 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2124 /* This one will create a cgroup in our private tree, but also
2125 * duplicate it in the trees specified in mask, and remove it
2128 /* First create the cgroup in our own hierarchy. */
2129 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2133 /* If we are in the unified hierarchy, we are done now */
2134 r = cg_all_unified();
2140 /* Otherwise, do the same in the other hierarchies */
2141 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2142 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2145 n = cgroup_controller_to_string(c);
2148 (void) cg_create(n, path);
2149 else if (supported & bit)
2150 (void) cg_trim(n, path, true);
2156 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2160 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2164 r = cg_all_unified();
2170 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2171 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2172 const char *p = NULL;
2174 if (!(supported & bit))
2178 p = path_callback(bit, userdata);
2183 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2189 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2194 SET_FOREACH(pidp, pids, i) {
2195 pid_t pid = PTR_TO_PID(pidp);
2198 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2199 if (q < 0 && r >= 0)
2206 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2210 if (!path_equal(from, to)) {
2211 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2216 q = cg_all_unified();
2222 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2223 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2224 const char *p = NULL;
2226 if (!(supported & bit))
2230 p = to_callback(bit, userdata);
2235 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2241 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2245 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2249 q = cg_all_unified();
2255 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2256 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2258 if (!(supported & bit))
2261 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2268 int cg_mask_supported(CGroupMask *ret) {
2269 CGroupMask mask = 0;
2272 /* Determines the mask of supported cgroup controllers. Only
2273 * includes controllers we can make sense of and that are
2274 * actually accessible. */
2276 r = cg_all_unified();
2280 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2283 /* In the unified hierarchy we can read the supported
2284 * and accessible controllers from a the top-level
2285 * cgroup attribute */
2287 r = cg_get_root_path(&root);
2291 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2295 r = read_one_line_file(path, &controllers);
2301 _cleanup_free_ char *n = NULL;
2304 r = extract_first_word(&c, &n, NULL, 0);
2310 v = cgroup_controller_from_string(n);
2314 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2317 /* Currently, we support the cpu, memory, io and pids
2318 * controller in the unified hierarchy, mask
2319 * everything else off. */
2320 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2325 /* In the legacy hierarchy, we check whether which
2326 * hierarchies are mounted. */
2328 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2331 n = cgroup_controller_to_string(c);
2332 if (controller_is_accessible(n) >= 0)
2333 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2341 #if 0 /// UNNEEDED by elogind
2342 int cg_kernel_controllers(Set *controllers) {
2343 _cleanup_fclose_ FILE *f = NULL;
2347 assert(controllers);
2349 /* Determines the full list of kernel-known controllers. Might
2350 * include controllers we don't actually support, arbitrary
2351 * named hierarchies and controllers that aren't currently
2352 * accessible (because not mounted). */
2354 f = fopen("/proc/cgroups", "re");
2356 if (errno == ENOENT)
2361 /* Ignore the header line */
2362 (void) fgets(buf, sizeof(buf), f);
2369 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2374 if (ferror(f) && errno > 0)
2385 if (!cg_controller_is_valid(controller)) {
2390 r = set_consume(controllers, controller);
2399 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2401 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup v2 on /sys/fs/cgroup/systemd. This
2402 * unfortunately broke other tools (such as docker) which expected the v1 "name=systemd" hierarchy on
2403 * /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mountnbs v2 on /sys/fs/cgroup/unified and maintains
2404 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility with other tools.
2406 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep cgroup v2
2407 * process management but disable the compat dual layout, we return %true on
2408 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and %false on cg_hybrid_unified().
2410 static thread_local bool unified_systemd_v232;
2412 static int cg_unified_update(void) {
2416 /* Checks if we support the unified hierarchy. Returns an
2417 * error when the cgroup hierarchies aren't mounted yet or we
2418 * have any other trouble determining if the unified hierarchy
2421 if (unified_cache >= CGROUP_UNIFIED_NONE)
2424 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2427 #if 0 /// UNNEEDED by elogind
2428 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2429 unified_cache = CGROUP_UNIFIED_ALL;
2430 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2431 if (statfs("/sys/fs/cgroup/unified/", &fs) == 0 &&
2432 F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2433 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2434 unified_systemd_v232 = false;
2435 } else if (statfs("/sys/fs/cgroup/systemd/", &fs) == 0 &&
2436 F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2437 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2438 unified_systemd_v232 = true;
2440 if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2442 if (!F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC))
2444 unified_cache = CGROUP_UNIFIED_NONE;
2449 /* elogind can not support the unified hierarchy as a controller,
2450 * so always assume a classical hierarchy.
2451 * If, and only *if*, someone really wants to substitute systemd-login
2452 * in an environment managed by systemd with elogind, we might have to
2453 * add such a support. */
2454 unified_cache = CGROUP_UNIFIED_NONE;
2460 int cg_unified_controller(const char *controller) {
2463 r = cg_unified_update();
2467 if (unified_cache == CGROUP_UNIFIED_NONE)
2470 if (unified_cache >= CGROUP_UNIFIED_ALL)
2473 return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER);
2476 int cg_all_unified(void) {
2479 r = cg_unified_update();
2483 return unified_cache >= CGROUP_UNIFIED_ALL;
2486 int cg_hybrid_unified(void) {
2489 r = cg_unified_update();
2493 return unified_cache == CGROUP_UNIFIED_SYSTEMD && !unified_systemd_v232;
2496 int cg_unified_flush(void) {
2497 unified_cache = CGROUP_UNIFIED_UNKNOWN;
2499 return cg_unified_update();
2502 #if 0 /// UNNEEDED by elogind
2503 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2504 _cleanup_free_ char *fs = NULL;
2513 r = cg_all_unified();
2516 if (r == 0) /* on the legacy hiearchy there's no joining of controllers defined */
2519 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2523 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2524 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2527 if (!(supported & bit))
2530 n = cgroup_controller_to_string(c);
2532 char s[1 + strlen(n) + 1];
2534 s[0] = mask & bit ? '+' : '-';
2537 r = write_string_file(fs, s, 0);
2539 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2546 bool cg_is_unified_wanted(void) {
2547 static thread_local int wanted = -1;
2550 const bool is_default = DEFAULT_HIERARCHY == CGROUP_UNIFIED_ALL;
2552 /* If we have a cached value, return that. */
2556 /* If the hierarchy is already mounted, then follow whatever
2557 * was chosen for it. */
2558 if (cg_unified_flush() >= 0)
2559 return (wanted = unified_cache >= CGROUP_UNIFIED_ALL);
2561 /* Otherwise, let's see what the kernel command line has to say.
2562 * Since checking is expensive, cache a non-error result. */
2563 r = proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b);
2565 return (wanted = r > 0 ? b : is_default);
2568 bool cg_is_legacy_wanted(void) {
2569 static thread_local int wanted = -1;
2571 /* If we have a cached value, return that. */
2575 /* Check if we have cgroups2 already mounted. */
2576 if (cg_unified_flush() >= 0 &&
2577 unified_cache == CGROUP_UNIFIED_ALL)
2578 return (wanted = false);
2580 /* Otherwise, assume that at least partial legacy is wanted,
2581 * since cgroups2 should already be mounted at this point. */
2582 return (wanted = true);
2585 bool cg_is_hybrid_wanted(void) {
2586 static thread_local int wanted = -1;
2589 const bool is_default = DEFAULT_HIERARCHY >= CGROUP_UNIFIED_SYSTEMD;
2590 /* We default to true if the default is "hybrid", obviously,
2591 * but also when the default is "unified", because if we get
2592 * called, it means that unified hierarchy was not mounted. */
2594 /* If we have a cached value, return that. */
2598 /* If the hierarchy is already mounted, then follow whatever
2599 * was chosen for it. */
2600 if (cg_unified_flush() >= 0 &&
2601 unified_cache == CGROUP_UNIFIED_ALL)
2602 return (wanted = false);
2604 /* Otherwise, let's see what the kernel command line has to say.
2605 * Since checking is expensive, cache a non-error result. */
2606 r = proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b);
2608 /* The meaning of the kernel option is reversed wrt. to the return value
2609 * of this function, hence the negation. */
2610 return (wanted = r > 0 ? !b : is_default);
2613 bool cg_is_unified_wanted(void) {
2616 bool cg_is_legacy_wanted(void) {
2619 bool cg_is_hybrid_wanted(void) {
2624 #if 0 /// UNNEEDED by elogind
2625 int cg_weight_parse(const char *s, uint64_t *ret) {
2630 *ret = CGROUP_WEIGHT_INVALID;
2634 r = safe_atou64(s, &u);
2638 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2645 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2646 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2647 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2648 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2649 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2652 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2653 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2654 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2655 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2656 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2659 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2661 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2666 *ret = CGROUP_CPU_SHARES_INVALID;
2670 r = safe_atou64(s, &u);
2674 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2681 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2686 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2690 r = safe_atou64(s, &u);
2694 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2702 bool is_cgroup_fs(const struct statfs *s) {
2703 return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2704 is_fs_type(s, CGROUP2_SUPER_MAGIC);
2707 bool fd_is_cgroup_fs(int fd) {
2710 if (fstatfs(fd, &s) < 0)
2713 return is_cgroup_fs(&s);
2716 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2717 [CGROUP_CONTROLLER_CPU] = "cpu",
2718 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2719 [CGROUP_CONTROLLER_IO] = "io",
2720 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2721 [CGROUP_CONTROLLER_MEMORY] = "memory",
2722 [CGROUP_CONTROLLER_DEVICES] = "devices",
2723 [CGROUP_CONTROLLER_PIDS] = "pids",
2726 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);