2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 //#include <sys/statfs.h>
30 #include <sys/types.h>
33 #include "alloc-util.h"
34 #include "cgroup-util.h"
36 #include "dirent-util.h"
37 #include "extract-word.h"
40 #include "formats-util.h"
43 #include "login-util.h"
45 //#include "missing.h"
47 #include "parse-util.h"
48 #include "path-util.h"
49 #include "proc-cmdline.h"
50 #include "process-util.h"
52 //#include "special.h"
53 #include "stat-util.h"
54 #include "stdio-util.h"
55 #include "string-table.h"
56 #include "string-util.h"
57 #include "unit-name.h"
58 #include "user-util.h"
60 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
61 _cleanup_free_ char *fs = NULL;
67 r = cg_get_path(controller, path, "cgroup.procs", &fs);
79 int cg_read_pid(FILE *f, pid_t *_pid) {
82 /* Note that the cgroup.procs might contain duplicates! See
83 * cgroups.txt for details. */
89 if (fscanf(f, "%lu", &ul) != 1) {
94 return errno > 0 ? -errno : -EIO;
104 int cg_read_event(const char *controller, const char *path, const char *event,
107 _cleanup_free_ char *events = NULL, *content = NULL;
111 r = cg_get_path(controller, path, "cgroup.events", &events);
115 r = read_full_file(events, &content, NULL);
120 while ((line = strsep(&p, "\n"))) {
123 key = strsep(&line, " ");
127 if (strcmp(key, event))
137 #if 0 /// UNNEEDED by elogind
138 bool cg_ns_supported(void) {
139 static thread_local int enabled = -1;
144 if (access("/proc/self/ns/cgroup", F_OK) == 0)
153 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
154 _cleanup_free_ char *fs = NULL;
160 /* This is not recursive! */
162 r = cg_get_path(controller, path, NULL, &fs);
174 int cg_read_subgroup(DIR *d, char **fn) {
180 FOREACH_DIRENT_ALL(de, d, return -errno) {
183 if (de->d_type != DT_DIR)
186 if (streq(de->d_name, ".") ||
187 streq(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, NULL);
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, NULL);
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 e = startswith(controller, "name=");
558 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
565 dn = controller_to_dirname(controller);
567 if (isempty(path) && isempty(suffix))
568 t = strappend("/sys/fs/cgroup/", dn);
569 else if (isempty(path))
570 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
571 else if (isempty(suffix))
572 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
574 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
582 static int join_path_unified(const char *path, const char *suffix, char **fs) {
587 if (isempty(path) && isempty(suffix))
588 t = strdup("/sys/fs/cgroup");
589 else if (isempty(path))
590 t = strappend("/sys/fs/cgroup/", suffix);
591 else if (isempty(suffix))
592 t = strappend("/sys/fs/cgroup/", path);
594 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
602 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
610 /* If no controller is specified, we return the path
611 * *below* the controllers, without any prefix. */
613 if (!path && !suffix)
621 t = strjoin(path, "/", suffix, NULL);
625 *fs = path_kill_slashes(t);
629 if (!cg_controller_is_valid(controller))
632 unified = cg_all_unified();
637 r = join_path_unified(path, suffix, fs);
639 r = join_path_legacy(controller, path, suffix, fs);
643 path_kill_slashes(*fs);
647 static int controller_is_accessible(const char *controller) {
652 /* Checks whether a specific controller is accessible,
653 * i.e. its hierarchy mounted. In the unified hierarchy all
654 * controllers are considered accessible, except for the named
657 if (!cg_controller_is_valid(controller))
660 unified = cg_all_unified();
664 /* We don't support named hierarchies if we are using
665 * the unified hierarchy. */
667 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
670 if (startswith(controller, "name="))
676 dn = controller_to_dirname(controller);
677 cc = strjoina("/sys/fs/cgroup/", dn);
679 if (laccess(cc, F_OK) < 0)
686 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
692 /* Check if the specified controller is actually accessible */
693 r = controller_is_accessible(controller);
697 return cg_get_path(controller, path, suffix, fs);
700 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
705 if (typeflag != FTW_DP)
708 if (ftwbuf->level < 1)
715 int cg_trim(const char *controller, const char *path, bool delete_root) {
716 _cleanup_free_ char *fs = NULL;
721 r = cg_get_path(controller, path, NULL, &fs);
726 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
736 if (rmdir(fs) < 0 && errno != ENOENT)
743 int cg_create(const char *controller, const char *path) {
744 _cleanup_free_ char *fs = NULL;
747 r = cg_get_path_and_check(controller, path, NULL, &fs);
751 r = mkdir_parents(fs, 0755);
755 if (mkdir(fs, 0755) < 0) {
766 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
771 r = cg_create(controller, path);
775 q = cg_attach(controller, path, pid);
779 /* This does not remove the cgroup on failure */
783 int cg_attach(const char *controller, const char *path, pid_t pid) {
784 _cleanup_free_ char *fs = NULL;
785 char c[DECIMAL_STR_MAX(pid_t) + 2];
791 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
798 xsprintf(c, PID_FMT "\n", pid);
800 return write_string_file(fs, c, 0);
803 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
810 r = cg_attach(controller, path, pid);
812 char prefix[strlen(path) + 1];
814 /* This didn't work? Then let's try all prefixes of
817 PATH_FOREACH_PREFIX(prefix, path) {
820 q = cg_attach(controller, prefix, pid);
829 #if 0 /// UNNEEDED by elogind
830 int cg_set_group_access(
831 const char *controller,
837 _cleanup_free_ char *fs = NULL;
840 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
843 if (mode != MODE_INVALID)
846 r = cg_get_path(controller, path, NULL, &fs);
850 return chmod_and_chown(fs, mode, uid, gid);
853 int cg_set_task_access(
854 const char *controller,
860 _cleanup_free_ char *fs = NULL, *procs = NULL;
865 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
868 if (mode != MODE_INVALID)
871 r = cg_get_path(controller, path, "cgroup.procs", &fs);
875 r = chmod_and_chown(fs, mode, uid, gid);
879 unified = cg_all_unified();
885 /* Compatibility, Always keep values for "tasks" in sync with
887 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
888 (void) chmod_and_chown(procs, mode, uid, gid);
894 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
895 _cleanup_fclose_ FILE *f = NULL;
904 unified = cg_all_unified();
909 if (!cg_controller_is_valid(controller))
912 controller = SYSTEMD_CGROUP_CONTROLLER;
914 cs = strlen(controller);
917 fs = procfs_file_alloca(pid, "cgroup");
918 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
919 pid, fs, controller);
922 return errno == ENOENT ? -ESRCH : -errno;
924 FOREACH_LINE(line, f, return -errno) {
930 e = startswith(line, "0:");
940 const char *word, *state;
943 l = strchr(line, ':');
953 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
954 if (k == cs && memcmp(word, controller, cs) == 0) {
964 log_debug_elogind("Found %s:%s", line, e+1);
976 int cg_install_release_agent(const char *controller, const char *agent) {
977 _cleanup_free_ char *fs = NULL, *contents = NULL;
983 unified = cg_all_unified();
986 if (unified) /* doesn't apply to unified hierarchy */
989 r = cg_get_path(controller, NULL, "release_agent", &fs);
993 r = read_one_line_file(fs, &contents);
997 sc = strstrip(contents);
999 r = write_string_file(fs, agent, 0);
1002 } else if (!path_equal(sc, agent))
1006 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1010 contents = mfree(contents);
1011 r = read_one_line_file(fs, &contents);
1015 sc = strstrip(contents);
1016 if (streq(sc, "0")) {
1017 r = write_string_file(fs, "1", 0);
1024 if (!streq(sc, "1"))
1030 int cg_uninstall_release_agent(const char *controller) {
1031 _cleanup_free_ char *fs = NULL;
1034 unified = cg_all_unified();
1037 if (unified) /* Doesn't apply to unified hierarchy */
1040 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1044 r = write_string_file(fs, "0", 0);
1050 r = cg_get_path(controller, NULL, "release_agent", &fs);
1054 r = write_string_file(fs, "", 0);
1061 int cg_is_empty(const char *controller, const char *path) {
1062 _cleanup_fclose_ FILE *f = NULL;
1068 r = cg_enumerate_processes(controller, path, &f);
1074 r = cg_read_pid(f, &pid);
1081 int cg_is_empty_recursive(const char *controller, const char *path) {
1086 /* The root cgroup is always populated */
1087 if (controller && (isempty(path) || path_equal(path, "/")))
1090 unified = cg_all_unified();
1095 _cleanup_free_ char *t = NULL;
1097 /* On the unified hierarchy we can check empty state
1098 * via the "populated" attribute of "cgroup.events". */
1100 r = cg_read_event(controller, path, "populated", &t);
1104 return streq(t, "0");
1106 _cleanup_closedir_ DIR *d = NULL;
1109 r = cg_is_empty(controller, path);
1113 r = cg_enumerate_subgroups(controller, path, &d);
1119 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1120 _cleanup_free_ char *p = NULL;
1122 p = strjoin(path, "/", fn, NULL);
1127 r = cg_is_empty_recursive(controller, p);
1138 int cg_split_spec(const char *spec, char **controller, char **path) {
1139 char *t = NULL, *u = NULL;
1145 if (!path_is_safe(spec))
1153 *path = path_kill_slashes(t);
1162 e = strchr(spec, ':');
1164 if (!cg_controller_is_valid(spec))
1181 t = strndup(spec, e-spec);
1184 if (!cg_controller_is_valid(t)) {
1198 if (!path_is_safe(u) ||
1199 !path_is_absolute(u)) {
1205 path_kill_slashes(u);
1221 int cg_mangle_path(const char *path, char **result) {
1222 _cleanup_free_ char *c = NULL, *p = NULL;
1229 /* First, check if it already is a filesystem path */
1230 if (path_startswith(path, "/sys/fs/cgroup")) {
1236 *result = path_kill_slashes(t);
1240 /* Otherwise, treat it as cg spec */
1241 r = cg_split_spec(path, &c, &p);
1245 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1248 int cg_get_root_path(char **path) {
1249 #if 0 /// elogind does not support systemd scopes and slices
1255 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1259 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1261 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1263 e = endswith(p, "/system"); /* even more legacy */
1271 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1275 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1276 _cleanup_free_ char *rt = NULL;
1284 /* If the root was specified let's use that, otherwise
1285 * let's determine it from PID 1 */
1287 r = cg_get_root_path(&rt);
1292 log_debug_elogind("Determined root path: \"%s\"", root);
1295 p = path_startswith(cgroup, root);
1296 if (p && p > cgroup)
1304 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1305 _cleanup_free_ char *raw = NULL;
1312 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1316 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1317 raw, pid, root ? root : "NULL");
1318 r = cg_shift_path(raw, root, &c);
1334 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1339 #if 0 /// UNNEEDED by elogind
1340 int cg_path_decode_unit(const char *cgroup, char **unit) {
1347 n = strcspn(cgroup, "/");
1351 c = strndupa(cgroup, n);
1354 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1365 static bool valid_slice_name(const char *p, size_t n) {
1370 if (n < strlen("x.slice"))
1373 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1379 c = cg_unescape(buf);
1381 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1387 static const char *skip_slices(const char *p) {
1390 /* Skips over all slice assignments */
1395 p += strspn(p, "/");
1397 n = strcspn(p, "/");
1398 if (!valid_slice_name(p, n))
1405 int cg_path_get_unit(const char *path, char **ret) {
1413 e = skip_slices(path);
1415 r = cg_path_decode_unit(e, &unit);
1419 /* We skipped over the slices, don't accept any now */
1420 if (endswith(unit, ".slice")) {
1429 int cg_pid_get_unit(pid_t pid, char **unit) {
1430 _cleanup_free_ char *cgroup = NULL;
1435 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1439 return cg_path_get_unit(cgroup, unit);
1443 * Skip session-*.scope, but require it to be there.
1445 static const char *skip_session(const char *p) {
1451 p += strspn(p, "/");
1453 n = strcspn(p, "/");
1454 if (n < strlen("session-x.scope"))
1457 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1458 char buf[n - 8 - 6 + 1];
1460 memcpy(buf, p + 8, n - 8 - 6);
1463 /* Note that session scopes never need unescaping,
1464 * since they cannot conflict with the kernel's own
1465 * names, hence we don't need to call cg_unescape()
1468 if (!session_id_valid(buf))
1472 p += strspn(p, "/");
1480 * Skip user@*.service, but require it to be there.
1482 static const char *skip_user_manager(const char *p) {
1488 p += strspn(p, "/");
1490 n = strcspn(p, "/");
1491 if (n < strlen("user@x.service"))
1494 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1495 char buf[n - 5 - 8 + 1];
1497 memcpy(buf, p + 5, n - 5 - 8);
1500 /* Note that user manager services never need unescaping,
1501 * since they cannot conflict with the kernel's own
1502 * names, hence we don't need to call cg_unescape()
1505 if (parse_uid(buf, NULL) < 0)
1509 p += strspn(p, "/");
1517 static const char *skip_user_prefix(const char *path) {
1522 /* Skip slices, if there are any */
1523 e = skip_slices(path);
1525 /* Skip the user manager, if it's in the path now... */
1526 t = skip_user_manager(e);
1530 /* Alternatively skip the user session if it is in the path... */
1531 return skip_session(e);
1534 int cg_path_get_user_unit(const char *path, char **ret) {
1540 t = skip_user_prefix(path);
1544 /* And from here on it looks pretty much the same as for a
1545 * system unit, hence let's use the same parser from here
1547 return cg_path_get_unit(t, ret);
1550 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1551 _cleanup_free_ char *cgroup = NULL;
1556 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1560 return cg_path_get_user_unit(cgroup, unit);
1563 int cg_path_get_machine_name(const char *path, char **machine) {
1564 _cleanup_free_ char *u = NULL;
1568 r = cg_path_get_unit(path, &u);
1572 sl = strjoina("/run/systemd/machines/unit:", u);
1573 return readlink_malloc(sl, machine);
1576 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1577 _cleanup_free_ char *cgroup = NULL;
1582 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1586 return cg_path_get_machine_name(cgroup, machine);
1590 int cg_path_get_session(const char *path, char **session) {
1591 #if 0 /// UNNEEDED by elogind
1592 _cleanup_free_ char *unit = NULL;
1598 r = cg_path_get_unit(path, &unit);
1602 start = startswith(unit, "session-");
1605 end = endswith(start, ".scope");
1610 if (!session_id_valid(start))
1613 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1614 wrinkle is that SESSION might be escaped. */
1615 const char *e, *n, *start;
1618 log_debug_elogind("path is \"%s\"", path);
1619 assert(path[0] == '/');
1622 n = strchrnul(e, '/');
1626 start = strndupa(e, n - e);
1627 start = cg_unescape(start);
1636 log_debug_elogind("found session: \"%s\"", start);
1647 int cg_pid_get_session(pid_t pid, char **session) {
1648 _cleanup_free_ char *cgroup = NULL;
1651 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1655 return cg_path_get_session(cgroup, session);
1658 #if 0 /// UNNEEDED by elogind
1659 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1660 _cleanup_free_ char *slice = NULL;
1666 r = cg_path_get_slice(path, &slice);
1670 start = startswith(slice, "user-");
1673 end = endswith(start, ".slice");
1678 if (parse_uid(start, uid) < 0)
1684 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1685 _cleanup_free_ char *cgroup = NULL;
1688 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1692 return cg_path_get_owner_uid(cgroup, uid);
1695 int cg_path_get_slice(const char *p, char **slice) {
1696 const char *e = NULL;
1701 /* Finds the right-most slice unit from the beginning, but
1702 * stops before we come to the first non-slice unit. */
1707 p += strspn(p, "/");
1709 n = strcspn(p, "/");
1710 if (!valid_slice_name(p, n)) {
1715 s = strdup("-.slice");
1723 return cg_path_decode_unit(e, slice);
1731 int cg_pid_get_slice(pid_t pid, char **slice) {
1732 _cleanup_free_ char *cgroup = NULL;
1737 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1741 return cg_path_get_slice(cgroup, slice);
1744 int cg_path_get_user_slice(const char *p, char **slice) {
1749 t = skip_user_prefix(p);
1753 /* And now it looks pretty much the same as for a system
1754 * slice, so let's just use the same parser from here on. */
1755 return cg_path_get_slice(t, slice);
1758 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1759 _cleanup_free_ char *cgroup = NULL;
1764 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1768 return cg_path_get_user_slice(cgroup, slice);
1772 char *cg_escape(const char *p) {
1773 bool need_prefix = false;
1775 /* This implements very minimal escaping for names to be used
1776 * as file names in the cgroup tree: any name which might
1777 * conflict with a kernel name or is prefixed with '_' is
1778 * prefixed with a '_'. That way, when reading cgroup names it
1779 * is sufficient to remove a single prefixing underscore if
1782 /* The return value of this function (unlike cg_unescape())
1788 streq(p, "notify_on_release") ||
1789 streq(p, "release_agent") ||
1790 streq(p, "tasks") ||
1791 startswith(p, "cgroup."))
1796 dot = strrchr(p, '.');
1801 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1804 n = cgroup_controller_to_string(c);
1809 if (memcmp(p, n, l) != 0)
1819 return strappend("_", p);
1824 char *cg_unescape(const char *p) {
1827 /* The return value of this function (unlike cg_escape())
1828 * doesn't need free()! */
1836 #define CONTROLLER_VALID \
1840 bool cg_controller_is_valid(const char *p) {
1846 s = startswith(p, "name=");
1850 if (*p == 0 || *p == '_')
1853 for (t = p; *t; t++)
1854 if (!strchr(CONTROLLER_VALID, *t))
1857 if (t - p > FILENAME_MAX)
1863 #if 0 /// UNNEEDED by elogind
1864 int cg_slice_to_path(const char *unit, char **ret) {
1865 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1872 if (streq(unit, "-.slice")) {
1882 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1885 if (!endswith(unit, ".slice"))
1888 r = unit_name_to_prefix(unit, &p);
1892 dash = strchr(p, '-');
1894 /* Don't allow initial dashes */
1899 _cleanup_free_ char *escaped = NULL;
1900 char n[dash - p + sizeof(".slice")];
1902 /* Don't allow trailing or double dashes */
1903 if (dash[1] == 0 || dash[1] == '-')
1906 strcpy(stpncpy(n, p, dash - p), ".slice");
1907 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1910 escaped = cg_escape(n);
1914 if (!strextend(&s, escaped, "/", NULL))
1917 dash = strchr(dash+1, '-');
1920 e = cg_escape(unit);
1924 if (!strextend(&s, e, NULL))
1934 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1935 _cleanup_free_ char *p = NULL;
1938 r = cg_get_path(controller, path, attribute, &p);
1942 return write_string_file(p, value, 0);
1945 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1946 _cleanup_free_ char *p = NULL;
1949 r = cg_get_path(controller, path, attribute, &p);
1953 return read_one_line_file(p, ret);
1956 #if 0 /// UNNEEDED by elogind
1957 int cg_get_keyed_attribute(const char *controller, const char *path, const char *attribute, const char **keys, char **values) {
1958 _cleanup_free_ char *filename = NULL, *content = NULL;
1962 for (i = 0; keys[i]; i++)
1965 r = cg_get_path(controller, path, attribute, &filename);
1969 r = read_full_file(filename, &content, NULL);
1974 while ((line = strsep(&p, "\n"))) {
1977 key = strsep(&line, " ");
1979 for (i = 0; keys[i]; i++) {
1980 if (streq(key, keys[i])) {
1981 values[i] = strdup(line);
1987 for (i = 0; keys[i]; i++) {
1989 for (i = 0; keys[i]; i++) {
2000 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2004 /* This one will create a cgroup in our private tree, but also
2005 * duplicate it in the trees specified in mask, and remove it
2008 /* First create the cgroup in our own hierarchy. */
2009 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2013 /* If we are in the unified hierarchy, we are done now */
2014 unified = cg_all_unified();
2020 /* Otherwise, do the same in the other hierarchies */
2021 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2022 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2025 n = cgroup_controller_to_string(c);
2028 (void) cg_create(n, path);
2029 else if (supported & bit)
2030 (void) cg_trim(n, path, true);
2036 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2040 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2044 unified = cg_all_unified();
2050 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2051 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2052 const char *p = NULL;
2054 if (!(supported & bit))
2058 p = path_callback(bit, userdata);
2063 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2069 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2074 SET_FOREACH(pidp, pids, i) {
2075 pid_t pid = PTR_TO_PID(pidp);
2078 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2079 if (q < 0 && r >= 0)
2086 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2090 if (!path_equal(from, to)) {
2091 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2096 unified = cg_all_unified();
2102 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2103 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2104 const char *p = NULL;
2106 if (!(supported & bit))
2110 p = to_callback(bit, userdata);
2115 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2121 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2125 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2129 unified = cg_all_unified();
2135 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2136 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2138 if (!(supported & bit))
2141 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2148 int cg_mask_supported(CGroupMask *ret) {
2149 CGroupMask mask = 0;
2152 /* Determines the mask of supported cgroup controllers. Only
2153 * includes controllers we can make sense of and that are
2154 * actually accessible. */
2156 unified = cg_all_unified();
2160 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2163 /* In the unified hierarchy we can read the supported
2164 * and accessible controllers from a the top-level
2165 * cgroup attribute */
2167 r = cg_get_root_path(&root);
2171 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2175 r = read_one_line_file(path, &controllers);
2181 _cleanup_free_ char *n = NULL;
2184 r = extract_first_word(&c, &n, NULL, 0);
2190 v = cgroup_controller_from_string(n);
2194 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2197 /* Currently, we support the cpu, memory, io and pids
2198 * controller in the unified hierarchy, mask
2199 * everything else off. */
2200 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2205 /* In the legacy hierarchy, we check whether which
2206 * hierarchies are mounted. */
2208 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2211 n = cgroup_controller_to_string(c);
2212 if (controller_is_accessible(n) >= 0)
2213 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2221 #if 0 /// UNNEEDED by elogind
2222 int cg_kernel_controllers(Set *controllers) {
2223 _cleanup_fclose_ FILE *f = NULL;
2227 assert(controllers);
2229 /* Determines the full list of kernel-known controllers. Might
2230 * include controllers we don't actually support, arbitrary
2231 * named hierarchies and controllers that aren't currently
2232 * accessible (because not mounted). */
2234 f = fopen("/proc/cgroups", "re");
2236 if (errno == ENOENT)
2241 /* Ignore the header line */
2242 (void) fgets(buf, sizeof(buf), f);
2249 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2254 if (ferror(f) && errno > 0)
2265 if (!cg_controller_is_valid(controller)) {
2270 r = set_consume(controllers, controller);
2279 static thread_local int unified_cache = -1;
2281 int cg_all_unified(void) {
2284 /* Checks if we support the unified hierarchy. Returns an
2285 * error when the cgroup hierarchies aren't mounted yet or we
2286 * have any other trouble determining if the unified hierarchy
2289 if (unified_cache >= 0)
2290 return unified_cache;
2292 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2295 #if 0 /// UNNEEDED by elogind
2296 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2298 /* elogind can not support the unified hierarchy as a controller,
2299 * so always assume a classical hierarchy.
2300 * If, and only *if*, someone really wants to substitute systemd-login
2301 * in an environment managed by systemd with elogind, we might have to
2302 * add such a support. */
2303 if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2305 unified_cache = true;
2306 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2307 unified_cache = false;
2311 return unified_cache;
2314 #if 0 /// UNNEEDED by elogind
2315 void cg_unified_flush(void) {
2319 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2320 _cleanup_free_ char *fs = NULL;
2329 unified = cg_all_unified();
2332 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2335 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2339 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2340 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2343 if (!(supported & bit))
2346 n = cgroup_controller_to_string(c);
2348 char s[1 + strlen(n) + 1];
2350 s[0] = mask & bit ? '+' : '-';
2353 r = write_string_file(fs, s, 0);
2355 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2362 bool cg_is_unified_wanted(void) {
2363 static thread_local int wanted = -1;
2366 /* If the hierarchy is already mounted, then follow whatever
2367 * was chosen for it. */
2368 unified = cg_all_unified();
2372 /* Otherwise, let's see what the kernel command line has to
2373 * say. Since checking that is expensive, let's cache the
2378 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2380 return (wanted = true);
2382 _cleanup_free_ char *value = NULL;
2384 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2388 return (wanted = false);
2390 return (wanted = parse_boolean(value) > 0);
2394 bool cg_is_legacy_wanted(void) {
2395 return !cg_is_unified_wanted();
2398 bool cg_is_legacy_wanted(void) {
2401 bool cg_is_unified_systemd_controller_wanted(void) {
2402 static thread_local int wanted = -1;
2405 /* If the unified hierarchy is requested in full, no need to
2406 * bother with this. */
2407 if (cg_is_unified_wanted())
2410 /* If the hierarchy is already mounted, then follow whatever
2411 * was chosen for it. */
2412 unified = cg_unified(SYSTEMD_CGROUP_CONTROLLER);
2416 /* Otherwise, let's see what the kernel command line has to
2417 * say. Since checking that is expensive, let's cache the
2422 r = get_proc_cmdline_key("systemd.legacy_systemd_cgroup_controller", NULL);
2426 _cleanup_free_ char *value = NULL;
2428 r = get_proc_cmdline_key("systemd.legacy_systemd_cgroup_controller=", &value);
2435 wanted = parse_boolean(value) <= 0;
2441 bool cg_is_legacy_systemd_controller_wanted(void) {
2442 return cg_is_legacy_wanted() && !cg_is_unified_systemd_controller_wanted();
2446 #if 0 /// UNNEEDED by elogind
2447 int cg_weight_parse(const char *s, uint64_t *ret) {
2452 *ret = CGROUP_WEIGHT_INVALID;
2456 r = safe_atou64(s, &u);
2460 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2467 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2468 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2469 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2470 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2471 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2474 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2475 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2476 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2477 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2478 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2481 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2483 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2488 *ret = CGROUP_CPU_SHARES_INVALID;
2492 r = safe_atou64(s, &u);
2496 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2503 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2508 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2512 r = safe_atou64(s, &u);
2516 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2524 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2525 [CGROUP_CONTROLLER_CPU] = "cpu",
2526 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2527 [CGROUP_CONTROLLER_IO] = "io",
2528 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2529 [CGROUP_CONTROLLER_MEMORY] = "memory",
2530 [CGROUP_CONTROLLER_DEVICES] = "devices",
2531 [CGROUP_CONTROLLER_PIDS] = "pids",
2534 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);