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)
200 int cg_kill(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, Set *s) {
201 _cleanup_set_free_ Set *allocated_set = NULL;
208 /* This goes through the tasks list and kills them all. This
209 * is repeated until no further processes are added to the
210 * tasks list, to properly handle forking processes */
213 s = allocated_set = set_new(NULL);
221 _cleanup_fclose_ FILE *f = NULL;
225 r = cg_enumerate_processes(controller, path, &f);
227 if (ret >= 0 && r != -ENOENT)
233 while ((r = cg_read_pid(f, &pid)) > 0) {
235 if (ignore_self && pid == my_pid)
238 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
241 /* If we haven't killed this process yet, kill
243 if (kill(pid, sig) < 0) {
244 if (ret >= 0 && errno != ESRCH)
247 if (sigcont && sig != SIGKILL)
248 (void) kill(pid, SIGCONT);
256 r = set_put(s, PID_TO_PTR(pid));
272 /* To avoid racing against processes which fork
273 * quicker than we can kill them we repeat this until
274 * no new pids need to be killed. */
281 int cg_kill_recursive(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, bool rem, Set *s) {
282 _cleanup_set_free_ Set *allocated_set = NULL;
283 _cleanup_closedir_ DIR *d = NULL;
291 s = allocated_set = set_new(NULL);
296 ret = cg_kill(controller, path, sig, sigcont, ignore_self, s);
298 r = cg_enumerate_subgroups(controller, path, &d);
300 if (ret >= 0 && r != -ENOENT)
306 while ((r = cg_read_subgroup(d, &fn)) > 0) {
307 _cleanup_free_ char *p = NULL;
309 p = strjoin(path, "/", fn, NULL);
314 r = cg_kill_recursive(controller, p, sig, sigcont, ignore_self, rem, s);
315 if (r != 0 && ret >= 0)
319 if (ret >= 0 && r < 0)
323 r = cg_rmdir(controller, path);
324 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
331 int cg_migrate(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self) {
333 _cleanup_set_free_ Set *s = NULL;
348 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
349 cfrom, pfrom, cto, pto,
350 ignore_self ? "ignoring self" : "watching self");
353 _cleanup_fclose_ FILE *f = NULL;
357 r = cg_enumerate_processes(cfrom, pfrom, &f);
359 if (ret >= 0 && r != -ENOENT)
365 while ((r = cg_read_pid(f, &pid)) > 0) {
367 /* This might do weird stuff if we aren't a
368 * single-threaded program. However, we
369 * luckily know we are not */
370 if (ignore_self && pid == my_pid)
373 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
376 /* Ignore kernel threads. Since they can only
377 * exist in the root cgroup, we only check for
380 (isempty(pfrom) || path_equal(pfrom, "/")) &&
381 is_kernel_thread(pid) > 0)
384 r = cg_attach(cto, pto, pid);
386 if (ret >= 0 && r != -ESRCH)
393 r = set_put(s, PID_TO_PTR(pid));
413 int cg_migrate_recursive(
421 _cleanup_closedir_ DIR *d = NULL;
430 ret = cg_migrate(cfrom, pfrom, cto, pto, ignore_self);
432 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
434 if (ret >= 0 && r != -ENOENT)
440 while ((r = cg_read_subgroup(d, &fn)) > 0) {
441 _cleanup_free_ char *p = NULL;
443 p = strjoin(pfrom, "/", fn, NULL);
448 r = cg_migrate_recursive(cfrom, p, cto, pto, ignore_self, rem);
449 if (r != 0 && ret >= 0)
453 if (r < 0 && ret >= 0)
457 r = cg_rmdir(cfrom, pfrom);
458 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
465 int cg_migrate_recursive_fallback(
480 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, ignore_self, rem);
482 char prefix[strlen(pto) + 1];
484 /* This didn't work? Then let's try all prefixes of the destination */
486 PATH_FOREACH_PREFIX(prefix, pto) {
489 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, ignore_self, rem);
498 static const char *controller_to_dirname(const char *controller) {
503 /* Converts a controller name to the directory name below
504 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
505 * just cuts off the name= prefixed used for named
506 * hierarchies, if it is specified. */
508 e = startswith(controller, "name=");
515 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
522 dn = controller_to_dirname(controller);
524 if (isempty(path) && isempty(suffix))
525 t = strappend("/sys/fs/cgroup/", dn);
526 else if (isempty(path))
527 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
528 else if (isempty(suffix))
529 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
531 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
539 static int join_path_unified(const char *path, const char *suffix, char **fs) {
544 if (isempty(path) && isempty(suffix))
545 t = strdup("/sys/fs/cgroup");
546 else if (isempty(path))
547 t = strappend("/sys/fs/cgroup/", suffix);
548 else if (isempty(suffix))
549 t = strappend("/sys/fs/cgroup/", path);
551 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
559 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
567 /* If no controller is specified, we return the path
568 * *below* the controllers, without any prefix. */
570 if (!path && !suffix)
578 t = strjoin(path, "/", suffix, NULL);
582 *fs = path_kill_slashes(t);
586 if (!cg_controller_is_valid(controller))
589 unified = cg_unified();
594 r = join_path_unified(path, suffix, fs);
596 r = join_path_legacy(controller, path, suffix, fs);
600 path_kill_slashes(*fs);
604 static int controller_is_accessible(const char *controller) {
609 /* Checks whether a specific controller is accessible,
610 * i.e. its hierarchy mounted. In the unified hierarchy all
611 * controllers are considered accessible, except for the named
614 if (!cg_controller_is_valid(controller))
617 unified = cg_unified();
621 /* We don't support named hierarchies if we are using
622 * the unified hierarchy. */
624 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
627 if (startswith(controller, "name="))
633 dn = controller_to_dirname(controller);
634 cc = strjoina("/sys/fs/cgroup/", dn);
636 if (laccess(cc, F_OK) < 0)
643 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
649 /* Check if the specified controller is actually accessible */
650 r = controller_is_accessible(controller);
654 return cg_get_path(controller, path, suffix, fs);
657 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
662 if (typeflag != FTW_DP)
665 if (ftwbuf->level < 1)
672 int cg_trim(const char *controller, const char *path, bool delete_root) {
673 _cleanup_free_ char *fs = NULL;
678 r = cg_get_path(controller, path, NULL, &fs);
683 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
693 if (rmdir(fs) < 0 && errno != ENOENT)
700 int cg_create(const char *controller, const char *path) {
701 _cleanup_free_ char *fs = NULL;
704 r = cg_get_path_and_check(controller, path, NULL, &fs);
708 r = mkdir_parents(fs, 0755);
712 if (mkdir(fs, 0755) < 0) {
723 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
728 r = cg_create(controller, path);
732 q = cg_attach(controller, path, pid);
736 /* This does not remove the cgroup on failure */
740 int cg_attach(const char *controller, const char *path, pid_t pid) {
741 _cleanup_free_ char *fs = NULL;
742 char c[DECIMAL_STR_MAX(pid_t) + 2];
748 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
755 xsprintf(c, PID_FMT "\n", pid);
757 return write_string_file(fs, c, 0);
760 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
767 r = cg_attach(controller, path, pid);
769 char prefix[strlen(path) + 1];
771 /* This didn't work? Then let's try all prefixes of
774 PATH_FOREACH_PREFIX(prefix, path) {
777 q = cg_attach(controller, prefix, pid);
786 #if 0 /// UNNEEDED by elogind
787 int cg_set_group_access(
788 const char *controller,
794 _cleanup_free_ char *fs = NULL;
797 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
800 if (mode != MODE_INVALID)
803 r = cg_get_path(controller, path, NULL, &fs);
807 return chmod_and_chown(fs, mode, uid, gid);
810 int cg_set_task_access(
811 const char *controller,
817 _cleanup_free_ char *fs = NULL, *procs = NULL;
822 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
825 if (mode != MODE_INVALID)
828 r = cg_get_path(controller, path, "cgroup.procs", &fs);
832 r = chmod_and_chown(fs, mode, uid, gid);
836 unified = cg_unified();
842 /* Compatibility, Always keep values for "tasks" in sync with
844 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
845 (void) chmod_and_chown(procs, mode, uid, gid);
851 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
852 _cleanup_fclose_ FILE *f = NULL;
861 unified = cg_unified();
866 if (!cg_controller_is_valid(controller))
869 controller = SYSTEMD_CGROUP_CONTROLLER;
871 cs = strlen(controller);
874 fs = procfs_file_alloca(pid, "cgroup");
875 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
876 pid, fs, controller);
879 return errno == ENOENT ? -ESRCH : -errno;
881 FOREACH_LINE(line, f, return -errno) {
887 e = startswith(line, "0:");
897 const char *word, *state;
900 l = strchr(line, ':');
910 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
911 if (k == cs && memcmp(word, controller, cs) == 0) {
921 log_debug_elogind("Found %s:%s", line, e+1);
933 int cg_install_release_agent(const char *controller, const char *agent) {
934 _cleanup_free_ char *fs = NULL, *contents = NULL;
940 unified = cg_unified();
943 if (unified) /* doesn't apply to unified hierarchy */
946 r = cg_get_path(controller, NULL, "release_agent", &fs);
950 r = read_one_line_file(fs, &contents);
954 sc = strstrip(contents);
956 r = write_string_file(fs, agent, 0);
959 } else if (!path_equal(sc, agent))
963 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
967 contents = mfree(contents);
968 r = read_one_line_file(fs, &contents);
972 sc = strstrip(contents);
973 if (streq(sc, "0")) {
974 r = write_string_file(fs, "1", 0);
987 int cg_uninstall_release_agent(const char *controller) {
988 _cleanup_free_ char *fs = NULL;
991 unified = cg_unified();
994 if (unified) /* Doesn't apply to unified hierarchy */
997 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1001 r = write_string_file(fs, "0", 0);
1007 r = cg_get_path(controller, NULL, "release_agent", &fs);
1011 r = write_string_file(fs, "", 0);
1018 int cg_is_empty(const char *controller, const char *path) {
1019 _cleanup_fclose_ FILE *f = NULL;
1025 r = cg_enumerate_processes(controller, path, &f);
1031 r = cg_read_pid(f, &pid);
1038 int cg_is_empty_recursive(const char *controller, const char *path) {
1043 /* The root cgroup is always populated */
1044 if (controller && (isempty(path) || path_equal(path, "/")))
1047 unified = cg_unified();
1052 _cleanup_free_ char *t = NULL;
1054 /* On the unified hierarchy we can check empty state
1055 * via the "populated" attribute of "cgroup.events". */
1057 r = cg_read_event(controller, path, "populated", &t);
1061 return streq(t, "0");
1063 _cleanup_closedir_ DIR *d = NULL;
1066 r = cg_is_empty(controller, path);
1070 r = cg_enumerate_subgroups(controller, path, &d);
1076 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1077 _cleanup_free_ char *p = NULL;
1079 p = strjoin(path, "/", fn, NULL);
1084 r = cg_is_empty_recursive(controller, p);
1095 int cg_split_spec(const char *spec, char **controller, char **path) {
1096 char *t = NULL, *u = NULL;
1102 if (!path_is_safe(spec))
1110 *path = path_kill_slashes(t);
1119 e = strchr(spec, ':');
1121 if (!cg_controller_is_valid(spec))
1138 t = strndup(spec, e-spec);
1141 if (!cg_controller_is_valid(t)) {
1155 if (!path_is_safe(u) ||
1156 !path_is_absolute(u)) {
1162 path_kill_slashes(u);
1178 int cg_mangle_path(const char *path, char **result) {
1179 _cleanup_free_ char *c = NULL, *p = NULL;
1186 /* First, check if it already is a filesystem path */
1187 if (path_startswith(path, "/sys/fs/cgroup")) {
1193 *result = path_kill_slashes(t);
1197 /* Otherwise, treat it as cg spec */
1198 r = cg_split_spec(path, &c, &p);
1202 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1205 int cg_get_root_path(char **path) {
1206 #if 0 /// elogind does not support systemd scopes and slices
1212 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1216 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1218 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1220 e = endswith(p, "/system"); /* even more legacy */
1228 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1232 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1233 _cleanup_free_ char *rt = NULL;
1241 /* If the root was specified let's use that, otherwise
1242 * let's determine it from PID 1 */
1244 r = cg_get_root_path(&rt);
1249 log_debug_elogind("Determined root path: \"%s\"", root);
1252 p = path_startswith(cgroup, root);
1253 if (p && p[0] && (p > cgroup))
1261 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1262 _cleanup_free_ char *raw = NULL;
1269 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1273 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1274 raw, pid, root ? root : "NULL");
1275 r = cg_shift_path(raw, root, &c);
1291 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1296 #if 0 /// UNNEEDED by elogind
1297 int cg_path_decode_unit(const char *cgroup, char **unit){
1304 n = strcspn(cgroup, "/");
1308 c = strndupa(cgroup, n);
1311 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1322 static bool valid_slice_name(const char *p, size_t n) {
1327 if (n < strlen("x.slice"))
1330 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1336 c = cg_unescape(buf);
1338 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1344 static const char *skip_slices(const char *p) {
1347 /* Skips over all slice assignments */
1352 p += strspn(p, "/");
1354 n = strcspn(p, "/");
1355 if (!valid_slice_name(p, n))
1362 int cg_path_get_unit(const char *path, char **ret) {
1370 e = skip_slices(path);
1372 r = cg_path_decode_unit(e, &unit);
1376 /* We skipped over the slices, don't accept any now */
1377 if (endswith(unit, ".slice")) {
1386 int cg_pid_get_unit(pid_t pid, char **unit) {
1387 _cleanup_free_ char *cgroup = NULL;
1392 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1396 return cg_path_get_unit(cgroup, unit);
1400 * Skip session-*.scope, but require it to be there.
1402 static const char *skip_session(const char *p) {
1408 p += strspn(p, "/");
1410 n = strcspn(p, "/");
1411 if (n < strlen("session-x.scope"))
1414 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1415 char buf[n - 8 - 6 + 1];
1417 memcpy(buf, p + 8, n - 8 - 6);
1420 /* Note that session scopes never need unescaping,
1421 * since they cannot conflict with the kernel's own
1422 * names, hence we don't need to call cg_unescape()
1425 if (!session_id_valid(buf))
1429 p += strspn(p, "/");
1437 * Skip user@*.service, but require it to be there.
1439 static const char *skip_user_manager(const char *p) {
1445 p += strspn(p, "/");
1447 n = strcspn(p, "/");
1448 if (n < strlen("user@x.service"))
1451 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1452 char buf[n - 5 - 8 + 1];
1454 memcpy(buf, p + 5, n - 5 - 8);
1457 /* Note that user manager services never need unescaping,
1458 * since they cannot conflict with the kernel's own
1459 * names, hence we don't need to call cg_unescape()
1462 if (parse_uid(buf, NULL) < 0)
1466 p += strspn(p, "/");
1474 static const char *skip_user_prefix(const char *path) {
1479 /* Skip slices, if there are any */
1480 e = skip_slices(path);
1482 /* Skip the user manager, if it's in the path now... */
1483 t = skip_user_manager(e);
1487 /* Alternatively skip the user session if it is in the path... */
1488 return skip_session(e);
1491 int cg_path_get_user_unit(const char *path, char **ret) {
1497 t = skip_user_prefix(path);
1501 /* And from here on it looks pretty much the same as for a
1502 * system unit, hence let's use the same parser from here
1504 return cg_path_get_unit(t, ret);
1507 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1508 _cleanup_free_ char *cgroup = NULL;
1513 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1517 return cg_path_get_user_unit(cgroup, unit);
1520 int cg_path_get_machine_name(const char *path, char **machine) {
1521 _cleanup_free_ char *u = NULL;
1525 r = cg_path_get_unit(path, &u);
1529 sl = strjoina("/run/systemd/machines/unit:", u);
1530 return readlink_malloc(sl, machine);
1533 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1534 _cleanup_free_ char *cgroup = NULL;
1539 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1543 return cg_path_get_machine_name(cgroup, machine);
1547 int cg_path_get_session(const char *path, char **session) {
1548 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1549 wrinkle is that SESSION might be escaped. */
1551 _cleanup_free_ char *unit = NULL;
1557 r = cg_path_get_unit(path, &unit);
1561 start = startswith(unit, "session-");
1564 end = endswith(start, ".scope");
1569 if (!session_id_valid(start))
1572 const char *e, *n, *start;
1575 log_debug_elogind("path is \"%s\"", path);
1576 assert(path[0] == '/');
1579 n = strchrnul(e, '/');
1583 start = strndupa(e, n - e);
1584 start = cg_unescape(start);
1593 log_debug_elogind("found session: \"%s\"", start);
1604 int cg_pid_get_session(pid_t pid, char **session) {
1605 _cleanup_free_ char *cgroup = NULL;
1608 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1612 return cg_path_get_session(cgroup, session);
1615 #if 0 /// UNNEEDED by elogind
1616 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1617 _cleanup_free_ char *slice = NULL;
1623 r = cg_path_get_slice(path, &slice);
1627 start = startswith(slice, "user-");
1630 end = endswith(start, ".slice");
1635 if (parse_uid(start, uid) < 0)
1641 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1642 _cleanup_free_ char *cgroup = NULL;
1645 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1649 return cg_path_get_owner_uid(cgroup, uid);
1652 int cg_path_get_slice(const char *p, char **slice) {
1653 const char *e = NULL;
1658 /* Finds the right-most slice unit from the beginning, but
1659 * stops before we come to the first non-slice unit. */
1664 p += strspn(p, "/");
1666 n = strcspn(p, "/");
1667 if (!valid_slice_name(p, n)) {
1672 s = strdup("-.slice");
1680 return cg_path_decode_unit(e, slice);
1688 int cg_pid_get_slice(pid_t pid, char **slice) {
1689 _cleanup_free_ char *cgroup = NULL;
1694 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1698 return cg_path_get_slice(cgroup, slice);
1701 int cg_path_get_user_slice(const char *p, char **slice) {
1706 t = skip_user_prefix(p);
1710 /* And now it looks pretty much the same as for a system
1711 * slice, so let's just use the same parser from here on. */
1712 return cg_path_get_slice(t, slice);
1715 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1716 _cleanup_free_ char *cgroup = NULL;
1721 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1725 return cg_path_get_user_slice(cgroup, slice);
1729 char *cg_escape(const char *p) {
1730 bool need_prefix = false;
1732 /* This implements very minimal escaping for names to be used
1733 * as file names in the cgroup tree: any name which might
1734 * conflict with a kernel name or is prefixed with '_' is
1735 * prefixed with a '_'. That way, when reading cgroup names it
1736 * is sufficient to remove a single prefixing underscore if
1739 /* The return value of this function (unlike cg_unescape())
1745 streq(p, "notify_on_release") ||
1746 streq(p, "release_agent") ||
1747 streq(p, "tasks") ||
1748 startswith(p, "cgroup."))
1753 dot = strrchr(p, '.');
1758 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1761 n = cgroup_controller_to_string(c);
1766 if (memcmp(p, n, l) != 0)
1776 return strappend("_", p);
1781 char *cg_unescape(const char *p) {
1784 /* The return value of this function (unlike cg_escape())
1785 * doesn't need free()! */
1793 #define CONTROLLER_VALID \
1797 bool cg_controller_is_valid(const char *p) {
1803 s = startswith(p, "name=");
1807 if (*p == 0 || *p == '_')
1810 for (t = p; *t; t++)
1811 if (!strchr(CONTROLLER_VALID, *t))
1814 if (t - p > FILENAME_MAX)
1820 #if 0 /// UNNEEDED by elogind
1821 int cg_slice_to_path(const char *unit, char **ret) {
1822 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1829 if (streq(unit, "-.slice")) {
1839 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1842 if (!endswith(unit, ".slice"))
1845 r = unit_name_to_prefix(unit, &p);
1849 dash = strchr(p, '-');
1851 /* Don't allow initial dashes */
1856 _cleanup_free_ char *escaped = NULL;
1857 char n[dash - p + sizeof(".slice")];
1859 /* Don't allow trailing or double dashes */
1860 if (dash[1] == 0 || dash[1] == '-')
1863 strcpy(stpncpy(n, p, dash - p), ".slice");
1864 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1867 escaped = cg_escape(n);
1871 if (!strextend(&s, escaped, "/", NULL))
1874 dash = strchr(dash+1, '-');
1877 e = cg_escape(unit);
1881 if (!strextend(&s, e, NULL))
1891 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1892 _cleanup_free_ char *p = NULL;
1895 r = cg_get_path(controller, path, attribute, &p);
1899 return write_string_file(p, value, 0);
1902 #if 0 /// UNNEEDED by elogind
1903 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1904 _cleanup_free_ char *p = NULL;
1907 r = cg_get_path(controller, path, attribute, &p);
1911 return read_one_line_file(p, ret);
1914 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1918 /* This one will create a cgroup in our private tree, but also
1919 * duplicate it in the trees specified in mask, and remove it
1922 /* First create the cgroup in our own hierarchy. */
1923 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1927 /* If we are in the unified hierarchy, we are done now */
1928 unified = cg_unified();
1934 /* Otherwise, do the same in the other hierarchies */
1935 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1936 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1939 n = cgroup_controller_to_string(c);
1942 (void) cg_create(n, path);
1943 else if (supported & bit)
1944 (void) cg_trim(n, path, true);
1950 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1954 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
1958 unified = cg_unified();
1964 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1965 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1966 const char *p = NULL;
1968 if (!(supported & bit))
1972 p = path_callback(bit, userdata);
1977 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
1983 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
1988 SET_FOREACH(pidp, pids, i) {
1989 pid_t pid = PTR_TO_PID(pidp);
1992 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
1993 if (q < 0 && r >= 0)
2000 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2004 if (!path_equal(from, to)) {
2005 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, false, true);
2010 unified = cg_unified();
2016 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2017 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2018 const char *p = NULL;
2020 if (!(supported & bit))
2024 p = to_callback(bit, userdata);
2029 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, false, false);
2035 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2039 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2043 unified = cg_unified();
2049 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2050 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2052 if (!(supported & bit))
2055 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2062 int cg_mask_supported(CGroupMask *ret) {
2063 CGroupMask mask = 0;
2066 /* Determines the mask of supported cgroup controllers. Only
2067 * includes controllers we can make sense of and that are
2068 * actually accessible. */
2070 unified = cg_unified();
2074 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2077 /* In the unified hierarchy we can read the supported
2078 * and accessible controllers from a the top-level
2079 * cgroup attribute */
2081 r = cg_get_root_path(&root);
2085 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2089 r = read_one_line_file(path, &controllers);
2095 _cleanup_free_ char *n = NULL;
2098 r = extract_first_word(&c, &n, NULL, 0);
2104 v = cgroup_controller_from_string(n);
2108 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2111 /* Currently, we only support the memory and pids
2112 * controller in the unified hierarchy, mask
2113 * everything else off. */
2114 mask &= CGROUP_MASK_MEMORY | CGROUP_MASK_PIDS;
2119 /* In the legacy hierarchy, we check whether which
2120 * hierarchies are mounted. */
2122 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2125 n = cgroup_controller_to_string(c);
2126 if (controller_is_accessible(n) >= 0)
2127 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2135 #if 0 /// UNNEEDED by elogind
2136 int cg_kernel_controllers(Set *controllers) {
2137 _cleanup_fclose_ FILE *f = NULL;
2141 assert(controllers);
2143 /* Determines the full list of kernel-known controllers. Might
2144 * include controllers we don't actually support, arbitrary
2145 * named hierarchies and controllers that aren't currently
2146 * accessible (because not mounted). */
2148 f = fopen("/proc/cgroups", "re");
2150 if (errno == ENOENT)
2155 /* Ignore the header line */
2156 (void) fgets(buf, sizeof(buf), f);
2163 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2168 if (ferror(f) && errno > 0)
2179 if (!cg_controller_is_valid(controller)) {
2184 r = set_consume(controllers, controller);
2193 static thread_local int unified_cache = -1;
2195 int cg_unified(void) {
2198 /* Checks if we support the unified hierarchy. Returns an
2199 * error when the cgroup hierarchies aren't mounted yet or we
2200 * have any other trouble determining if the unified hierarchy
2203 if (unified_cache >= 0)
2204 return unified_cache;
2206 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2209 /// elogind can not support the unified hierarchy as a controller,
2210 /// so always assume a classical hierarchy.
2211 /// If, ond only *if*, someone really wants to substitute systemd-login
2212 /// in an environment managed by systemd with elogin, we might have to
2213 /// add such a support.
2215 if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC))
2216 unified_cache = true;
2217 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2219 if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2221 unified_cache = false;
2225 return unified_cache;
2228 #if 0 /// UNNEEDED by elogind
2229 void cg_unified_flush(void) {
2233 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2234 _cleanup_free_ char *fs = NULL;
2243 unified = cg_unified();
2246 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2249 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2253 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2254 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2257 if (!(supported & bit))
2260 n = cgroup_controller_to_string(c);
2262 char s[1 + strlen(n) + 1];
2264 s[0] = mask & bit ? '+' : '-';
2267 r = write_string_file(fs, s, 0);
2269 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2276 bool cg_is_unified_wanted(void) {
2277 static thread_local int wanted = -1;
2280 /* If the hierarchy is already mounted, then follow whatever
2281 * was chosen for it. */
2282 unified = cg_unified();
2286 /* Otherwise, let's see what the kernel command line has to
2287 * say. Since checking that is expensive, let's cache the
2292 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2294 return (wanted = true);
2296 _cleanup_free_ char *value = NULL;
2298 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2302 return (wanted = false);
2304 return (wanted = parse_boolean(value) > 0);
2308 bool cg_is_legacy_wanted(void) {
2309 return !cg_is_unified_wanted();
2312 bool cg_is_legacy_wanted(void) {
2317 #if 0 /// UNNEEDED by elogind
2318 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2323 *ret = CGROUP_CPU_SHARES_INVALID;
2327 r = safe_atou64(s, &u);
2331 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2338 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2343 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2347 r = safe_atou64(s, &u);
2351 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2359 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2360 [CGROUP_CONTROLLER_CPU] = "cpu",
2361 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2362 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2363 [CGROUP_CONTROLLER_MEMORY] = "memory",
2364 [CGROUP_CONTROLLER_DEVICES] = "devices",
2365 [CGROUP_CONTROLLER_PIDS] = "pids",
2368 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);