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"
47 #include "parse-util.h"
48 #include "path-util.h"
49 #include "proc-cmdline.h"
50 #include "process-util.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 bool cg_ns_supported(void) {
138 static thread_local
int enabled
= -1;
143 if (access("/proc/self/ns/cgroup", F_OK
) == 0)
151 int cg_enumerate_subgroups(const char *controller
, const char *path
, DIR **_d
) {
152 _cleanup_free_
char *fs
= NULL
;
158 /* This is not recursive! */
160 r
= cg_get_path(controller
, path
, NULL
, &fs
);
172 int cg_read_subgroup(DIR *d
, char **fn
) {
178 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
181 if (de
->d_type
!= DT_DIR
)
184 if (streq(de
->d_name
, ".") ||
185 streq(de
->d_name
, ".."))
188 b
= strdup(de
->d_name
);
199 int cg_rmdir(const char *controller
, const char *path
) {
200 _cleanup_free_
char *p
= NULL
;
203 r
= cg_get_path(controller
, path
, NULL
, &p
);
208 if (r
< 0 && errno
!= ENOENT
)
215 const char *controller
,
220 cg_kill_log_func_t log_kill
,
223 _cleanup_set_free_ Set
*allocated_set
= NULL
;
230 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
231 * SIGCONT on SIGKILL. */
232 if (IN_SET(sig
, SIGCONT
, SIGKILL
))
233 flags
&= ~CGROUP_SIGCONT
;
235 /* This goes through the tasks list and kills them all. This
236 * is repeated until no further processes are added to the
237 * tasks list, to properly handle forking processes */
240 s
= allocated_set
= set_new(NULL
);
248 _cleanup_fclose_
FILE *f
= NULL
;
252 r
= cg_enumerate_processes(controller
, path
, &f
);
254 if (ret
>= 0 && r
!= -ENOENT
)
260 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
262 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
265 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
269 log_kill(pid
, sig
, userdata
);
271 /* If we haven't killed this process yet, kill
273 if (kill(pid
, sig
) < 0) {
274 if (ret
>= 0 && errno
!= ESRCH
)
277 if (flags
& CGROUP_SIGCONT
)
278 (void) kill(pid
, SIGCONT
);
286 r
= set_put(s
, PID_TO_PTR(pid
));
302 /* To avoid racing against processes which fork
303 * quicker than we can kill them we repeat this until
304 * no new pids need to be killed. */
311 int cg_kill_recursive(
312 const char *controller
,
317 cg_kill_log_func_t log_kill
,
320 _cleanup_set_free_ Set
*allocated_set
= NULL
;
321 _cleanup_closedir_
DIR *d
= NULL
;
329 s
= allocated_set
= set_new(NULL
);
334 ret
= cg_kill(controller
, path
, sig
, flags
, s
, log_kill
, userdata
);
336 r
= cg_enumerate_subgroups(controller
, path
, &d
);
338 if (ret
>= 0 && r
!= -ENOENT
)
344 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
345 _cleanup_free_
char *p
= NULL
;
347 p
= strjoin(path
, "/", fn
, NULL
);
352 r
= cg_kill_recursive(controller
, p
, sig
, flags
, s
, log_kill
, userdata
);
353 if (r
!= 0 && ret
>= 0)
356 if (ret
>= 0 && r
< 0)
359 if (flags
& CGROUP_REMOVE
) {
360 r
= cg_rmdir(controller
, path
);
361 if (r
< 0 && ret
>= 0 && r
!= -ENOENT
&& r
!= -EBUSY
)
376 _cleanup_set_free_ Set
*s
= NULL
;
392 _cleanup_fclose_
FILE *f
= NULL
;
396 r
= cg_enumerate_processes(cfrom
, pfrom
, &f
);
398 if (ret
>= 0 && r
!= -ENOENT
)
404 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
406 /* This might do weird stuff if we aren't a
407 * single-threaded program. However, we
408 * luckily know we are not */
409 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
412 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
415 /* Ignore kernel threads. Since they can only
416 * exist in the root cgroup, we only check for
419 (isempty(pfrom
) || path_equal(pfrom
, "/")) &&
420 is_kernel_thread(pid
) > 0)
423 r
= cg_attach(cto
, pto
, pid
);
425 if (ret
>= 0 && r
!= -ESRCH
)
432 r
= set_put(s
, PID_TO_PTR(pid
));
452 int cg_migrate_recursive(
459 _cleanup_closedir_
DIR *d
= NULL
;
468 ret
= cg_migrate(cfrom
, pfrom
, cto
, pto
, flags
);
470 r
= cg_enumerate_subgroups(cfrom
, pfrom
, &d
);
472 if (ret
>= 0 && r
!= -ENOENT
)
478 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
479 _cleanup_free_
char *p
= NULL
;
481 p
= strjoin(pfrom
, "/", fn
, NULL
);
486 r
= cg_migrate_recursive(cfrom
, p
, cto
, pto
, flags
);
487 if (r
!= 0 && ret
>= 0)
491 if (r
< 0 && ret
>= 0)
494 if (flags
& CGROUP_REMOVE
) {
495 r
= cg_rmdir(cfrom
, pfrom
);
496 if (r
< 0 && ret
>= 0 && r
!= -ENOENT
&& r
!= -EBUSY
)
503 int cg_migrate_recursive_fallback(
517 r
= cg_migrate_recursive(cfrom
, pfrom
, cto
, pto
, flags
);
519 char prefix
[strlen(pto
) + 1];
521 /* This didn't work? Then let's try all prefixes of the destination */
523 PATH_FOREACH_PREFIX(prefix
, pto
) {
526 q
= cg_migrate_recursive(cfrom
, pfrom
, cto
, prefix
, flags
);
535 static const char *controller_to_dirname(const char *controller
) {
540 /* Converts a controller name to the directory name below
541 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
542 * just cuts off the name= prefixed used for named
543 * hierarchies, if it is specified. */
545 e
= startswith(controller
, "name=");
552 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
559 dn
= controller_to_dirname(controller
);
561 if (isempty(path
) && isempty(suffix
))
562 t
= strappend("/sys/fs/cgroup/", dn
);
563 else if (isempty(path
))
564 t
= strjoin("/sys/fs/cgroup/", dn
, "/", suffix
, NULL
);
565 else if (isempty(suffix
))
566 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
, NULL
);
568 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
, "/", suffix
, NULL
);
576 static int join_path_unified(const char *path
, const char *suffix
, char **fs
) {
581 if (isempty(path
) && isempty(suffix
))
582 t
= strdup("/sys/fs/cgroup");
583 else if (isempty(path
))
584 t
= strappend("/sys/fs/cgroup/", suffix
);
585 else if (isempty(suffix
))
586 t
= strappend("/sys/fs/cgroup/", path
);
588 t
= strjoin("/sys/fs/cgroup/", path
, "/", suffix
, NULL
);
596 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
604 /* If no controller is specified, we return the path
605 * *below* the controllers, without any prefix. */
607 if (!path
&& !suffix
)
615 t
= strjoin(path
, "/", suffix
, NULL
);
619 *fs
= path_kill_slashes(t
);
623 if (!cg_controller_is_valid(controller
))
626 unified
= cg_all_unified();
631 r
= join_path_unified(path
, suffix
, fs
);
633 r
= join_path_legacy(controller
, path
, suffix
, fs
);
637 path_kill_slashes(*fs
);
641 static int controller_is_accessible(const char *controller
) {
646 /* Checks whether a specific controller is accessible,
647 * i.e. its hierarchy mounted. In the unified hierarchy all
648 * controllers are considered accessible, except for the named
651 if (!cg_controller_is_valid(controller
))
654 unified
= cg_all_unified();
658 /* We don't support named hierarchies if we are using
659 * the unified hierarchy. */
661 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
664 if (startswith(controller
, "name="))
670 dn
= controller_to_dirname(controller
);
671 cc
= strjoina("/sys/fs/cgroup/", dn
);
673 if (laccess(cc
, F_OK
) < 0)
680 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
686 /* Check if the specified controller is actually accessible */
687 r
= controller_is_accessible(controller
);
691 return cg_get_path(controller
, path
, suffix
, fs
);
694 static int trim_cb(const char *path
, const struct stat
*sb
, int typeflag
, struct FTW
*ftwbuf
) {
699 if (typeflag
!= FTW_DP
)
702 if (ftwbuf
->level
< 1)
709 int cg_trim(const char *controller
, const char *path
, bool delete_root
) {
710 _cleanup_free_
char *fs
= NULL
;
715 r
= cg_get_path(controller
, path
, NULL
, &fs
);
720 if (nftw(fs
, trim_cb
, 64, FTW_DEPTH
|FTW_MOUNT
|FTW_PHYS
) != 0) {
730 if (rmdir(fs
) < 0 && errno
!= ENOENT
)
737 int cg_create(const char *controller
, const char *path
) {
738 _cleanup_free_
char *fs
= NULL
;
741 r
= cg_get_path_and_check(controller
, path
, NULL
, &fs
);
745 r
= mkdir_parents(fs
, 0755);
749 if (mkdir(fs
, 0755) < 0) {
760 int cg_create_and_attach(const char *controller
, const char *path
, pid_t pid
) {
765 r
= cg_create(controller
, path
);
769 q
= cg_attach(controller
, path
, pid
);
773 /* This does not remove the cgroup on failure */
777 int cg_attach(const char *controller
, const char *path
, pid_t pid
) {
778 _cleanup_free_
char *fs
= NULL
;
779 char c
[DECIMAL_STR_MAX(pid_t
) + 2];
785 r
= cg_get_path_and_check(controller
, path
, "cgroup.procs", &fs
);
792 xsprintf(c
, PID_FMT
"\n", pid
);
794 return write_string_file(fs
, c
, 0);
797 int cg_attach_fallback(const char *controller
, const char *path
, pid_t pid
) {
804 r
= cg_attach(controller
, path
, pid
);
806 char prefix
[strlen(path
) + 1];
808 /* This didn't work? Then let's try all prefixes of
811 PATH_FOREACH_PREFIX(prefix
, path
) {
814 q
= cg_attach(controller
, prefix
, pid
);
823 int cg_set_group_access(
824 const char *controller
,
830 _cleanup_free_
char *fs
= NULL
;
833 if (mode
== MODE_INVALID
&& uid
== UID_INVALID
&& gid
== GID_INVALID
)
836 if (mode
!= MODE_INVALID
)
839 r
= cg_get_path(controller
, path
, NULL
, &fs
);
843 return chmod_and_chown(fs
, mode
, uid
, gid
);
846 int cg_set_task_access(
847 const char *controller
,
853 _cleanup_free_
char *fs
= NULL
, *procs
= NULL
;
858 if (mode
== MODE_INVALID
&& uid
== UID_INVALID
&& gid
== GID_INVALID
)
861 if (mode
!= MODE_INVALID
)
864 r
= cg_get_path(controller
, path
, "cgroup.procs", &fs
);
868 r
= chmod_and_chown(fs
, mode
, uid
, gid
);
872 unified
= cg_unified(controller
);
878 /* Compatibility, Always keep values for "tasks" in sync with
880 if (cg_get_path(controller
, path
, "tasks", &procs
) >= 0)
881 (void) chmod_and_chown(procs
, mode
, uid
, gid
);
886 int cg_pid_get_path(const char *controller
, pid_t pid
, char **path
) {
887 _cleanup_fclose_
FILE *f
= NULL
;
897 if (!cg_controller_is_valid(controller
))
900 controller
= SYSTEMD_CGROUP_CONTROLLER
;
902 unified
= cg_unified(controller
);
906 cs
= strlen(controller
);
908 fs
= procfs_file_alloca(pid
, "cgroup");
911 return errno
== ENOENT
? -ESRCH
: -errno
;
913 FOREACH_LINE(line
, f
, return -errno
) {
919 e
= startswith(line
, "0:");
929 const char *word
, *state
;
932 l
= strchr(line
, ':');
942 FOREACH_WORD_SEPARATOR(word
, k
, l
, ",", state
) {
943 if (k
== cs
&& memcmp(word
, controller
, cs
) == 0) {
964 int cg_install_release_agent(const char *controller
, const char *agent
) {
965 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
971 unified
= cg_unified(controller
);
974 if (unified
) /* doesn't apply to unified hierarchy */
977 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
981 r
= read_one_line_file(fs
, &contents
);
985 sc
= strstrip(contents
);
987 r
= write_string_file(fs
, agent
, 0);
990 } else if (!path_equal(sc
, agent
))
994 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
998 contents
= mfree(contents
);
999 r
= read_one_line_file(fs
, &contents
);
1003 sc
= strstrip(contents
);
1004 if (streq(sc
, "0")) {
1005 r
= write_string_file(fs
, "1", 0);
1012 if (!streq(sc
, "1"))
1018 int cg_uninstall_release_agent(const char *controller
) {
1019 _cleanup_free_
char *fs
= NULL
;
1022 unified
= cg_unified(controller
);
1025 if (unified
) /* Doesn't apply to unified hierarchy */
1028 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
1032 r
= write_string_file(fs
, "0", 0);
1038 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
1042 r
= write_string_file(fs
, "", 0);
1049 int cg_is_empty(const char *controller
, const char *path
) {
1050 _cleanup_fclose_
FILE *f
= NULL
;
1056 r
= cg_enumerate_processes(controller
, path
, &f
);
1062 r
= cg_read_pid(f
, &pid
);
1069 int cg_is_empty_recursive(const char *controller
, const char *path
) {
1074 /* The root cgroup is always populated */
1075 if (controller
&& (isempty(path
) || path_equal(path
, "/")))
1078 unified
= cg_unified(controller
);
1083 _cleanup_free_
char *t
= NULL
;
1085 /* On the unified hierarchy we can check empty state
1086 * via the "populated" attribute of "cgroup.events". */
1088 r
= cg_read_event(controller
, path
, "populated", &t
);
1092 return streq(t
, "0");
1094 _cleanup_closedir_
DIR *d
= NULL
;
1097 r
= cg_is_empty(controller
, path
);
1101 r
= cg_enumerate_subgroups(controller
, path
, &d
);
1107 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1108 _cleanup_free_
char *p
= NULL
;
1110 p
= strjoin(path
, "/", fn
, NULL
);
1115 r
= cg_is_empty_recursive(controller
, p
);
1126 int cg_split_spec(const char *spec
, char **controller
, char **path
) {
1127 char *t
= NULL
, *u
= NULL
;
1133 if (!path_is_safe(spec
))
1141 *path
= path_kill_slashes(t
);
1150 e
= strchr(spec
, ':');
1152 if (!cg_controller_is_valid(spec
))
1169 t
= strndup(spec
, e
-spec
);
1172 if (!cg_controller_is_valid(t
)) {
1186 if (!path_is_safe(u
) ||
1187 !path_is_absolute(u
)) {
1193 path_kill_slashes(u
);
1209 int cg_mangle_path(const char *path
, char **result
) {
1210 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
1217 /* First, check if it already is a filesystem path */
1218 if (path_startswith(path
, "/sys/fs/cgroup")) {
1224 *result
= path_kill_slashes(t
);
1228 /* Otherwise, treat it as cg spec */
1229 r
= cg_split_spec(path
, &c
, &p
);
1233 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, result
);
1236 int cg_get_root_path(char **path
) {
1242 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
1246 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
1248 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
1250 e
= endswith(p
, "/system"); /* even more legacy */
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
);
1277 p
= path_startswith(cgroup
, root
);
1278 if (p
&& p
> cgroup
)
1286 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **cgroup
) {
1287 _cleanup_free_
char *raw
= NULL
;
1294 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1298 r
= cg_shift_path(raw
, root
, &c
);
1318 int cg_path_decode_unit(const char *cgroup
, char **unit
) {
1325 n
= strcspn(cgroup
, "/");
1329 c
= strndupa(cgroup
, n
);
1332 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1343 static bool valid_slice_name(const char *p
, size_t n
) {
1348 if (n
< strlen("x.slice"))
1351 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1357 c
= cg_unescape(buf
);
1359 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1365 static const char *skip_slices(const char *p
) {
1368 /* Skips over all slice assignments */
1373 p
+= strspn(p
, "/");
1375 n
= strcspn(p
, "/");
1376 if (!valid_slice_name(p
, n
))
1383 int cg_path_get_unit(const char *path
, char **ret
) {
1391 e
= skip_slices(path
);
1393 r
= cg_path_decode_unit(e
, &unit
);
1397 /* We skipped over the slices, don't accept any now */
1398 if (endswith(unit
, ".slice")) {
1407 int cg_pid_get_unit(pid_t pid
, char **unit
) {
1408 _cleanup_free_
char *cgroup
= NULL
;
1413 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1417 return cg_path_get_unit(cgroup
, unit
);
1421 * Skip session-*.scope, but require it to be there.
1423 static const char *skip_session(const char *p
) {
1429 p
+= strspn(p
, "/");
1431 n
= strcspn(p
, "/");
1432 if (n
< strlen("session-x.scope"))
1435 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1436 char buf
[n
- 8 - 6 + 1];
1438 memcpy(buf
, p
+ 8, n
- 8 - 6);
1441 /* Note that session scopes never need unescaping,
1442 * since they cannot conflict with the kernel's own
1443 * names, hence we don't need to call cg_unescape()
1446 if (!session_id_valid(buf
))
1450 p
+= strspn(p
, "/");
1458 * Skip user@*.service, but require it to be there.
1460 static const char *skip_user_manager(const char *p
) {
1466 p
+= strspn(p
, "/");
1468 n
= strcspn(p
, "/");
1469 if (n
< strlen("user@x.service"))
1472 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1473 char buf
[n
- 5 - 8 + 1];
1475 memcpy(buf
, p
+ 5, n
- 5 - 8);
1478 /* Note that user manager services never need unescaping,
1479 * since they cannot conflict with the kernel's own
1480 * names, hence we don't need to call cg_unescape()
1483 if (parse_uid(buf
, NULL
) < 0)
1487 p
+= strspn(p
, "/");
1495 static const char *skip_user_prefix(const char *path
) {
1500 /* Skip slices, if there are any */
1501 e
= skip_slices(path
);
1503 /* Skip the user manager, if it's in the path now... */
1504 t
= skip_user_manager(e
);
1508 /* Alternatively skip the user session if it is in the path... */
1509 return skip_session(e
);
1512 int cg_path_get_user_unit(const char *path
, char **ret
) {
1518 t
= skip_user_prefix(path
);
1522 /* And from here on it looks pretty much the same as for a
1523 * system unit, hence let's use the same parser from here
1525 return cg_path_get_unit(t
, ret
);
1528 int cg_pid_get_user_unit(pid_t pid
, char **unit
) {
1529 _cleanup_free_
char *cgroup
= NULL
;
1534 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1538 return cg_path_get_user_unit(cgroup
, unit
);
1541 int cg_path_get_machine_name(const char *path
, char **machine
) {
1542 _cleanup_free_
char *u
= NULL
;
1546 r
= cg_path_get_unit(path
, &u
);
1550 sl
= strjoina("/run/systemd/machines/unit:", u
);
1551 return readlink_malloc(sl
, machine
);
1554 int cg_pid_get_machine_name(pid_t pid
, char **machine
) {
1555 _cleanup_free_
char *cgroup
= NULL
;
1560 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1564 return cg_path_get_machine_name(cgroup
, machine
);
1567 int cg_path_get_session(const char *path
, char **session
) {
1568 _cleanup_free_
char *unit
= NULL
;
1574 r
= cg_path_get_unit(path
, &unit
);
1578 start
= startswith(unit
, "session-");
1581 end
= endswith(start
, ".scope");
1586 if (!session_id_valid(start
))
1602 int cg_pid_get_session(pid_t pid
, char **session
) {
1603 _cleanup_free_
char *cgroup
= NULL
;
1606 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1610 return cg_path_get_session(cgroup
, session
);
1613 int cg_path_get_owner_uid(const char *path
, uid_t
*uid
) {
1614 _cleanup_free_
char *slice
= NULL
;
1620 r
= cg_path_get_slice(path
, &slice
);
1624 start
= startswith(slice
, "user-");
1627 end
= endswith(start
, ".slice");
1632 if (parse_uid(start
, uid
) < 0)
1638 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*uid
) {
1639 _cleanup_free_
char *cgroup
= NULL
;
1642 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1646 return cg_path_get_owner_uid(cgroup
, uid
);
1649 int cg_path_get_slice(const char *p
, char **slice
) {
1650 const char *e
= NULL
;
1655 /* Finds the right-most slice unit from the beginning, but
1656 * stops before we come to the first non-slice unit. */
1661 p
+= strspn(p
, "/");
1663 n
= strcspn(p
, "/");
1664 if (!valid_slice_name(p
, n
)) {
1669 s
= strdup("-.slice");
1677 return cg_path_decode_unit(e
, slice
);
1685 int cg_pid_get_slice(pid_t pid
, char **slice
) {
1686 _cleanup_free_
char *cgroup
= NULL
;
1691 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1695 return cg_path_get_slice(cgroup
, slice
);
1698 int cg_path_get_user_slice(const char *p
, char **slice
) {
1703 t
= skip_user_prefix(p
);
1707 /* And now it looks pretty much the same as for a system
1708 * slice, so let's just use the same parser from here on. */
1709 return cg_path_get_slice(t
, slice
);
1712 int cg_pid_get_user_slice(pid_t pid
, char **slice
) {
1713 _cleanup_free_
char *cgroup
= NULL
;
1718 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1722 return cg_path_get_user_slice(cgroup
, slice
);
1725 char *cg_escape(const char *p
) {
1726 bool need_prefix
= false;
1728 /* This implements very minimal escaping for names to be used
1729 * as file names in the cgroup tree: any name which might
1730 * conflict with a kernel name or is prefixed with '_' is
1731 * prefixed with a '_'. That way, when reading cgroup names it
1732 * is sufficient to remove a single prefixing underscore if
1735 /* The return value of this function (unlike cg_unescape())
1741 streq(p
, "notify_on_release") ||
1742 streq(p
, "release_agent") ||
1743 streq(p
, "tasks") ||
1744 startswith(p
, "cgroup."))
1749 dot
= strrchr(p
, '.');
1754 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1757 n
= cgroup_controller_to_string(c
);
1762 if (memcmp(p
, n
, l
) != 0)
1772 return strappend("_", p
);
1777 char *cg_unescape(const char *p
) {
1780 /* The return value of this function (unlike cg_escape())
1781 * doesn't need free()! */
1789 #define CONTROLLER_VALID \
1793 bool cg_controller_is_valid(const char *p
) {
1799 s
= startswith(p
, "name=");
1803 if (*p
== 0 || *p
== '_')
1806 for (t
= p
; *t
; t
++)
1807 if (!strchr(CONTROLLER_VALID
, *t
))
1810 if (t
- p
> FILENAME_MAX
)
1816 int cg_slice_to_path(const char *unit
, char **ret
) {
1817 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1824 if (streq(unit
, "-.slice")) {
1834 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1837 if (!endswith(unit
, ".slice"))
1840 r
= unit_name_to_prefix(unit
, &p
);
1844 dash
= strchr(p
, '-');
1846 /* Don't allow initial dashes */
1851 _cleanup_free_
char *escaped
= NULL
;
1852 char n
[dash
- p
+ sizeof(".slice")];
1854 /* Don't allow trailing or double dashes */
1855 if (dash
[1] == 0 || dash
[1] == '-')
1858 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1859 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1862 escaped
= cg_escape(n
);
1866 if (!strextend(&s
, escaped
, "/", NULL
))
1869 dash
= strchr(dash
+1, '-');
1872 e
= cg_escape(unit
);
1876 if (!strextend(&s
, e
, NULL
))
1885 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
1886 _cleanup_free_
char *p
= NULL
;
1889 r
= cg_get_path(controller
, path
, attribute
, &p
);
1893 return write_string_file(p
, value
, 0);
1896 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
1897 _cleanup_free_
char *p
= NULL
;
1900 r
= cg_get_path(controller
, path
, attribute
, &p
);
1904 return read_one_line_file(p
, ret
);
1907 int cg_get_keyed_attribute(const char *controller
, const char *path
, const char *attribute
, const char **keys
, char **values
) {
1908 _cleanup_free_
char *filename
= NULL
, *content
= NULL
;
1912 for (i
= 0; keys
[i
]; i
++)
1915 r
= cg_get_path(controller
, path
, attribute
, &filename
);
1919 r
= read_full_file(filename
, &content
, NULL
);
1924 while ((line
= strsep(&p
, "\n"))) {
1927 key
= strsep(&line
, " ");
1929 for (i
= 0; keys
[i
]; i
++) {
1930 if (streq(key
, keys
[i
])) {
1931 values
[i
] = strdup(line
);
1937 for (i
= 0; keys
[i
]; i
++) {
1939 for (i
= 0; keys
[i
]; i
++) {
1950 int cg_create_everywhere(CGroupMask supported
, CGroupMask mask
, const char *path
) {
1954 /* This one will create a cgroup in our private tree, but also
1955 * duplicate it in the trees specified in mask, and remove it
1958 /* First create the cgroup in our own hierarchy. */
1959 r
= cg_create(SYSTEMD_CGROUP_CONTROLLER
, path
);
1963 /* If we are in the unified hierarchy, we are done now */
1964 unified
= cg_all_unified();
1970 /* Otherwise, do the same in the other hierarchies */
1971 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1972 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1975 n
= cgroup_controller_to_string(c
);
1978 (void) cg_create(n
, path
);
1979 else if (supported
& bit
)
1980 (void) cg_trim(n
, path
, true);
1986 int cg_attach_everywhere(CGroupMask supported
, const char *path
, pid_t pid
, cg_migrate_callback_t path_callback
, void *userdata
) {
1990 r
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, path
, pid
);
1994 unified
= cg_all_unified();
2000 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2001 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2002 const char *p
= NULL
;
2004 if (!(supported
& bit
))
2008 p
= path_callback(bit
, userdata
);
2013 (void) cg_attach_fallback(cgroup_controller_to_string(c
), p
, pid
);
2019 int cg_attach_many_everywhere(CGroupMask supported
, const char *path
, Set
* pids
, cg_migrate_callback_t path_callback
, void *userdata
) {
2024 SET_FOREACH(pidp
, pids
, i
) {
2025 pid_t pid
= PTR_TO_PID(pidp
);
2028 q
= cg_attach_everywhere(supported
, path
, pid
, path_callback
, userdata
);
2029 if (q
< 0 && r
>= 0)
2036 int cg_migrate_everywhere(CGroupMask supported
, const char *from
, const char *to
, cg_migrate_callback_t to_callback
, void *userdata
) {
2040 if (!path_equal(from
, to
)) {
2041 r
= cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER
, from
, SYSTEMD_CGROUP_CONTROLLER
, to
, CGROUP_REMOVE
);
2046 unified
= cg_all_unified();
2052 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2053 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2054 const char *p
= NULL
;
2056 if (!(supported
& bit
))
2060 p
= to_callback(bit
, userdata
);
2065 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER
, to
, cgroup_controller_to_string(c
), p
, 0);
2071 int cg_trim_everywhere(CGroupMask supported
, const char *path
, bool delete_root
) {
2075 r
= cg_trim(SYSTEMD_CGROUP_CONTROLLER
, path
, delete_root
);
2079 unified
= cg_all_unified();
2085 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2086 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2088 if (!(supported
& bit
))
2091 (void) cg_trim(cgroup_controller_to_string(c
), path
, delete_root
);
2097 int cg_mask_supported(CGroupMask
*ret
) {
2098 CGroupMask mask
= 0;
2101 /* Determines the mask of supported cgroup controllers. Only
2102 * includes controllers we can make sense of and that are
2103 * actually accessible. */
2105 unified
= cg_all_unified();
2109 _cleanup_free_
char *root
= NULL
, *controllers
= NULL
, *path
= NULL
;
2112 /* In the unified hierarchy we can read the supported
2113 * and accessible controllers from a the top-level
2114 * cgroup attribute */
2116 r
= cg_get_root_path(&root
);
2120 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
2124 r
= read_one_line_file(path
, &controllers
);
2130 _cleanup_free_
char *n
= NULL
;
2133 r
= extract_first_word(&c
, &n
, NULL
, 0);
2139 v
= cgroup_controller_from_string(n
);
2143 mask
|= CGROUP_CONTROLLER_TO_MASK(v
);
2146 /* Currently, we support the cpu, memory, io and pids
2147 * controller in the unified hierarchy, mask
2148 * everything else off. */
2149 mask
&= CGROUP_MASK_CPU
| CGROUP_MASK_MEMORY
| CGROUP_MASK_IO
| CGROUP_MASK_PIDS
;
2154 /* In the legacy hierarchy, we check whether which
2155 * hierarchies are mounted. */
2157 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2160 n
= cgroup_controller_to_string(c
);
2161 if (controller_is_accessible(n
) >= 0)
2162 mask
|= CGROUP_CONTROLLER_TO_MASK(c
);
2170 int cg_kernel_controllers(Set
*controllers
) {
2171 _cleanup_fclose_
FILE *f
= NULL
;
2175 assert(controllers
);
2177 /* Determines the full list of kernel-known controllers. Might
2178 * include controllers we don't actually support, arbitrary
2179 * named hierarchies and controllers that aren't currently
2180 * accessible (because not mounted). */
2182 f
= fopen("/proc/cgroups", "re");
2184 if (errno
== ENOENT
)
2189 /* Ignore the header line */
2190 (void) fgets(buf
, sizeof(buf
), f
);
2197 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
2202 if (ferror(f
) && errno
> 0)
2213 if (!cg_controller_is_valid(controller
)) {
2218 r
= set_consume(controllers
, controller
);
2226 static thread_local CGroupUnified unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2228 static int cg_update_unified(void) {
2232 /* Checks if we support the unified hierarchy. Returns an
2233 * error when the cgroup hierarchies aren't mounted yet or we
2234 * have any other trouble determining if the unified hierarchy
2237 if (unified_cache
>= CGROUP_UNIFIED_NONE
)
2240 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
2243 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
))
2244 unified_cache
= CGROUP_UNIFIED_ALL
;
2245 else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
)) {
2246 if (statfs("/sys/fs/cgroup/systemd/", &fs
) < 0)
2249 unified_cache
= F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
) ?
2250 CGROUP_UNIFIED_SYSTEMD
: CGROUP_UNIFIED_NONE
;
2257 int cg_unified(const char *controller
) {
2261 r
= cg_update_unified();
2265 if (streq_ptr(controller
, SYSTEMD_CGROUP_CONTROLLER
))
2266 return unified_cache
>= CGROUP_UNIFIED_SYSTEMD
;
2268 return unified_cache
>= CGROUP_UNIFIED_ALL
;
2271 int cg_all_unified(void) {
2273 return cg_unified(NULL
);
2276 void cg_unified_flush(void) {
2277 unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2280 int cg_enable_everywhere(CGroupMask supported
, CGroupMask mask
, const char *p
) {
2281 _cleanup_free_
char *fs
= NULL
;
2290 unified
= cg_all_unified();
2293 if (!unified
) /* on the legacy hiearchy there's no joining of controllers defined */
2296 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, p
, "cgroup.subtree_control", &fs
);
2300 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2301 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2304 if (!(supported
& bit
))
2307 n
= cgroup_controller_to_string(c
);
2309 char s
[1 + strlen(n
) + 1];
2311 s
[0] = mask
& bit
? '+' : '-';
2314 r
= write_string_file(fs
, s
, 0);
2316 log_debug_errno(r
, "Failed to enable controller %s for %s (%s): %m", n
, p
, fs
);
2323 bool cg_is_unified_wanted(void) {
2324 static thread_local
int wanted
= -1;
2327 /* If the hierarchy is already mounted, then follow whatever
2328 * was chosen for it. */
2329 unified
= cg_all_unified();
2333 /* Otherwise, let's see what the kernel command line has to
2334 * say. Since checking that is expensive, let's cache the
2339 r
= get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL
);
2341 return (wanted
= true);
2343 _cleanup_free_
char *value
= NULL
;
2345 r
= get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value
);
2349 return (wanted
= false);
2351 return (wanted
= parse_boolean(value
) > 0);
2355 bool cg_is_legacy_wanted(void) {
2356 return !cg_is_unified_wanted();
2359 bool cg_is_unified_systemd_controller_wanted(void) {
2360 static thread_local
int wanted
= -1;
2363 /* If the unified hierarchy is requested in full, no need to
2364 * bother with this. */
2365 if (cg_is_unified_wanted())
2368 /* If the hierarchy is already mounted, then follow whatever
2369 * was chosen for it. */
2370 unified
= cg_unified(SYSTEMD_CGROUP_CONTROLLER
);
2374 /* Otherwise, let's see what the kernel command line has to
2375 * say. Since checking that is expensive, let's cache the
2380 r
= get_proc_cmdline_key("systemd.legacy_systemd_cgroup_controller", NULL
);
2384 _cleanup_free_
char *value
= NULL
;
2386 r
= get_proc_cmdline_key("systemd.legacy_systemd_cgroup_controller=", &value
);
2393 wanted
= parse_boolean(value
) <= 0;
2399 bool cg_is_legacy_systemd_controller_wanted(void) {
2400 return cg_is_legacy_wanted() && !cg_is_unified_systemd_controller_wanted();
2403 int cg_weight_parse(const char *s
, uint64_t *ret
) {
2408 *ret
= CGROUP_WEIGHT_INVALID
;
2412 r
= safe_atou64(s
, &u
);
2416 if (u
< CGROUP_WEIGHT_MIN
|| u
> CGROUP_WEIGHT_MAX
)
2423 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2424 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2425 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2426 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2427 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2430 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2431 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2432 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2433 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2434 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2437 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2439 int cg_cpu_shares_parse(const char *s
, uint64_t *ret
) {
2444 *ret
= CGROUP_CPU_SHARES_INVALID
;
2448 r
= safe_atou64(s
, &u
);
2452 if (u
< CGROUP_CPU_SHARES_MIN
|| u
> CGROUP_CPU_SHARES_MAX
)
2459 int cg_blkio_weight_parse(const char *s
, uint64_t *ret
) {
2464 *ret
= CGROUP_BLKIO_WEIGHT_INVALID
;
2468 r
= safe_atou64(s
, &u
);
2472 if (u
< CGROUP_BLKIO_WEIGHT_MIN
|| u
> CGROUP_BLKIO_WEIGHT_MAX
)
2479 static const char *cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2480 [CGROUP_CONTROLLER_CPU
] = "cpu",
2481 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2482 [CGROUP_CONTROLLER_IO
] = "io",
2483 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2484 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2485 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2486 [CGROUP_CONTROLLER_PIDS
] = "pids",
2489 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);