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 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
138 _cleanup_free_ char *fs = NULL;
144 /* This is not recursive! */
146 r = cg_get_path(controller, path, NULL, &fs);
158 int cg_read_subgroup(DIR *d, char **fn) {
164 FOREACH_DIRENT_ALL(de, d, return -errno) {
167 if (de->d_type != DT_DIR)
170 if (streq(de->d_name, ".") ||
171 streq(de->d_name, ".."))
174 b = strdup(de->d_name);
185 int cg_rmdir(const char *controller, const char *path) {
186 _cleanup_free_ char *p = NULL;
189 r = cg_get_path(controller, path, NULL, &p);
194 if (r < 0 && errno != ENOENT)
201 const char *controller,
206 cg_kill_log_func_t log_kill,
209 _cleanup_set_free_ Set *allocated_set = NULL;
216 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
217 * SIGCONT on SIGKILL. */
218 if (IN_SET(sig, SIGCONT, SIGKILL))
219 flags &= ~CGROUP_SIGCONT;
221 /* This goes through the tasks list and kills them all. This
222 * is repeated until no further processes are added to the
223 * tasks list, to properly handle forking processes */
226 s = allocated_set = set_new(NULL);
234 _cleanup_fclose_ FILE *f = NULL;
238 r = cg_enumerate_processes(controller, path, &f);
240 if (ret >= 0 && r != -ENOENT)
246 while ((r = cg_read_pid(f, &pid)) > 0) {
248 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
251 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
255 log_kill(pid, sig, userdata);
257 /* If we haven't killed this process yet, kill
259 if (kill(pid, sig) < 0) {
260 if (ret >= 0 && errno != ESRCH)
263 if (flags & CGROUP_SIGCONT)
264 (void) kill(pid, SIGCONT);
272 r = set_put(s, PID_TO_PTR(pid));
288 /* To avoid racing against processes which fork
289 * quicker than we can kill them we repeat this until
290 * no new pids need to be killed. */
297 int cg_kill_recursive(
298 const char *controller,
303 cg_kill_log_func_t log_kill,
306 _cleanup_set_free_ Set *allocated_set = NULL;
307 _cleanup_closedir_ DIR *d = NULL;
315 s = allocated_set = set_new(NULL);
320 ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
322 r = cg_enumerate_subgroups(controller, path, &d);
324 if (ret >= 0 && r != -ENOENT)
330 while ((r = cg_read_subgroup(d, &fn)) > 0) {
331 _cleanup_free_ char *p = NULL;
333 p = strjoin(path, "/", fn, NULL);
338 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
339 if (r != 0 && ret >= 0)
342 if (ret >= 0 && r < 0)
345 if (flags & CGROUP_REMOVE) {
346 r = cg_rmdir(controller, path);
347 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
362 _cleanup_set_free_ Set *s = NULL;
377 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
378 cfrom, pfrom, cto, pto,
379 ignore_self ? "ignoring self" : "watching self");
381 _cleanup_fclose_ FILE *f = NULL;
385 r = cg_enumerate_processes(cfrom, pfrom, &f);
387 if (ret >= 0 && r != -ENOENT)
393 while ((r = cg_read_pid(f, &pid)) > 0) {
395 /* This might do weird stuff if we aren't a
396 * single-threaded program. However, we
397 * luckily know we are not */
398 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
401 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
404 /* Ignore kernel threads. Since they can only
405 * exist in the root cgroup, we only check for
408 (isempty(pfrom) || path_equal(pfrom, "/")) &&
409 is_kernel_thread(pid) > 0)
412 r = cg_attach(cto, pto, pid);
414 if (ret >= 0 && r != -ESRCH)
421 r = set_put(s, PID_TO_PTR(pid));
441 int cg_migrate_recursive(
448 _cleanup_closedir_ DIR *d = NULL;
457 ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
459 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
461 if (ret >= 0 && r != -ENOENT)
467 while ((r = cg_read_subgroup(d, &fn)) > 0) {
468 _cleanup_free_ char *p = NULL;
470 p = strjoin(pfrom, "/", fn, NULL);
475 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
476 if (r != 0 && ret >= 0)
480 if (r < 0 && ret >= 0)
483 if (flags & CGROUP_REMOVE) {
484 r = cg_rmdir(cfrom, pfrom);
485 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
492 int cg_migrate_recursive_fallback(
506 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
508 char prefix[strlen(pto) + 1];
510 /* This didn't work? Then let's try all prefixes of the destination */
512 PATH_FOREACH_PREFIX(prefix, pto) {
515 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
524 static const char *controller_to_dirname(const char *controller) {
529 /* Converts a controller name to the directory name below
530 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
531 * just cuts off the name= prefixed used for named
532 * hierarchies, if it is specified. */
534 e = startswith(controller, "name=");
541 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
548 dn = controller_to_dirname(controller);
550 if (isempty(path) && isempty(suffix))
551 t = strappend("/sys/fs/cgroup/", dn);
552 else if (isempty(path))
553 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
554 else if (isempty(suffix))
555 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
557 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
565 static int join_path_unified(const char *path, const char *suffix, char **fs) {
570 if (isempty(path) && isempty(suffix))
571 t = strdup("/sys/fs/cgroup");
572 else if (isempty(path))
573 t = strappend("/sys/fs/cgroup/", suffix);
574 else if (isempty(suffix))
575 t = strappend("/sys/fs/cgroup/", path);
577 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
585 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
593 /* If no controller is specified, we return the path
594 * *below* the controllers, without any prefix. */
596 if (!path && !suffix)
604 t = strjoin(path, "/", suffix, NULL);
608 *fs = path_kill_slashes(t);
612 if (!cg_controller_is_valid(controller))
615 unified = cg_unified();
620 r = join_path_unified(path, suffix, fs);
622 r = join_path_legacy(controller, path, suffix, fs);
626 path_kill_slashes(*fs);
630 static int controller_is_accessible(const char *controller) {
635 /* Checks whether a specific controller is accessible,
636 * i.e. its hierarchy mounted. In the unified hierarchy all
637 * controllers are considered accessible, except for the named
640 if (!cg_controller_is_valid(controller))
643 unified = cg_unified();
647 /* We don't support named hierarchies if we are using
648 * the unified hierarchy. */
650 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
653 if (startswith(controller, "name="))
659 dn = controller_to_dirname(controller);
660 cc = strjoina("/sys/fs/cgroup/", dn);
662 if (laccess(cc, F_OK) < 0)
669 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
675 /* Check if the specified controller is actually accessible */
676 r = controller_is_accessible(controller);
680 return cg_get_path(controller, path, suffix, fs);
683 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
688 if (typeflag != FTW_DP)
691 if (ftwbuf->level < 1)
698 int cg_trim(const char *controller, const char *path, bool delete_root) {
699 _cleanup_free_ char *fs = NULL;
704 r = cg_get_path(controller, path, NULL, &fs);
709 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
719 if (rmdir(fs) < 0 && errno != ENOENT)
726 int cg_create(const char *controller, const char *path) {
727 _cleanup_free_ char *fs = NULL;
730 r = cg_get_path_and_check(controller, path, NULL, &fs);
734 r = mkdir_parents(fs, 0755);
738 if (mkdir(fs, 0755) < 0) {
749 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
754 r = cg_create(controller, path);
758 q = cg_attach(controller, path, pid);
762 /* This does not remove the cgroup on failure */
766 int cg_attach(const char *controller, const char *path, pid_t pid) {
767 _cleanup_free_ char *fs = NULL;
768 char c[DECIMAL_STR_MAX(pid_t) + 2];
774 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
781 xsprintf(c, PID_FMT "\n", pid);
783 return write_string_file(fs, c, 0);
786 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
793 r = cg_attach(controller, path, pid);
795 char prefix[strlen(path) + 1];
797 /* This didn't work? Then let's try all prefixes of
800 PATH_FOREACH_PREFIX(prefix, path) {
803 q = cg_attach(controller, prefix, pid);
812 #if 0 /// UNNEEDED by elogind
813 int cg_set_group_access(
814 const char *controller,
820 _cleanup_free_ char *fs = NULL;
823 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
826 if (mode != MODE_INVALID)
829 r = cg_get_path(controller, path, NULL, &fs);
833 return chmod_and_chown(fs, mode, uid, gid);
836 int cg_set_task_access(
837 const char *controller,
843 _cleanup_free_ char *fs = NULL, *procs = NULL;
848 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
851 if (mode != MODE_INVALID)
854 r = cg_get_path(controller, path, "cgroup.procs", &fs);
858 r = chmod_and_chown(fs, mode, uid, gid);
862 unified = cg_unified();
868 /* Compatibility, Always keep values for "tasks" in sync with
870 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
871 (void) chmod_and_chown(procs, mode, uid, gid);
877 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
878 _cleanup_fclose_ FILE *f = NULL;
887 unified = cg_unified();
892 if (!cg_controller_is_valid(controller))
895 controller = SYSTEMD_CGROUP_CONTROLLER;
897 cs = strlen(controller);
900 fs = procfs_file_alloca(pid, "cgroup");
901 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
902 pid, fs, controller);
905 return errno == ENOENT ? -ESRCH : -errno;
907 FOREACH_LINE(line, f, return -errno) {
913 e = startswith(line, "0:");
923 const char *word, *state;
926 l = strchr(line, ':');
936 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
937 if (k == cs && memcmp(word, controller, cs) == 0) {
947 log_debug_elogind("Found %s:%s", line, e+1);
959 int cg_install_release_agent(const char *controller, const char *agent) {
960 _cleanup_free_ char *fs = NULL, *contents = NULL;
966 unified = cg_unified();
969 if (unified) /* doesn't apply to unified hierarchy */
972 r = cg_get_path(controller, NULL, "release_agent", &fs);
976 r = read_one_line_file(fs, &contents);
980 sc = strstrip(contents);
982 r = write_string_file(fs, agent, 0);
985 } else if (!path_equal(sc, agent))
989 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
993 contents = mfree(contents);
994 r = read_one_line_file(fs, &contents);
998 sc = strstrip(contents);
999 if (streq(sc, "0")) {
1000 r = write_string_file(fs, "1", 0);
1007 if (!streq(sc, "1"))
1013 int cg_uninstall_release_agent(const char *controller) {
1014 _cleanup_free_ char *fs = NULL;
1017 unified = cg_unified();
1020 if (unified) /* Doesn't apply to unified hierarchy */
1023 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1027 r = write_string_file(fs, "0", 0);
1033 r = cg_get_path(controller, NULL, "release_agent", &fs);
1037 r = write_string_file(fs, "", 0);
1044 int cg_is_empty(const char *controller, const char *path) {
1045 _cleanup_fclose_ FILE *f = NULL;
1051 r = cg_enumerate_processes(controller, path, &f);
1057 r = cg_read_pid(f, &pid);
1064 int cg_is_empty_recursive(const char *controller, const char *path) {
1069 /* The root cgroup is always populated */
1070 if (controller && (isempty(path) || path_equal(path, "/")))
1073 unified = cg_unified();
1078 _cleanup_free_ char *t = NULL;
1080 /* On the unified hierarchy we can check empty state
1081 * via the "populated" attribute of "cgroup.events". */
1083 r = cg_read_event(controller, path, "populated", &t);
1087 return streq(t, "0");
1089 _cleanup_closedir_ DIR *d = NULL;
1092 r = cg_is_empty(controller, path);
1096 r = cg_enumerate_subgroups(controller, path, &d);
1102 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1103 _cleanup_free_ char *p = NULL;
1105 p = strjoin(path, "/", fn, NULL);
1110 r = cg_is_empty_recursive(controller, p);
1121 int cg_split_spec(const char *spec, char **controller, char **path) {
1122 char *t = NULL, *u = NULL;
1128 if (!path_is_safe(spec))
1136 *path = path_kill_slashes(t);
1145 e = strchr(spec, ':');
1147 if (!cg_controller_is_valid(spec))
1164 t = strndup(spec, e-spec);
1167 if (!cg_controller_is_valid(t)) {
1181 if (!path_is_safe(u) ||
1182 !path_is_absolute(u)) {
1188 path_kill_slashes(u);
1204 int cg_mangle_path(const char *path, char **result) {
1205 _cleanup_free_ char *c = NULL, *p = NULL;
1212 /* First, check if it already is a filesystem path */
1213 if (path_startswith(path, "/sys/fs/cgroup")) {
1219 *result = path_kill_slashes(t);
1223 /* Otherwise, treat it as cg spec */
1224 r = cg_split_spec(path, &c, &p);
1228 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1231 int cg_get_root_path(char **path) {
1232 #if 0 /// elogind does not support systemd scopes and slices
1238 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1242 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1244 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1246 e = endswith(p, "/system"); /* even more legacy */
1254 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1258 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1259 _cleanup_free_ char *rt = NULL;
1267 /* If the root was specified let's use that, otherwise
1268 * let's determine it from PID 1 */
1270 r = cg_get_root_path(&rt);
1275 log_debug_elogind("Determined root path: \"%s\"", root);
1278 p = path_startswith(cgroup, root);
1279 if (p && p[0] && (p > cgroup))
1287 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1288 _cleanup_free_ char *raw = NULL;
1295 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1299 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1300 raw, pid, root ? root : "NULL");
1301 r = cg_shift_path(raw, root, &c);
1317 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1322 #if 0 /// UNNEEDED by elogind
1323 int cg_path_decode_unit(const char *cgroup, char **unit) {
1330 n = strcspn(cgroup, "/");
1334 c = strndupa(cgroup, n);
1337 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1348 static bool valid_slice_name(const char *p, size_t n) {
1353 if (n < strlen("x.slice"))
1356 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1362 c = cg_unescape(buf);
1364 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1370 static const char *skip_slices(const char *p) {
1373 /* Skips over all slice assignments */
1378 p += strspn(p, "/");
1380 n = strcspn(p, "/");
1381 if (!valid_slice_name(p, n))
1388 int cg_path_get_unit(const char *path, char **ret) {
1396 e = skip_slices(path);
1398 r = cg_path_decode_unit(e, &unit);
1402 /* We skipped over the slices, don't accept any now */
1403 if (endswith(unit, ".slice")) {
1412 int cg_pid_get_unit(pid_t pid, char **unit) {
1413 _cleanup_free_ char *cgroup = NULL;
1418 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1422 return cg_path_get_unit(cgroup, unit);
1426 * Skip session-*.scope, but require it to be there.
1428 static const char *skip_session(const char *p) {
1434 p += strspn(p, "/");
1436 n = strcspn(p, "/");
1437 if (n < strlen("session-x.scope"))
1440 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1441 char buf[n - 8 - 6 + 1];
1443 memcpy(buf, p + 8, n - 8 - 6);
1446 /* Note that session scopes never need unescaping,
1447 * since they cannot conflict with the kernel's own
1448 * names, hence we don't need to call cg_unescape()
1451 if (!session_id_valid(buf))
1455 p += strspn(p, "/");
1463 * Skip user@*.service, but require it to be there.
1465 static const char *skip_user_manager(const char *p) {
1471 p += strspn(p, "/");
1473 n = strcspn(p, "/");
1474 if (n < strlen("user@x.service"))
1477 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1478 char buf[n - 5 - 8 + 1];
1480 memcpy(buf, p + 5, n - 5 - 8);
1483 /* Note that user manager services never need unescaping,
1484 * since they cannot conflict with the kernel's own
1485 * names, hence we don't need to call cg_unescape()
1488 if (parse_uid(buf, NULL) < 0)
1492 p += strspn(p, "/");
1500 static const char *skip_user_prefix(const char *path) {
1505 /* Skip slices, if there are any */
1506 e = skip_slices(path);
1508 /* Skip the user manager, if it's in the path now... */
1509 t = skip_user_manager(e);
1513 /* Alternatively skip the user session if it is in the path... */
1514 return skip_session(e);
1517 int cg_path_get_user_unit(const char *path, char **ret) {
1523 t = skip_user_prefix(path);
1527 /* And from here on it looks pretty much the same as for a
1528 * system unit, hence let's use the same parser from here
1530 return cg_path_get_unit(t, ret);
1533 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1534 _cleanup_free_ char *cgroup = NULL;
1539 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1543 return cg_path_get_user_unit(cgroup, unit);
1546 int cg_path_get_machine_name(const char *path, char **machine) {
1547 _cleanup_free_ char *u = NULL;
1551 r = cg_path_get_unit(path, &u);
1555 sl = strjoina("/run/systemd/machines/unit:", u);
1556 return readlink_malloc(sl, machine);
1559 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1560 _cleanup_free_ char *cgroup = NULL;
1565 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1569 return cg_path_get_machine_name(cgroup, machine);
1573 int cg_path_get_session(const char *path, char **session) {
1574 #if 0 /// UNNEEDED by elogind
1575 _cleanup_free_ char *unit = NULL;
1581 r = cg_path_get_unit(path, &unit);
1585 start = startswith(unit, "session-");
1588 end = endswith(start, ".scope");
1593 if (!session_id_valid(start))
1596 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1597 wrinkle is that SESSION might be escaped. */
1598 const char *e, *n, *start;
1601 log_debug_elogind("path is \"%s\"", path);
1602 assert(path[0] == '/');
1605 n = strchrnul(e, '/');
1609 start = strndupa(e, n - e);
1610 start = cg_unescape(start);
1619 log_debug_elogind("found session: \"%s\"", start);
1630 int cg_pid_get_session(pid_t pid, char **session) {
1631 _cleanup_free_ char *cgroup = NULL;
1634 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1638 return cg_path_get_session(cgroup, session);
1641 #if 0 /// UNNEEDED by elogind
1642 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1643 _cleanup_free_ char *slice = NULL;
1649 r = cg_path_get_slice(path, &slice);
1653 start = startswith(slice, "user-");
1656 end = endswith(start, ".slice");
1661 if (parse_uid(start, uid) < 0)
1667 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1668 _cleanup_free_ char *cgroup = NULL;
1671 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1675 return cg_path_get_owner_uid(cgroup, uid);
1678 int cg_path_get_slice(const char *p, char **slice) {
1679 const char *e = NULL;
1684 /* Finds the right-most slice unit from the beginning, but
1685 * stops before we come to the first non-slice unit. */
1690 p += strspn(p, "/");
1692 n = strcspn(p, "/");
1693 if (!valid_slice_name(p, n)) {
1698 s = strdup("-.slice");
1706 return cg_path_decode_unit(e, slice);
1714 int cg_pid_get_slice(pid_t pid, char **slice) {
1715 _cleanup_free_ char *cgroup = NULL;
1720 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1724 return cg_path_get_slice(cgroup, slice);
1727 int cg_path_get_user_slice(const char *p, char **slice) {
1732 t = skip_user_prefix(p);
1736 /* And now it looks pretty much the same as for a system
1737 * slice, so let's just use the same parser from here on. */
1738 return cg_path_get_slice(t, slice);
1741 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1742 _cleanup_free_ char *cgroup = NULL;
1747 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1751 return cg_path_get_user_slice(cgroup, slice);
1755 char *cg_escape(const char *p) {
1756 bool need_prefix = false;
1758 /* This implements very minimal escaping for names to be used
1759 * as file names in the cgroup tree: any name which might
1760 * conflict with a kernel name or is prefixed with '_' is
1761 * prefixed with a '_'. That way, when reading cgroup names it
1762 * is sufficient to remove a single prefixing underscore if
1765 /* The return value of this function (unlike cg_unescape())
1771 streq(p, "notify_on_release") ||
1772 streq(p, "release_agent") ||
1773 streq(p, "tasks") ||
1774 startswith(p, "cgroup."))
1779 dot = strrchr(p, '.');
1784 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1787 n = cgroup_controller_to_string(c);
1792 if (memcmp(p, n, l) != 0)
1802 return strappend("_", p);
1807 char *cg_unescape(const char *p) {
1810 /* The return value of this function (unlike cg_escape())
1811 * doesn't need free()! */
1819 #define CONTROLLER_VALID \
1823 bool cg_controller_is_valid(const char *p) {
1829 s = startswith(p, "name=");
1833 if (*p == 0 || *p == '_')
1836 for (t = p; *t; t++)
1837 if (!strchr(CONTROLLER_VALID, *t))
1840 if (t - p > FILENAME_MAX)
1846 #if 0 /// UNNEEDED by elogind
1847 int cg_slice_to_path(const char *unit, char **ret) {
1848 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1855 if (streq(unit, "-.slice")) {
1865 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1868 if (!endswith(unit, ".slice"))
1871 r = unit_name_to_prefix(unit, &p);
1875 dash = strchr(p, '-');
1877 /* Don't allow initial dashes */
1882 _cleanup_free_ char *escaped = NULL;
1883 char n[dash - p + sizeof(".slice")];
1885 /* Don't allow trailing or double dashes */
1886 if (dash[1] == 0 || dash[1] == '-')
1889 strcpy(stpncpy(n, p, dash - p), ".slice");
1890 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1893 escaped = cg_escape(n);
1897 if (!strextend(&s, escaped, "/", NULL))
1900 dash = strchr(dash+1, '-');
1903 e = cg_escape(unit);
1907 if (!strextend(&s, e, NULL))
1917 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1918 _cleanup_free_ char *p = NULL;
1921 r = cg_get_path(controller, path, attribute, &p);
1925 return write_string_file(p, value, 0);
1928 #if 0 /// UNNEEDED by elogind
1929 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1930 _cleanup_free_ char *p = NULL;
1933 r = cg_get_path(controller, path, attribute, &p);
1937 return read_one_line_file(p, ret);
1940 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1944 /* This one will create a cgroup in our private tree, but also
1945 * duplicate it in the trees specified in mask, and remove it
1948 /* First create the cgroup in our own hierarchy. */
1949 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1953 /* If we are in the unified hierarchy, we are done now */
1954 unified = cg_unified();
1960 /* Otherwise, do the same in the other hierarchies */
1961 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1962 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1965 n = cgroup_controller_to_string(c);
1968 (void) cg_create(n, path);
1969 else if (supported & bit)
1970 (void) cg_trim(n, path, true);
1976 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1980 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
1984 unified = cg_unified();
1990 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1991 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1992 const char *p = NULL;
1994 if (!(supported & bit))
1998 p = path_callback(bit, userdata);
2003 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2009 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2014 SET_FOREACH(pidp, pids, i) {
2015 pid_t pid = PTR_TO_PID(pidp);
2018 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2019 if (q < 0 && r >= 0)
2026 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2030 if (!path_equal(from, to)) {
2031 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2036 unified = cg_unified();
2042 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2043 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2044 const char *p = NULL;
2046 if (!(supported & bit))
2050 p = to_callback(bit, userdata);
2055 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2061 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2065 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2069 unified = cg_unified();
2075 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2076 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2078 if (!(supported & bit))
2081 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2088 int cg_mask_supported(CGroupMask *ret) {
2089 CGroupMask mask = 0;
2092 /* Determines the mask of supported cgroup controllers. Only
2093 * includes controllers we can make sense of and that are
2094 * actually accessible. */
2096 unified = cg_unified();
2100 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2103 /* In the unified hierarchy we can read the supported
2104 * and accessible controllers from a the top-level
2105 * cgroup attribute */
2107 r = cg_get_root_path(&root);
2111 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2115 r = read_one_line_file(path, &controllers);
2121 _cleanup_free_ char *n = NULL;
2124 r = extract_first_word(&c, &n, NULL, 0);
2130 v = cgroup_controller_from_string(n);
2134 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2137 /* Currently, we only support the memory, io and pids
2138 * controller in the unified hierarchy, mask
2139 * everything else off. */
2140 mask &= CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2145 /* In the legacy hierarchy, we check whether which
2146 * hierarchies are mounted. */
2148 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2151 n = cgroup_controller_to_string(c);
2152 if (controller_is_accessible(n) >= 0)
2153 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2161 #if 0 /// UNNEEDED by elogind
2162 int cg_kernel_controllers(Set *controllers) {
2163 _cleanup_fclose_ FILE *f = NULL;
2167 assert(controllers);
2169 /* Determines the full list of kernel-known controllers. Might
2170 * include controllers we don't actually support, arbitrary
2171 * named hierarchies and controllers that aren't currently
2172 * accessible (because not mounted). */
2174 f = fopen("/proc/cgroups", "re");
2176 if (errno == ENOENT)
2181 /* Ignore the header line */
2182 (void) fgets(buf, sizeof(buf), f);
2189 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2194 if (ferror(f) && errno > 0)
2205 if (!cg_controller_is_valid(controller)) {
2210 r = set_consume(controllers, controller);
2219 static thread_local int unified_cache = -1;
2221 int cg_unified(void) {
2224 /* Checks if we support the unified hierarchy. Returns an
2225 * error when the cgroup hierarchies aren't mounted yet or we
2226 * have any other trouble determining if the unified hierarchy
2229 if (unified_cache >= 0)
2230 return unified_cache;
2232 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2235 #if 0 /// UNNEEDED by elogind
2236 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2237 unified_cache = true;
2238 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2240 /* elogind can not support the unified hierarchy as a controller,
2241 * so always assume a classical hierarchy.
2242 * If, ond only *if*, someone really wants to substitute systemd-login
2243 * in an environment managed by systemd with elogin, we might have to
2244 * add such a support. */
2245 if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2247 unified_cache = false;
2251 return unified_cache;
2254 #if 0 /// UNNEEDED by elogind
2255 void cg_unified_flush(void) {
2259 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2260 _cleanup_free_ char *fs = NULL;
2269 unified = cg_unified();
2272 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2275 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2279 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2280 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2283 if (!(supported & bit))
2286 n = cgroup_controller_to_string(c);
2288 char s[1 + strlen(n) + 1];
2290 s[0] = mask & bit ? '+' : '-';
2293 r = write_string_file(fs, s, 0);
2295 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2302 bool cg_is_unified_wanted(void) {
2303 static thread_local int wanted = -1;
2306 /* If the hierarchy is already mounted, then follow whatever
2307 * was chosen for it. */
2308 unified = cg_unified();
2312 /* Otherwise, let's see what the kernel command line has to
2313 * say. Since checking that is expensive, let's cache the
2318 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2320 return (wanted = true);
2322 _cleanup_free_ char *value = NULL;
2324 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2328 return (wanted = false);
2330 return (wanted = parse_boolean(value) > 0);
2334 bool cg_is_legacy_wanted(void) {
2335 return !cg_is_unified_wanted();
2338 bool cg_is_legacy_wanted(void) {
2343 #if 0 /// UNNEEDED by elogind
2344 int cg_weight_parse(const char *s, uint64_t *ret) {
2349 *ret = CGROUP_WEIGHT_INVALID;
2353 r = safe_atou64(s, &u);
2357 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2364 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2365 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2366 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2367 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2368 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2371 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2372 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2373 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2374 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2375 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2378 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2380 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2385 *ret = CGROUP_CPU_SHARES_INVALID;
2389 r = safe_atou64(s, &u);
2393 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2400 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2405 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2409 r = safe_atou64(s, &u);
2413 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2421 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2422 [CGROUP_CONTROLLER_CPU] = "cpu",
2423 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2424 [CGROUP_CONTROLLER_IO] = "io",
2425 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2426 [CGROUP_CONTROLLER_MEMORY] = "memory",
2427 [CGROUP_CONTROLLER_DEVICES] = "devices",
2428 [CGROUP_CONTROLLER_PIDS] = "pids",
2431 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);