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 (streq(de->d_name, ".") ||
188 streq(de->d_name, ".."))
191 b = strdup(de->d_name);
202 int cg_rmdir(const char *controller, const char *path) {
203 _cleanup_free_ char *p = NULL;
206 r = cg_get_path(controller, path, NULL, &p);
211 if (r < 0 && errno != ENOENT)
218 const char *controller,
223 cg_kill_log_func_t log_kill,
226 _cleanup_set_free_ Set *allocated_set = NULL;
233 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
234 * SIGCONT on SIGKILL. */
235 if (IN_SET(sig, SIGCONT, SIGKILL))
236 flags &= ~CGROUP_SIGCONT;
238 /* This goes through the tasks list and kills them all. This
239 * is repeated until no further processes are added to the
240 * tasks list, to properly handle forking processes */
243 s = allocated_set = set_new(NULL);
251 _cleanup_fclose_ FILE *f = NULL;
255 r = cg_enumerate_processes(controller, path, &f);
257 if (ret >= 0 && r != -ENOENT)
263 while ((r = cg_read_pid(f, &pid)) > 0) {
265 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
268 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
272 log_kill(pid, sig, userdata);
274 /* If we haven't killed this process yet, kill
276 if (kill(pid, sig) < 0) {
277 if (ret >= 0 && errno != ESRCH)
280 if (flags & CGROUP_SIGCONT)
281 (void) kill(pid, SIGCONT);
289 r = set_put(s, PID_TO_PTR(pid));
305 /* To avoid racing against processes which fork
306 * quicker than we can kill them we repeat this until
307 * no new pids need to be killed. */
314 int cg_kill_recursive(
315 const char *controller,
320 cg_kill_log_func_t log_kill,
323 _cleanup_set_free_ Set *allocated_set = NULL;
324 _cleanup_closedir_ DIR *d = NULL;
332 s = allocated_set = set_new(NULL);
337 ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
339 r = cg_enumerate_subgroups(controller, path, &d);
341 if (ret >= 0 && r != -ENOENT)
347 while ((r = cg_read_subgroup(d, &fn)) > 0) {
348 _cleanup_free_ char *p = NULL;
350 p = strjoin(path, "/", fn);
355 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
356 if (r != 0 && ret >= 0)
359 if (ret >= 0 && r < 0)
362 if (flags & CGROUP_REMOVE) {
363 r = cg_rmdir(controller, path);
364 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
379 _cleanup_set_free_ Set *s = NULL;
394 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
395 cfrom, pfrom, cto, pto,
396 (flags & CGROUP_IGNORE_SELF)
397 ? "ignoring self" : "watching self");
399 _cleanup_fclose_ FILE *f = NULL;
403 r = cg_enumerate_processes(cfrom, pfrom, &f);
405 if (ret >= 0 && r != -ENOENT)
411 while ((r = cg_read_pid(f, &pid)) > 0) {
413 /* This might do weird stuff if we aren't a
414 * single-threaded program. However, we
415 * luckily know we are not */
416 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
419 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
422 /* Ignore kernel threads. Since they can only
423 * exist in the root cgroup, we only check for
426 (isempty(pfrom) || path_equal(pfrom, "/")) &&
427 is_kernel_thread(pid) > 0)
430 r = cg_attach(cto, pto, pid);
432 if (ret >= 0 && r != -ESRCH)
439 r = set_put(s, PID_TO_PTR(pid));
459 int cg_migrate_recursive(
466 _cleanup_closedir_ DIR *d = NULL;
475 ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
477 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
479 if (ret >= 0 && r != -ENOENT)
485 while ((r = cg_read_subgroup(d, &fn)) > 0) {
486 _cleanup_free_ char *p = NULL;
488 p = strjoin(pfrom, "/", fn);
493 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
494 if (r != 0 && ret >= 0)
498 if (r < 0 && ret >= 0)
501 if (flags & CGROUP_REMOVE) {
502 r = cg_rmdir(cfrom, pfrom);
503 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
510 int cg_migrate_recursive_fallback(
524 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
526 char prefix[strlen(pto) + 1];
528 /* This didn't work? Then let's try all prefixes of the destination */
530 PATH_FOREACH_PREFIX(prefix, pto) {
533 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
542 static const char *controller_to_dirname(const char *controller) {
547 /* Converts a controller name to the directory name below
548 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
549 * just cuts off the name= prefixed used for named
550 * hierarchies, if it is specified. */
552 e = startswith(controller, "name=");
559 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
566 dn = controller_to_dirname(controller);
568 if (isempty(path) && isempty(suffix))
569 t = strappend("/sys/fs/cgroup/", dn);
570 else if (isempty(path))
571 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix);
572 else if (isempty(suffix))
573 t = strjoin("/sys/fs/cgroup/", dn, "/", path);
575 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix);
583 static int join_path_unified(const char *path, const char *suffix, char **fs) {
588 if (isempty(path) && isempty(suffix))
589 t = strdup("/sys/fs/cgroup");
590 else if (isempty(path))
591 t = strappend("/sys/fs/cgroup/", suffix);
592 else if (isempty(suffix))
593 t = strappend("/sys/fs/cgroup/", path);
595 t = strjoin("/sys/fs/cgroup/", path, "/", suffix);
603 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
611 /* If no controller is specified, we return the path
612 * *below* the controllers, without any prefix. */
614 if (!path && !suffix)
622 t = strjoin(path, "/", suffix);
626 *fs = path_kill_slashes(t);
630 if (!cg_controller_is_valid(controller))
633 unified = cg_all_unified();
638 r = join_path_unified(path, suffix, fs);
640 r = join_path_legacy(controller, path, suffix, fs);
644 path_kill_slashes(*fs);
648 static int controller_is_accessible(const char *controller) {
653 /* Checks whether a specific controller is accessible,
654 * i.e. its hierarchy mounted. In the unified hierarchy all
655 * controllers are considered accessible, except for the named
658 if (!cg_controller_is_valid(controller))
661 unified = cg_all_unified();
665 /* We don't support named hierarchies if we are using
666 * the unified hierarchy. */
668 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
671 if (startswith(controller, "name="))
677 dn = controller_to_dirname(controller);
678 cc = strjoina("/sys/fs/cgroup/", dn);
680 if (laccess(cc, F_OK) < 0)
687 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
693 /* Check if the specified controller is actually accessible */
694 r = controller_is_accessible(controller);
698 return cg_get_path(controller, path, suffix, fs);
701 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
706 if (typeflag != FTW_DP)
709 if (ftwbuf->level < 1)
716 int cg_trim(const char *controller, const char *path, bool delete_root) {
717 _cleanup_free_ char *fs = NULL;
722 r = cg_get_path(controller, path, NULL, &fs);
727 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
737 if (rmdir(fs) < 0 && errno != ENOENT)
744 int cg_create(const char *controller, const char *path) {
745 _cleanup_free_ char *fs = NULL;
748 r = cg_get_path_and_check(controller, path, NULL, &fs);
752 r = mkdir_parents(fs, 0755);
756 if (mkdir(fs, 0755) < 0) {
767 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
772 r = cg_create(controller, path);
776 q = cg_attach(controller, path, pid);
780 /* This does not remove the cgroup on failure */
784 int cg_attach(const char *controller, const char *path, pid_t pid) {
785 _cleanup_free_ char *fs = NULL;
786 char c[DECIMAL_STR_MAX(pid_t) + 2];
792 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
799 xsprintf(c, PID_FMT "\n", pid);
801 return write_string_file(fs, c, 0);
804 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
811 r = cg_attach(controller, path, pid);
813 char prefix[strlen(path) + 1];
815 /* This didn't work? Then let's try all prefixes of
818 PATH_FOREACH_PREFIX(prefix, path) {
821 q = cg_attach(controller, prefix, pid);
830 #if 0 /// UNNEEDED by elogind
831 int cg_set_group_access(
832 const char *controller,
838 _cleanup_free_ char *fs = NULL;
841 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
844 if (mode != MODE_INVALID)
847 r = cg_get_path(controller, path, NULL, &fs);
851 return chmod_and_chown(fs, mode, uid, gid);
854 int cg_set_task_access(
855 const char *controller,
861 _cleanup_free_ char *fs = NULL, *procs = NULL;
866 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
869 if (mode != MODE_INVALID)
872 r = cg_get_path(controller, path, "cgroup.procs", &fs);
876 r = chmod_and_chown(fs, mode, uid, gid);
880 unified = cg_unified(controller);
886 /* Compatibility, Always keep values for "tasks" in sync with
888 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
889 (void) chmod_and_chown(procs, mode, uid, gid);
894 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
895 _cleanup_free_ char *fs = NULL;
900 assert(value || size <= 0);
902 r = cg_get_path(controller, path, NULL, &fs);
906 if (setxattr(fs, name, value, size, flags) < 0)
912 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
913 _cleanup_free_ char *fs = NULL;
920 r = cg_get_path(controller, path, NULL, &fs);
924 n = getxattr(fs, name, value, size);
932 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
933 _cleanup_fclose_ FILE *f = NULL;
943 if (!cg_controller_is_valid(controller))
946 controller = SYSTEMD_CGROUP_CONTROLLER;
948 unified = cg_unified(controller);
952 cs = strlen(controller);
954 fs = procfs_file_alloca(pid, "cgroup");
955 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
956 pid, fs, controller);
959 return errno == ENOENT ? -ESRCH : -errno;
961 FOREACH_LINE(line, f, return -errno) {
967 e = startswith(line, "0:");
977 const char *word, *state;
980 l = strchr(line, ':');
990 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
991 if (k == cs && memcmp(word, controller, cs) == 0) {
1001 log_debug_elogind("Found %s:%s", line, e+1);
1013 int cg_install_release_agent(const char *controller, const char *agent) {
1014 _cleanup_free_ char *fs = NULL, *contents = NULL;
1020 unified = cg_unified(controller);
1023 if (unified) /* doesn't apply to unified hierarchy */
1026 r = cg_get_path(controller, NULL, "release_agent", &fs);
1030 r = read_one_line_file(fs, &contents);
1034 sc = strstrip(contents);
1036 r = write_string_file(fs, agent, 0);
1039 } else if (!path_equal(sc, agent))
1043 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1047 contents = mfree(contents);
1048 r = read_one_line_file(fs, &contents);
1052 sc = strstrip(contents);
1053 if (streq(sc, "0")) {
1054 r = write_string_file(fs, "1", 0);
1061 if (!streq(sc, "1"))
1067 int cg_uninstall_release_agent(const char *controller) {
1068 _cleanup_free_ char *fs = NULL;
1071 unified = cg_unified(controller);
1074 if (unified) /* Doesn't apply to unified hierarchy */
1077 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1081 r = write_string_file(fs, "0", 0);
1087 r = cg_get_path(controller, NULL, "release_agent", &fs);
1091 r = write_string_file(fs, "", 0);
1098 int cg_is_empty(const char *controller, const char *path) {
1099 _cleanup_fclose_ FILE *f = NULL;
1105 r = cg_enumerate_processes(controller, path, &f);
1111 r = cg_read_pid(f, &pid);
1118 int cg_is_empty_recursive(const char *controller, const char *path) {
1123 /* The root cgroup is always populated */
1124 if (controller && (isempty(path) || path_equal(path, "/")))
1127 unified = cg_unified(controller);
1132 _cleanup_free_ char *t = NULL;
1134 /* On the unified hierarchy we can check empty state
1135 * via the "populated" attribute of "cgroup.events". */
1137 r = cg_read_event(controller, path, "populated", &t);
1141 return streq(t, "0");
1143 _cleanup_closedir_ DIR *d = NULL;
1146 r = cg_is_empty(controller, path);
1150 r = cg_enumerate_subgroups(controller, path, &d);
1156 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1157 _cleanup_free_ char *p = NULL;
1159 p = strjoin(path, "/", fn);
1164 r = cg_is_empty_recursive(controller, p);
1175 int cg_split_spec(const char *spec, char **controller, char **path) {
1176 char *t = NULL, *u = NULL;
1182 if (!path_is_safe(spec))
1190 *path = path_kill_slashes(t);
1199 e = strchr(spec, ':');
1201 if (!cg_controller_is_valid(spec))
1218 t = strndup(spec, e-spec);
1221 if (!cg_controller_is_valid(t)) {
1235 if (!path_is_safe(u) ||
1236 !path_is_absolute(u)) {
1242 path_kill_slashes(u);
1258 int cg_mangle_path(const char *path, char **result) {
1259 _cleanup_free_ char *c = NULL, *p = NULL;
1266 /* First, check if it already is a filesystem path */
1267 if (path_startswith(path, "/sys/fs/cgroup")) {
1273 *result = path_kill_slashes(t);
1277 /* Otherwise, treat it as cg spec */
1278 r = cg_split_spec(path, &c, &p);
1282 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1285 int cg_get_root_path(char **path) {
1286 #if 0 /// elogind does not support systemd scopes and slices
1292 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1296 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1298 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1300 e = endswith(p, "/system"); /* even more legacy */
1308 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1312 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1313 _cleanup_free_ char *rt = NULL;
1321 /* If the root was specified let's use that, otherwise
1322 * let's determine it from PID 1 */
1324 r = cg_get_root_path(&rt);
1329 log_debug_elogind("Determined root path: \"%s\"", root);
1332 p = path_startswith(cgroup, root);
1333 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1334 if (p && p > cgroup)
1336 if (p && p[0] && (p > cgroup))
1345 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1346 _cleanup_free_ char *raw = NULL;
1353 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1357 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1358 raw, pid, root ? root : "NULL");
1359 r = cg_shift_path(raw, root, &c);
1375 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1380 #if 0 /// UNNEEDED by elogind
1381 int cg_path_decode_unit(const char *cgroup, char **unit) {
1388 n = strcspn(cgroup, "/");
1392 c = strndupa(cgroup, n);
1395 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1406 static bool valid_slice_name(const char *p, size_t n) {
1411 if (n < strlen("x.slice"))
1414 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1420 c = cg_unescape(buf);
1422 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1428 static const char *skip_slices(const char *p) {
1431 /* Skips over all slice assignments */
1436 p += strspn(p, "/");
1438 n = strcspn(p, "/");
1439 if (!valid_slice_name(p, n))
1446 int cg_path_get_unit(const char *path, char **ret) {
1454 e = skip_slices(path);
1456 r = cg_path_decode_unit(e, &unit);
1460 /* We skipped over the slices, don't accept any now */
1461 if (endswith(unit, ".slice")) {
1470 int cg_pid_get_unit(pid_t pid, char **unit) {
1471 _cleanup_free_ char *cgroup = NULL;
1476 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1480 return cg_path_get_unit(cgroup, unit);
1484 * Skip session-*.scope, but require it to be there.
1486 static const char *skip_session(const char *p) {
1492 p += strspn(p, "/");
1494 n = strcspn(p, "/");
1495 if (n < strlen("session-x.scope"))
1498 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1499 char buf[n - 8 - 6 + 1];
1501 memcpy(buf, p + 8, n - 8 - 6);
1504 /* Note that session scopes never need unescaping,
1505 * since they cannot conflict with the kernel's own
1506 * names, hence we don't need to call cg_unescape()
1509 if (!session_id_valid(buf))
1513 p += strspn(p, "/");
1521 * Skip user@*.service, but require it to be there.
1523 static const char *skip_user_manager(const char *p) {
1529 p += strspn(p, "/");
1531 n = strcspn(p, "/");
1532 if (n < strlen("user@x.service"))
1535 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1536 char buf[n - 5 - 8 + 1];
1538 memcpy(buf, p + 5, n - 5 - 8);
1541 /* Note that user manager services never need unescaping,
1542 * since they cannot conflict with the kernel's own
1543 * names, hence we don't need to call cg_unescape()
1546 if (parse_uid(buf, NULL) < 0)
1550 p += strspn(p, "/");
1558 static const char *skip_user_prefix(const char *path) {
1563 /* Skip slices, if there are any */
1564 e = skip_slices(path);
1566 /* Skip the user manager, if it's in the path now... */
1567 t = skip_user_manager(e);
1571 /* Alternatively skip the user session if it is in the path... */
1572 return skip_session(e);
1575 int cg_path_get_user_unit(const char *path, char **ret) {
1581 t = skip_user_prefix(path);
1585 /* And from here on it looks pretty much the same as for a
1586 * system unit, hence let's use the same parser from here
1588 return cg_path_get_unit(t, ret);
1591 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1592 _cleanup_free_ char *cgroup = NULL;
1597 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1601 return cg_path_get_user_unit(cgroup, unit);
1604 int cg_path_get_machine_name(const char *path, char **machine) {
1605 _cleanup_free_ char *u = NULL;
1609 r = cg_path_get_unit(path, &u);
1613 sl = strjoina("/run/systemd/machines/unit:", u);
1614 return readlink_malloc(sl, machine);
1617 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1618 _cleanup_free_ char *cgroup = NULL;
1623 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1627 return cg_path_get_machine_name(cgroup, machine);
1631 int cg_path_get_session(const char *path, char **session) {
1632 #if 0 /// UNNEEDED by elogind
1633 _cleanup_free_ char *unit = NULL;
1639 r = cg_path_get_unit(path, &unit);
1643 start = startswith(unit, "session-");
1646 end = endswith(start, ".scope");
1651 if (!session_id_valid(start))
1654 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1655 wrinkle is that SESSION might be escaped. */
1656 const char *e, *n, *start;
1659 log_debug_elogind("path is \"%s\"", path);
1660 assert(path[0] == '/');
1663 n = strchrnul(e, '/');
1667 start = strndupa(e, n - e);
1668 start = cg_unescape(start);
1677 log_debug_elogind("found session: \"%s\"", start);
1688 int cg_pid_get_session(pid_t pid, char **session) {
1689 _cleanup_free_ char *cgroup = NULL;
1692 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1696 return cg_path_get_session(cgroup, session);
1699 #if 0 /// UNNEEDED by elogind
1700 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1701 _cleanup_free_ char *slice = NULL;
1707 r = cg_path_get_slice(path, &slice);
1711 start = startswith(slice, "user-");
1714 end = endswith(start, ".slice");
1719 if (parse_uid(start, uid) < 0)
1725 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1726 _cleanup_free_ char *cgroup = NULL;
1729 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1733 return cg_path_get_owner_uid(cgroup, uid);
1736 int cg_path_get_slice(const char *p, char **slice) {
1737 const char *e = NULL;
1742 /* Finds the right-most slice unit from the beginning, but
1743 * stops before we come to the first non-slice unit. */
1748 p += strspn(p, "/");
1750 n = strcspn(p, "/");
1751 if (!valid_slice_name(p, n)) {
1756 s = strdup(SPECIAL_ROOT_SLICE);
1764 return cg_path_decode_unit(e, slice);
1772 int cg_pid_get_slice(pid_t pid, char **slice) {
1773 _cleanup_free_ char *cgroup = NULL;
1778 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1782 return cg_path_get_slice(cgroup, slice);
1785 int cg_path_get_user_slice(const char *p, char **slice) {
1790 t = skip_user_prefix(p);
1794 /* And now it looks pretty much the same as for a system
1795 * slice, so let's just use the same parser from here on. */
1796 return cg_path_get_slice(t, slice);
1799 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1800 _cleanup_free_ char *cgroup = NULL;
1805 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1809 return cg_path_get_user_slice(cgroup, slice);
1813 char *cg_escape(const char *p) {
1814 bool need_prefix = false;
1816 /* This implements very minimal escaping for names to be used
1817 * as file names in the cgroup tree: any name which might
1818 * conflict with a kernel name or is prefixed with '_' is
1819 * prefixed with a '_'. That way, when reading cgroup names it
1820 * is sufficient to remove a single prefixing underscore if
1823 /* The return value of this function (unlike cg_unescape())
1829 streq(p, "notify_on_release") ||
1830 streq(p, "release_agent") ||
1831 streq(p, "tasks") ||
1832 startswith(p, "cgroup."))
1837 dot = strrchr(p, '.');
1842 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1845 n = cgroup_controller_to_string(c);
1850 if (memcmp(p, n, l) != 0)
1860 return strappend("_", p);
1865 char *cg_unescape(const char *p) {
1868 /* The return value of this function (unlike cg_escape())
1869 * doesn't need free()! */
1877 #define CONTROLLER_VALID \
1881 bool cg_controller_is_valid(const char *p) {
1887 s = startswith(p, "name=");
1891 if (*p == 0 || *p == '_')
1894 for (t = p; *t; t++)
1895 if (!strchr(CONTROLLER_VALID, *t))
1898 if (t - p > FILENAME_MAX)
1904 #if 0 /// UNNEEDED by elogind
1905 int cg_slice_to_path(const char *unit, char **ret) {
1906 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1913 if (streq(unit, SPECIAL_ROOT_SLICE)) {
1923 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1926 if (!endswith(unit, ".slice"))
1929 r = unit_name_to_prefix(unit, &p);
1933 dash = strchr(p, '-');
1935 /* Don't allow initial dashes */
1940 _cleanup_free_ char *escaped = NULL;
1941 char n[dash - p + sizeof(".slice")];
1943 /* Don't allow trailing or double dashes */
1944 if (dash[1] == 0 || dash[1] == '-')
1947 strcpy(stpncpy(n, p, dash - p), ".slice");
1948 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1951 escaped = cg_escape(n);
1955 if (!strextend(&s, escaped, "/", NULL))
1958 dash = strchr(dash+1, '-');
1961 e = cg_escape(unit);
1965 if (!strextend(&s, e, NULL))
1975 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1976 _cleanup_free_ char *p = NULL;
1979 r = cg_get_path(controller, path, attribute, &p);
1983 return write_string_file(p, value, 0);
1986 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1987 _cleanup_free_ char *p = NULL;
1990 r = cg_get_path(controller, path, attribute, &p);
1994 return read_one_line_file(p, ret);
1997 #if 0 /// UNNEEDED by elogind
1998 int cg_get_keyed_attribute(const char *controller, const char *path, const char *attribute, const char **keys, char **values) {
1999 _cleanup_free_ char *filename = NULL, *content = NULL;
2003 for (i = 0; keys[i]; i++)
2006 r = cg_get_path(controller, path, attribute, &filename);
2010 r = read_full_file(filename, &content, NULL);
2015 while ((line = strsep(&p, "\n"))) {
2018 key = strsep(&line, " ");
2020 for (i = 0; keys[i]; i++) {
2021 if (streq(key, keys[i])) {
2022 values[i] = strdup(line);
2028 for (i = 0; keys[i]; i++) {
2030 for (i = 0; keys[i]; i++) {
2041 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2045 /* This one will create a cgroup in our private tree, but also
2046 * duplicate it in the trees specified in mask, and remove it
2049 /* First create the cgroup in our own hierarchy. */
2050 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2054 /* If we are in the unified hierarchy, we are done now */
2055 unified = cg_all_unified();
2061 /* Otherwise, do the same in the other hierarchies */
2062 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2063 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2066 n = cgroup_controller_to_string(c);
2069 (void) cg_create(n, path);
2070 else if (supported & bit)
2071 (void) cg_trim(n, path, true);
2077 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2081 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2085 unified = cg_all_unified();
2091 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2092 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2093 const char *p = NULL;
2095 if (!(supported & bit))
2099 p = path_callback(bit, userdata);
2104 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2110 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2115 SET_FOREACH(pidp, pids, i) {
2116 pid_t pid = PTR_TO_PID(pidp);
2119 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2120 if (q < 0 && r >= 0)
2127 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2131 if (!path_equal(from, to)) {
2132 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2137 unified = cg_all_unified();
2143 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2144 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2145 const char *p = NULL;
2147 if (!(supported & bit))
2151 p = to_callback(bit, userdata);
2156 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2162 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2166 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2170 unified = cg_all_unified();
2176 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2177 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2179 if (!(supported & bit))
2182 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2189 int cg_mask_supported(CGroupMask *ret) {
2190 CGroupMask mask = 0;
2193 /* Determines the mask of supported cgroup controllers. Only
2194 * includes controllers we can make sense of and that are
2195 * actually accessible. */
2197 unified = cg_all_unified();
2201 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2204 /* In the unified hierarchy we can read the supported
2205 * and accessible controllers from a the top-level
2206 * cgroup attribute */
2208 r = cg_get_root_path(&root);
2212 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2216 r = read_one_line_file(path, &controllers);
2222 _cleanup_free_ char *n = NULL;
2225 r = extract_first_word(&c, &n, NULL, 0);
2231 v = cgroup_controller_from_string(n);
2235 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2238 /* Currently, we support the cpu, memory, io and pids
2239 * controller in the unified hierarchy, mask
2240 * everything else off. */
2241 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2246 /* In the legacy hierarchy, we check whether which
2247 * hierarchies are mounted. */
2249 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2252 n = cgroup_controller_to_string(c);
2253 if (controller_is_accessible(n) >= 0)
2254 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2262 #if 0 /// UNNEEDED by elogind
2263 int cg_kernel_controllers(Set *controllers) {
2264 _cleanup_fclose_ FILE *f = NULL;
2268 assert(controllers);
2270 /* Determines the full list of kernel-known controllers. Might
2271 * include controllers we don't actually support, arbitrary
2272 * named hierarchies and controllers that aren't currently
2273 * accessible (because not mounted). */
2275 f = fopen("/proc/cgroups", "re");
2277 if (errno == ENOENT)
2282 /* Ignore the header line */
2283 (void) fgets(buf, sizeof(buf), f);
2290 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2295 if (ferror(f) && errno > 0)
2306 if (!cg_controller_is_valid(controller)) {
2311 r = set_consume(controllers, controller);
2320 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2322 static int cg_update_unified(void) {
2326 /* Checks if we support the unified hierarchy. Returns an
2327 * error when the cgroup hierarchies aren't mounted yet or we
2328 * have any other trouble determining if the unified hierarchy
2331 if (unified_cache >= CGROUP_UNIFIED_NONE)
2334 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2337 #if 0 /// UNNEEDED by elogind
2338 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2339 unified_cache = CGROUP_UNIFIED_ALL;
2340 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2341 if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2344 unified_cache = F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC) ?
2345 CGROUP_UNIFIED_SYSTEMD : CGROUP_UNIFIED_NONE;
2349 /* elogind can not support the unified hierarchy as a controller,
2350 * so always assume a classical hierarchy.
2351 * If, and only *if*, someone really wants to substitute systemd-login
2352 * in an environment managed by systemd with elogind, we might have to
2353 * add such a support. */
2354 unified_cache = CGROUP_UNIFIED_NONE;
2360 int cg_unified(const char *controller) {
2364 r = cg_update_unified();
2368 if (streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER))
2369 return unified_cache >= CGROUP_UNIFIED_SYSTEMD;
2371 return unified_cache >= CGROUP_UNIFIED_ALL;
2374 int cg_all_unified(void) {
2376 return cg_unified(NULL);
2379 #if 0 /// UNNEEDED by elogind
2380 void cg_unified_flush(void) {
2381 unified_cache = CGROUP_UNIFIED_UNKNOWN;
2384 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2385 _cleanup_free_ char *fs = NULL;
2394 unified = cg_all_unified();
2397 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2400 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2404 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2405 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2408 if (!(supported & bit))
2411 n = cgroup_controller_to_string(c);
2413 char s[1 + strlen(n) + 1];
2415 s[0] = mask & bit ? '+' : '-';
2418 r = write_string_file(fs, s, 0);
2420 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2427 bool cg_is_unified_wanted(void) {
2428 static thread_local int wanted = -1;
2431 /* If the hierarchy is already mounted, then follow whatever
2432 * was chosen for it. */
2433 unified = cg_all_unified();
2437 /* Otherwise, let's see what the kernel command line has to
2438 * say. Since checking that is expensive, let's cache the
2443 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2445 return (wanted = true);
2447 _cleanup_free_ char *value = NULL;
2449 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2453 return (wanted = false);
2455 return (wanted = parse_boolean(value) > 0);
2459 bool cg_is_legacy_wanted(void) {
2460 return !cg_is_unified_wanted();
2463 bool cg_is_unified_systemd_controller_wanted(void) {
2464 static thread_local int wanted = -1;
2467 /* If the unified hierarchy is requested in full, no need to
2468 * bother with this. */
2469 if (cg_is_unified_wanted())
2472 /* If the hierarchy is already mounted, then follow whatever
2473 * was chosen for it. */
2474 unified = cg_unified(SYSTEMD_CGROUP_CONTROLLER);
2478 /* Otherwise, let's see what the kernel command line has to
2479 * say. Since checking that is expensive, let's cache the
2484 r = get_proc_cmdline_key("systemd.legacy_systemd_cgroup_controller", NULL);
2488 _cleanup_free_ char *value = NULL;
2490 r = get_proc_cmdline_key("systemd.legacy_systemd_cgroup_controller=", &value);
2497 wanted = parse_boolean(value) <= 0;
2503 bool cg_is_legacy_systemd_controller_wanted(void) {
2504 return cg_is_legacy_wanted() && !cg_is_unified_systemd_controller_wanted();
2507 bool cg_is_legacy_wanted(void) {
2512 #if 0 /// UNNEEDED by elogind
2513 int cg_weight_parse(const char *s, uint64_t *ret) {
2518 *ret = CGROUP_WEIGHT_INVALID;
2522 r = safe_atou64(s, &u);
2526 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2533 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2534 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2535 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2536 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2537 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2540 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2541 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2542 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2543 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2544 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2547 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2549 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2554 *ret = CGROUP_CPU_SHARES_INVALID;
2558 r = safe_atou64(s, &u);
2562 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2569 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2574 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2578 r = safe_atou64(s, &u);
2582 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2590 bool is_cgroup_fs(const struct statfs *s) {
2591 return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2592 is_fs_type(s, CGROUP2_SUPER_MAGIC);
2595 bool fd_is_cgroup_fs(int fd) {
2598 if (fstatfs(fd, &s) < 0)
2601 return is_cgroup_fs(&s);
2604 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2605 [CGROUP_CONTROLLER_CPU] = "cpu",
2606 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2607 [CGROUP_CONTROLLER_IO] = "io",
2608 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2609 [CGROUP_CONTROLLER_MEMORY] = "memory",
2610 [CGROUP_CONTROLLER_DEVICES] = "devices",
2611 [CGROUP_CONTROLLER_PIDS] = "pids",
2614 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);