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 "formats-util.h"
44 #include "login-util.h"
48 #include "parse-util.h"
49 #include "path-util.h"
50 #include "proc-cmdline.h"
51 #include "process-util.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 bool cg_ns_supported(void) {
139 static thread_local
int enabled
= -1;
144 if (access("/proc/self/ns/cgroup", F_OK
) == 0)
152 int cg_enumerate_subgroups(const char *controller
, const char *path
, DIR **_d
) {
153 _cleanup_free_
char *fs
= NULL
;
159 /* This is not recursive! */
161 r
= cg_get_path(controller
, path
, NULL
, &fs
);
173 int cg_read_subgroup(DIR *d
, char **fn
) {
179 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
182 if (de
->d_type
!= DT_DIR
)
185 if (streq(de
->d_name
, ".") ||
186 streq(de
->d_name
, ".."))
189 b
= strdup(de
->d_name
);
200 int cg_rmdir(const char *controller
, const char *path
) {
201 _cleanup_free_
char *p
= NULL
;
204 r
= cg_get_path(controller
, path
, NULL
, &p
);
209 if (r
< 0 && errno
!= ENOENT
)
216 const char *controller
,
221 cg_kill_log_func_t log_kill
,
224 _cleanup_set_free_ Set
*allocated_set
= NULL
;
231 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
232 * SIGCONT on SIGKILL. */
233 if (IN_SET(sig
, SIGCONT
, SIGKILL
))
234 flags
&= ~CGROUP_SIGCONT
;
236 /* This goes through the tasks list and kills them all. This
237 * is repeated until no further processes are added to the
238 * tasks list, to properly handle forking processes */
241 s
= allocated_set
= set_new(NULL
);
249 _cleanup_fclose_
FILE *f
= NULL
;
253 r
= cg_enumerate_processes(controller
, path
, &f
);
255 if (ret
>= 0 && r
!= -ENOENT
)
261 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
263 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
266 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
270 log_kill(pid
, sig
, userdata
);
272 /* If we haven't killed this process yet, kill
274 if (kill(pid
, sig
) < 0) {
275 if (ret
>= 0 && errno
!= ESRCH
)
278 if (flags
& CGROUP_SIGCONT
)
279 (void) kill(pid
, SIGCONT
);
287 r
= set_put(s
, PID_TO_PTR(pid
));
303 /* To avoid racing against processes which fork
304 * quicker than we can kill them we repeat this until
305 * no new pids need to be killed. */
312 int cg_kill_recursive(
313 const char *controller
,
318 cg_kill_log_func_t log_kill
,
321 _cleanup_set_free_ Set
*allocated_set
= NULL
;
322 _cleanup_closedir_
DIR *d
= NULL
;
330 s
= allocated_set
= set_new(NULL
);
335 ret
= cg_kill(controller
, path
, sig
, flags
, s
, log_kill
, userdata
);
337 r
= cg_enumerate_subgroups(controller
, path
, &d
);
339 if (ret
>= 0 && r
!= -ENOENT
)
345 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
346 _cleanup_free_
char *p
= NULL
;
348 p
= strjoin(path
, "/", fn
, NULL
);
353 r
= cg_kill_recursive(controller
, p
, sig
, flags
, s
, log_kill
, userdata
);
354 if (r
!= 0 && ret
>= 0)
357 if (ret
>= 0 && r
< 0)
360 if (flags
& CGROUP_REMOVE
) {
361 r
= cg_rmdir(controller
, path
);
362 if (r
< 0 && ret
>= 0 && r
!= -ENOENT
&& r
!= -EBUSY
)
377 _cleanup_set_free_ Set
*s
= NULL
;
393 _cleanup_fclose_
FILE *f
= NULL
;
397 r
= cg_enumerate_processes(cfrom
, pfrom
, &f
);
399 if (ret
>= 0 && r
!= -ENOENT
)
405 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
407 /* This might do weird stuff if we aren't a
408 * single-threaded program. However, we
409 * luckily know we are not */
410 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
413 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
416 /* Ignore kernel threads. Since they can only
417 * exist in the root cgroup, we only check for
420 (isempty(pfrom
) || path_equal(pfrom
, "/")) &&
421 is_kernel_thread(pid
) > 0)
424 r
= cg_attach(cto
, pto
, pid
);
426 if (ret
>= 0 && r
!= -ESRCH
)
433 r
= set_put(s
, PID_TO_PTR(pid
));
453 int cg_migrate_recursive(
460 _cleanup_closedir_
DIR *d
= NULL
;
469 ret
= cg_migrate(cfrom
, pfrom
, cto
, pto
, flags
);
471 r
= cg_enumerate_subgroups(cfrom
, pfrom
, &d
);
473 if (ret
>= 0 && r
!= -ENOENT
)
479 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
480 _cleanup_free_
char *p
= NULL
;
482 p
= strjoin(pfrom
, "/", fn
, NULL
);
487 r
= cg_migrate_recursive(cfrom
, p
, cto
, pto
, flags
);
488 if (r
!= 0 && ret
>= 0)
492 if (r
< 0 && ret
>= 0)
495 if (flags
& CGROUP_REMOVE
) {
496 r
= cg_rmdir(cfrom
, pfrom
);
497 if (r
< 0 && ret
>= 0 && r
!= -ENOENT
&& r
!= -EBUSY
)
504 int cg_migrate_recursive_fallback(
518 r
= cg_migrate_recursive(cfrom
, pfrom
, cto
, pto
, flags
);
520 char prefix
[strlen(pto
) + 1];
522 /* This didn't work? Then let's try all prefixes of the destination */
524 PATH_FOREACH_PREFIX(prefix
, pto
) {
527 q
= cg_migrate_recursive(cfrom
, pfrom
, cto
, prefix
, flags
);
536 static const char *controller_to_dirname(const char *controller
) {
541 /* Converts a controller name to the directory name below
542 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
543 * just cuts off the name= prefixed used for named
544 * hierarchies, if it is specified. */
546 e
= startswith(controller
, "name=");
553 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
560 dn
= controller_to_dirname(controller
);
562 if (isempty(path
) && isempty(suffix
))
563 t
= strappend("/sys/fs/cgroup/", dn
);
564 else if (isempty(path
))
565 t
= strjoin("/sys/fs/cgroup/", dn
, "/", suffix
, NULL
);
566 else if (isempty(suffix
))
567 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
, NULL
);
569 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
, "/", suffix
, NULL
);
577 static int join_path_unified(const char *path
, const char *suffix
, char **fs
) {
582 if (isempty(path
) && isempty(suffix
))
583 t
= strdup("/sys/fs/cgroup");
584 else if (isempty(path
))
585 t
= strappend("/sys/fs/cgroup/", suffix
);
586 else if (isempty(suffix
))
587 t
= strappend("/sys/fs/cgroup/", path
);
589 t
= strjoin("/sys/fs/cgroup/", path
, "/", suffix
, NULL
);
597 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
605 /* If no controller is specified, we return the path
606 * *below* the controllers, without any prefix. */
608 if (!path
&& !suffix
)
616 t
= strjoin(path
, "/", suffix
, NULL
);
620 *fs
= path_kill_slashes(t
);
624 if (!cg_controller_is_valid(controller
))
627 unified
= cg_all_unified();
632 r
= join_path_unified(path
, suffix
, fs
);
634 r
= join_path_legacy(controller
, path
, suffix
, fs
);
638 path_kill_slashes(*fs
);
642 static int controller_is_accessible(const char *controller
) {
647 /* Checks whether a specific controller is accessible,
648 * i.e. its hierarchy mounted. In the unified hierarchy all
649 * controllers are considered accessible, except for the named
652 if (!cg_controller_is_valid(controller
))
655 unified
= cg_all_unified();
659 /* We don't support named hierarchies if we are using
660 * the unified hierarchy. */
662 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
665 if (startswith(controller
, "name="))
671 dn
= controller_to_dirname(controller
);
672 cc
= strjoina("/sys/fs/cgroup/", dn
);
674 if (laccess(cc
, F_OK
) < 0)
681 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
687 /* Check if the specified controller is actually accessible */
688 r
= controller_is_accessible(controller
);
692 return cg_get_path(controller
, path
, suffix
, fs
);
695 static int trim_cb(const char *path
, const struct stat
*sb
, int typeflag
, struct FTW
*ftwbuf
) {
700 if (typeflag
!= FTW_DP
)
703 if (ftwbuf
->level
< 1)
710 int cg_trim(const char *controller
, const char *path
, bool delete_root
) {
711 _cleanup_free_
char *fs
= NULL
;
716 r
= cg_get_path(controller
, path
, NULL
, &fs
);
721 if (nftw(fs
, trim_cb
, 64, FTW_DEPTH
|FTW_MOUNT
|FTW_PHYS
) != 0) {
731 if (rmdir(fs
) < 0 && errno
!= ENOENT
)
738 int cg_create(const char *controller
, const char *path
) {
739 _cleanup_free_
char *fs
= NULL
;
742 r
= cg_get_path_and_check(controller
, path
, NULL
, &fs
);
746 r
= mkdir_parents(fs
, 0755);
750 if (mkdir(fs
, 0755) < 0) {
761 int cg_create_and_attach(const char *controller
, const char *path
, pid_t pid
) {
766 r
= cg_create(controller
, path
);
770 q
= cg_attach(controller
, path
, pid
);
774 /* This does not remove the cgroup on failure */
778 int cg_attach(const char *controller
, const char *path
, pid_t pid
) {
779 _cleanup_free_
char *fs
= NULL
;
780 char c
[DECIMAL_STR_MAX(pid_t
) + 2];
786 r
= cg_get_path_and_check(controller
, path
, "cgroup.procs", &fs
);
793 xsprintf(c
, PID_FMT
"\n", pid
);
795 return write_string_file(fs
, c
, 0);
798 int cg_attach_fallback(const char *controller
, const char *path
, pid_t pid
) {
805 r
= cg_attach(controller
, path
, pid
);
807 char prefix
[strlen(path
) + 1];
809 /* This didn't work? Then let's try all prefixes of
812 PATH_FOREACH_PREFIX(prefix
, path
) {
815 q
= cg_attach(controller
, prefix
, pid
);
824 int cg_set_group_access(
825 const char *controller
,
831 _cleanup_free_
char *fs
= NULL
;
834 if (mode
== MODE_INVALID
&& uid
== UID_INVALID
&& gid
== GID_INVALID
)
837 if (mode
!= MODE_INVALID
)
840 r
= cg_get_path(controller
, path
, NULL
, &fs
);
844 return chmod_and_chown(fs
, mode
, uid
, gid
);
847 int cg_set_task_access(
848 const char *controller
,
854 _cleanup_free_
char *fs
= NULL
, *procs
= NULL
;
859 if (mode
== MODE_INVALID
&& uid
== UID_INVALID
&& gid
== GID_INVALID
)
862 if (mode
!= MODE_INVALID
)
865 r
= cg_get_path(controller
, path
, "cgroup.procs", &fs
);
869 r
= chmod_and_chown(fs
, mode
, uid
, gid
);
873 unified
= cg_unified(controller
);
879 /* Compatibility, Always keep values for "tasks" in sync with
881 if (cg_get_path(controller
, path
, "tasks", &procs
) >= 0)
882 (void) chmod_and_chown(procs
, mode
, uid
, gid
);
887 int cg_set_xattr(const char *controller
, const char *path
, const char *name
, const void *value
, size_t size
, int flags
) {
888 _cleanup_free_
char *fs
= NULL
;
893 assert(value
|| size
<= 0);
895 r
= cg_get_path(controller
, path
, NULL
, &fs
);
899 if (setxattr(fs
, name
, value
, size
, flags
) < 0)
905 int cg_get_xattr(const char *controller
, const char *path
, const char *name
, void *value
, size_t size
) {
906 _cleanup_free_
char *fs
= NULL
;
913 r
= cg_get_path(controller
, path
, NULL
, &fs
);
917 n
= getxattr(fs
, name
, value
, size
);
924 int cg_pid_get_path(const char *controller
, pid_t pid
, char **path
) {
925 _cleanup_fclose_
FILE *f
= NULL
;
935 if (!cg_controller_is_valid(controller
))
938 controller
= SYSTEMD_CGROUP_CONTROLLER
;
940 unified
= cg_unified(controller
);
944 cs
= strlen(controller
);
946 fs
= procfs_file_alloca(pid
, "cgroup");
949 return errno
== ENOENT
? -ESRCH
: -errno
;
951 FOREACH_LINE(line
, f
, return -errno
) {
957 e
= startswith(line
, "0:");
967 const char *word
, *state
;
970 l
= strchr(line
, ':');
980 FOREACH_WORD_SEPARATOR(word
, k
, l
, ",", state
) {
981 if (k
== cs
&& memcmp(word
, controller
, cs
) == 0) {
1002 int cg_install_release_agent(const char *controller
, const char *agent
) {
1003 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
1009 unified
= cg_unified(controller
);
1012 if (unified
) /* doesn't apply to unified hierarchy */
1015 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
1019 r
= read_one_line_file(fs
, &contents
);
1023 sc
= strstrip(contents
);
1025 r
= write_string_file(fs
, agent
, 0);
1028 } else if (!path_equal(sc
, agent
))
1032 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
1036 contents
= mfree(contents
);
1037 r
= read_one_line_file(fs
, &contents
);
1041 sc
= strstrip(contents
);
1042 if (streq(sc
, "0")) {
1043 r
= write_string_file(fs
, "1", 0);
1050 if (!streq(sc
, "1"))
1056 int cg_uninstall_release_agent(const char *controller
) {
1057 _cleanup_free_
char *fs
= NULL
;
1060 unified
= cg_unified(controller
);
1063 if (unified
) /* Doesn't apply to unified hierarchy */
1066 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
1070 r
= write_string_file(fs
, "0", 0);
1076 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
1080 r
= write_string_file(fs
, "", 0);
1087 int cg_is_empty(const char *controller
, const char *path
) {
1088 _cleanup_fclose_
FILE *f
= NULL
;
1094 r
= cg_enumerate_processes(controller
, path
, &f
);
1100 r
= cg_read_pid(f
, &pid
);
1107 int cg_is_empty_recursive(const char *controller
, const char *path
) {
1112 /* The root cgroup is always populated */
1113 if (controller
&& (isempty(path
) || path_equal(path
, "/")))
1116 unified
= cg_unified(controller
);
1121 _cleanup_free_
char *t
= NULL
;
1123 /* On the unified hierarchy we can check empty state
1124 * via the "populated" attribute of "cgroup.events". */
1126 r
= cg_read_event(controller
, path
, "populated", &t
);
1130 return streq(t
, "0");
1132 _cleanup_closedir_
DIR *d
= NULL
;
1135 r
= cg_is_empty(controller
, path
);
1139 r
= cg_enumerate_subgroups(controller
, path
, &d
);
1145 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1146 _cleanup_free_
char *p
= NULL
;
1148 p
= strjoin(path
, "/", fn
, NULL
);
1153 r
= cg_is_empty_recursive(controller
, p
);
1164 int cg_split_spec(const char *spec
, char **controller
, char **path
) {
1165 char *t
= NULL
, *u
= NULL
;
1171 if (!path_is_safe(spec
))
1179 *path
= path_kill_slashes(t
);
1188 e
= strchr(spec
, ':');
1190 if (!cg_controller_is_valid(spec
))
1207 t
= strndup(spec
, e
-spec
);
1210 if (!cg_controller_is_valid(t
)) {
1224 if (!path_is_safe(u
) ||
1225 !path_is_absolute(u
)) {
1231 path_kill_slashes(u
);
1247 int cg_mangle_path(const char *path
, char **result
) {
1248 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
1255 /* First, check if it already is a filesystem path */
1256 if (path_startswith(path
, "/sys/fs/cgroup")) {
1262 *result
= path_kill_slashes(t
);
1266 /* Otherwise, treat it as cg spec */
1267 r
= cg_split_spec(path
, &c
, &p
);
1271 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, result
);
1274 int cg_get_root_path(char **path
) {
1280 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
1284 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
1286 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
1288 e
= endswith(p
, "/system"); /* even more legacy */
1296 int cg_shift_path(const char *cgroup
, const char *root
, const char **shifted
) {
1297 _cleanup_free_
char *rt
= NULL
;
1305 /* If the root was specified let's use that, otherwise
1306 * let's determine it from PID 1 */
1308 r
= cg_get_root_path(&rt
);
1315 p
= path_startswith(cgroup
, root
);
1316 if (p
&& p
> cgroup
)
1324 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **cgroup
) {
1325 _cleanup_free_
char *raw
= NULL
;
1332 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1336 r
= cg_shift_path(raw
, root
, &c
);
1356 int cg_path_decode_unit(const char *cgroup
, char **unit
) {
1363 n
= strcspn(cgroup
, "/");
1367 c
= strndupa(cgroup
, n
);
1370 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1381 static bool valid_slice_name(const char *p
, size_t n
) {
1386 if (n
< strlen("x.slice"))
1389 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1395 c
= cg_unescape(buf
);
1397 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1403 static const char *skip_slices(const char *p
) {
1406 /* Skips over all slice assignments */
1411 p
+= strspn(p
, "/");
1413 n
= strcspn(p
, "/");
1414 if (!valid_slice_name(p
, n
))
1421 int cg_path_get_unit(const char *path
, char **ret
) {
1429 e
= skip_slices(path
);
1431 r
= cg_path_decode_unit(e
, &unit
);
1435 /* We skipped over the slices, don't accept any now */
1436 if (endswith(unit
, ".slice")) {
1445 int cg_pid_get_unit(pid_t pid
, char **unit
) {
1446 _cleanup_free_
char *cgroup
= NULL
;
1451 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1455 return cg_path_get_unit(cgroup
, unit
);
1459 * Skip session-*.scope, but require it to be there.
1461 static const char *skip_session(const char *p
) {
1467 p
+= strspn(p
, "/");
1469 n
= strcspn(p
, "/");
1470 if (n
< strlen("session-x.scope"))
1473 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1474 char buf
[n
- 8 - 6 + 1];
1476 memcpy(buf
, p
+ 8, n
- 8 - 6);
1479 /* Note that session scopes never need unescaping,
1480 * since they cannot conflict with the kernel's own
1481 * names, hence we don't need to call cg_unescape()
1484 if (!session_id_valid(buf
))
1488 p
+= strspn(p
, "/");
1496 * Skip user@*.service, but require it to be there.
1498 static const char *skip_user_manager(const char *p
) {
1504 p
+= strspn(p
, "/");
1506 n
= strcspn(p
, "/");
1507 if (n
< strlen("user@x.service"))
1510 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1511 char buf
[n
- 5 - 8 + 1];
1513 memcpy(buf
, p
+ 5, n
- 5 - 8);
1516 /* Note that user manager services never need unescaping,
1517 * since they cannot conflict with the kernel's own
1518 * names, hence we don't need to call cg_unescape()
1521 if (parse_uid(buf
, NULL
) < 0)
1525 p
+= strspn(p
, "/");
1533 static const char *skip_user_prefix(const char *path
) {
1538 /* Skip slices, if there are any */
1539 e
= skip_slices(path
);
1541 /* Skip the user manager, if it's in the path now... */
1542 t
= skip_user_manager(e
);
1546 /* Alternatively skip the user session if it is in the path... */
1547 return skip_session(e
);
1550 int cg_path_get_user_unit(const char *path
, char **ret
) {
1556 t
= skip_user_prefix(path
);
1560 /* And from here on it looks pretty much the same as for a
1561 * system unit, hence let's use the same parser from here
1563 return cg_path_get_unit(t
, ret
);
1566 int cg_pid_get_user_unit(pid_t pid
, char **unit
) {
1567 _cleanup_free_
char *cgroup
= NULL
;
1572 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1576 return cg_path_get_user_unit(cgroup
, unit
);
1579 int cg_path_get_machine_name(const char *path
, char **machine
) {
1580 _cleanup_free_
char *u
= NULL
;
1584 r
= cg_path_get_unit(path
, &u
);
1588 sl
= strjoina("/run/systemd/machines/unit:", u
);
1589 return readlink_malloc(sl
, machine
);
1592 int cg_pid_get_machine_name(pid_t pid
, char **machine
) {
1593 _cleanup_free_
char *cgroup
= NULL
;
1598 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1602 return cg_path_get_machine_name(cgroup
, machine
);
1605 int cg_path_get_session(const char *path
, char **session
) {
1606 _cleanup_free_
char *unit
= NULL
;
1612 r
= cg_path_get_unit(path
, &unit
);
1616 start
= startswith(unit
, "session-");
1619 end
= endswith(start
, ".scope");
1624 if (!session_id_valid(start
))
1640 int cg_pid_get_session(pid_t pid
, char **session
) {
1641 _cleanup_free_
char *cgroup
= NULL
;
1644 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1648 return cg_path_get_session(cgroup
, session
);
1651 int cg_path_get_owner_uid(const char *path
, uid_t
*uid
) {
1652 _cleanup_free_
char *slice
= NULL
;
1658 r
= cg_path_get_slice(path
, &slice
);
1662 start
= startswith(slice
, "user-");
1665 end
= endswith(start
, ".slice");
1670 if (parse_uid(start
, uid
) < 0)
1676 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*uid
) {
1677 _cleanup_free_
char *cgroup
= NULL
;
1680 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1684 return cg_path_get_owner_uid(cgroup
, uid
);
1687 int cg_path_get_slice(const char *p
, char **slice
) {
1688 const char *e
= NULL
;
1693 /* Finds the right-most slice unit from the beginning, but
1694 * stops before we come to the first non-slice unit. */
1699 p
+= strspn(p
, "/");
1701 n
= strcspn(p
, "/");
1702 if (!valid_slice_name(p
, n
)) {
1707 s
= strdup(SPECIAL_ROOT_SLICE
);
1715 return cg_path_decode_unit(e
, slice
);
1723 int cg_pid_get_slice(pid_t pid
, char **slice
) {
1724 _cleanup_free_
char *cgroup
= NULL
;
1729 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1733 return cg_path_get_slice(cgroup
, slice
);
1736 int cg_path_get_user_slice(const char *p
, char **slice
) {
1741 t
= skip_user_prefix(p
);
1745 /* And now it looks pretty much the same as for a system
1746 * slice, so let's just use the same parser from here on. */
1747 return cg_path_get_slice(t
, slice
);
1750 int cg_pid_get_user_slice(pid_t pid
, char **slice
) {
1751 _cleanup_free_
char *cgroup
= NULL
;
1756 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1760 return cg_path_get_user_slice(cgroup
, slice
);
1763 char *cg_escape(const char *p
) {
1764 bool need_prefix
= false;
1766 /* This implements very minimal escaping for names to be used
1767 * as file names in the cgroup tree: any name which might
1768 * conflict with a kernel name or is prefixed with '_' is
1769 * prefixed with a '_'. That way, when reading cgroup names it
1770 * is sufficient to remove a single prefixing underscore if
1773 /* The return value of this function (unlike cg_unescape())
1779 streq(p
, "notify_on_release") ||
1780 streq(p
, "release_agent") ||
1781 streq(p
, "tasks") ||
1782 startswith(p
, "cgroup."))
1787 dot
= strrchr(p
, '.');
1792 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1795 n
= cgroup_controller_to_string(c
);
1800 if (memcmp(p
, n
, l
) != 0)
1810 return strappend("_", p
);
1815 char *cg_unescape(const char *p
) {
1818 /* The return value of this function (unlike cg_escape())
1819 * doesn't need free()! */
1827 #define CONTROLLER_VALID \
1831 bool cg_controller_is_valid(const char *p
) {
1837 s
= startswith(p
, "name=");
1841 if (*p
== 0 || *p
== '_')
1844 for (t
= p
; *t
; t
++)
1845 if (!strchr(CONTROLLER_VALID
, *t
))
1848 if (t
- p
> FILENAME_MAX
)
1854 int cg_slice_to_path(const char *unit
, char **ret
) {
1855 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1862 if (streq(unit
, SPECIAL_ROOT_SLICE
)) {
1872 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1875 if (!endswith(unit
, ".slice"))
1878 r
= unit_name_to_prefix(unit
, &p
);
1882 dash
= strchr(p
, '-');
1884 /* Don't allow initial dashes */
1889 _cleanup_free_
char *escaped
= NULL
;
1890 char n
[dash
- p
+ sizeof(".slice")];
1892 /* Don't allow trailing or double dashes */
1893 if (dash
[1] == 0 || dash
[1] == '-')
1896 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1897 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1900 escaped
= cg_escape(n
);
1904 if (!strextend(&s
, escaped
, "/", NULL
))
1907 dash
= strchr(dash
+1, '-');
1910 e
= cg_escape(unit
);
1914 if (!strextend(&s
, e
, NULL
))
1923 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
1924 _cleanup_free_
char *p
= NULL
;
1927 r
= cg_get_path(controller
, path
, attribute
, &p
);
1931 return write_string_file(p
, value
, 0);
1934 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
1935 _cleanup_free_
char *p
= NULL
;
1938 r
= cg_get_path(controller
, path
, attribute
, &p
);
1942 return read_one_line_file(p
, ret
);
1945 int cg_get_keyed_attribute(const char *controller
, const char *path
, const char *attribute
, const char **keys
, char **values
) {
1946 _cleanup_free_
char *filename
= NULL
, *content
= NULL
;
1950 for (i
= 0; keys
[i
]; i
++)
1953 r
= cg_get_path(controller
, path
, attribute
, &filename
);
1957 r
= read_full_file(filename
, &content
, NULL
);
1962 while ((line
= strsep(&p
, "\n"))) {
1965 key
= strsep(&line
, " ");
1967 for (i
= 0; keys
[i
]; i
++) {
1968 if (streq(key
, keys
[i
])) {
1969 values
[i
] = strdup(line
);
1975 for (i
= 0; keys
[i
]; i
++) {
1977 for (i
= 0; keys
[i
]; i
++) {
1988 int cg_create_everywhere(CGroupMask supported
, CGroupMask mask
, const char *path
) {
1992 /* This one will create a cgroup in our private tree, but also
1993 * duplicate it in the trees specified in mask, and remove it
1996 /* First create the cgroup in our own hierarchy. */
1997 r
= cg_create(SYSTEMD_CGROUP_CONTROLLER
, path
);
2001 /* If we are in the unified hierarchy, we are done now */
2002 unified
= cg_all_unified();
2008 /* Otherwise, do the same in the other hierarchies */
2009 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2010 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2013 n
= cgroup_controller_to_string(c
);
2016 (void) cg_create(n
, path
);
2017 else if (supported
& bit
)
2018 (void) cg_trim(n
, path
, true);
2024 int cg_attach_everywhere(CGroupMask supported
, const char *path
, pid_t pid
, cg_migrate_callback_t path_callback
, void *userdata
) {
2028 r
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, path
, pid
);
2032 unified
= cg_all_unified();
2038 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2039 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2040 const char *p
= NULL
;
2042 if (!(supported
& bit
))
2046 p
= path_callback(bit
, userdata
);
2051 (void) cg_attach_fallback(cgroup_controller_to_string(c
), p
, pid
);
2057 int cg_attach_many_everywhere(CGroupMask supported
, const char *path
, Set
* pids
, cg_migrate_callback_t path_callback
, void *userdata
) {
2062 SET_FOREACH(pidp
, pids
, i
) {
2063 pid_t pid
= PTR_TO_PID(pidp
);
2066 q
= cg_attach_everywhere(supported
, path
, pid
, path_callback
, userdata
);
2067 if (q
< 0 && r
>= 0)
2074 int cg_migrate_everywhere(CGroupMask supported
, const char *from
, const char *to
, cg_migrate_callback_t to_callback
, void *userdata
) {
2078 if (!path_equal(from
, to
)) {
2079 r
= cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER
, from
, SYSTEMD_CGROUP_CONTROLLER
, to
, CGROUP_REMOVE
);
2084 unified
= cg_all_unified();
2090 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2091 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2092 const char *p
= NULL
;
2094 if (!(supported
& bit
))
2098 p
= to_callback(bit
, userdata
);
2103 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER
, to
, cgroup_controller_to_string(c
), p
, 0);
2109 int cg_trim_everywhere(CGroupMask supported
, const char *path
, bool delete_root
) {
2113 r
= cg_trim(SYSTEMD_CGROUP_CONTROLLER
, path
, delete_root
);
2117 unified
= cg_all_unified();
2123 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2124 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2126 if (!(supported
& bit
))
2129 (void) cg_trim(cgroup_controller_to_string(c
), path
, delete_root
);
2135 int cg_mask_supported(CGroupMask
*ret
) {
2136 CGroupMask mask
= 0;
2139 /* Determines the mask of supported cgroup controllers. Only
2140 * includes controllers we can make sense of and that are
2141 * actually accessible. */
2143 unified
= cg_all_unified();
2147 _cleanup_free_
char *root
= NULL
, *controllers
= NULL
, *path
= NULL
;
2150 /* In the unified hierarchy we can read the supported
2151 * and accessible controllers from a the top-level
2152 * cgroup attribute */
2154 r
= cg_get_root_path(&root
);
2158 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
2162 r
= read_one_line_file(path
, &controllers
);
2168 _cleanup_free_
char *n
= NULL
;
2171 r
= extract_first_word(&c
, &n
, NULL
, 0);
2177 v
= cgroup_controller_from_string(n
);
2181 mask
|= CGROUP_CONTROLLER_TO_MASK(v
);
2184 /* Currently, we support the cpu, memory, io and pids
2185 * controller in the unified hierarchy, mask
2186 * everything else off. */
2187 mask
&= CGROUP_MASK_CPU
| CGROUP_MASK_MEMORY
| CGROUP_MASK_IO
| CGROUP_MASK_PIDS
;
2192 /* In the legacy hierarchy, we check whether which
2193 * hierarchies are mounted. */
2195 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2198 n
= cgroup_controller_to_string(c
);
2199 if (controller_is_accessible(n
) >= 0)
2200 mask
|= CGROUP_CONTROLLER_TO_MASK(c
);
2208 int cg_kernel_controllers(Set
*controllers
) {
2209 _cleanup_fclose_
FILE *f
= NULL
;
2213 assert(controllers
);
2215 /* Determines the full list of kernel-known controllers. Might
2216 * include controllers we don't actually support, arbitrary
2217 * named hierarchies and controllers that aren't currently
2218 * accessible (because not mounted). */
2220 f
= fopen("/proc/cgroups", "re");
2222 if (errno
== ENOENT
)
2227 /* Ignore the header line */
2228 (void) fgets(buf
, sizeof(buf
), f
);
2235 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
2240 if (ferror(f
) && errno
> 0)
2251 if (!cg_controller_is_valid(controller
)) {
2256 r
= set_consume(controllers
, controller
);
2264 static thread_local CGroupUnified unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2266 static int cg_update_unified(void) {
2270 /* Checks if we support the unified hierarchy. Returns an
2271 * error when the cgroup hierarchies aren't mounted yet or we
2272 * have any other trouble determining if the unified hierarchy
2275 if (unified_cache
>= CGROUP_UNIFIED_NONE
)
2278 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
2281 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
))
2282 unified_cache
= CGROUP_UNIFIED_ALL
;
2283 else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
)) {
2284 if (statfs("/sys/fs/cgroup/systemd/", &fs
) < 0)
2287 unified_cache
= F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
) ?
2288 CGROUP_UNIFIED_SYSTEMD
: CGROUP_UNIFIED_NONE
;
2295 int cg_unified(const char *controller
) {
2299 r
= cg_update_unified();
2303 if (streq_ptr(controller
, SYSTEMD_CGROUP_CONTROLLER
))
2304 return unified_cache
>= CGROUP_UNIFIED_SYSTEMD
;
2306 return unified_cache
>= CGROUP_UNIFIED_ALL
;
2309 int cg_all_unified(void) {
2311 return cg_unified(NULL
);
2314 void cg_unified_flush(void) {
2315 unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2318 int cg_enable_everywhere(CGroupMask supported
, CGroupMask mask
, const char *p
) {
2319 _cleanup_free_
char *fs
= NULL
;
2328 unified
= cg_all_unified();
2331 if (!unified
) /* on the legacy hiearchy there's no joining of controllers defined */
2334 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, p
, "cgroup.subtree_control", &fs
);
2338 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2339 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2342 if (!(supported
& bit
))
2345 n
= cgroup_controller_to_string(c
);
2347 char s
[1 + strlen(n
) + 1];
2349 s
[0] = mask
& bit
? '+' : '-';
2352 r
= write_string_file(fs
, s
, 0);
2354 log_debug_errno(r
, "Failed to enable controller %s for %s (%s): %m", n
, p
, fs
);
2361 bool cg_is_unified_wanted(void) {
2362 static thread_local
int wanted
= -1;
2365 /* If the hierarchy is already mounted, then follow whatever
2366 * was chosen for it. */
2367 unified
= cg_all_unified();
2371 /* Otherwise, let's see what the kernel command line has to
2372 * say. Since checking that is expensive, let's cache the
2377 r
= get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL
);
2379 return (wanted
= true);
2381 _cleanup_free_
char *value
= NULL
;
2383 r
= get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value
);
2387 return (wanted
= false);
2389 return (wanted
= parse_boolean(value
) > 0);
2393 bool cg_is_legacy_wanted(void) {
2394 return !cg_is_unified_wanted();
2397 bool cg_is_unified_systemd_controller_wanted(void) {
2398 static thread_local
int wanted
= -1;
2401 /* If the unified hierarchy is requested in full, no need to
2402 * bother with this. */
2403 if (cg_is_unified_wanted())
2406 /* If the hierarchy is already mounted, then follow whatever
2407 * was chosen for it. */
2408 unified
= cg_unified(SYSTEMD_CGROUP_CONTROLLER
);
2412 /* Otherwise, let's see what the kernel command line has to
2413 * say. Since checking that is expensive, let's cache the
2418 r
= get_proc_cmdline_key("systemd.legacy_systemd_cgroup_controller", NULL
);
2422 _cleanup_free_
char *value
= NULL
;
2424 r
= get_proc_cmdline_key("systemd.legacy_systemd_cgroup_controller=", &value
);
2431 wanted
= parse_boolean(value
) <= 0;
2437 bool cg_is_legacy_systemd_controller_wanted(void) {
2438 return cg_is_legacy_wanted() && !cg_is_unified_systemd_controller_wanted();
2441 int cg_weight_parse(const char *s
, uint64_t *ret
) {
2446 *ret
= CGROUP_WEIGHT_INVALID
;
2450 r
= safe_atou64(s
, &u
);
2454 if (u
< CGROUP_WEIGHT_MIN
|| u
> CGROUP_WEIGHT_MAX
)
2461 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2462 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2463 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2464 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2465 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2468 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2469 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2470 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2471 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2472 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2475 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2477 int cg_cpu_shares_parse(const char *s
, uint64_t *ret
) {
2482 *ret
= CGROUP_CPU_SHARES_INVALID
;
2486 r
= safe_atou64(s
, &u
);
2490 if (u
< CGROUP_CPU_SHARES_MIN
|| u
> CGROUP_CPU_SHARES_MAX
)
2497 int cg_blkio_weight_parse(const char *s
, uint64_t *ret
) {
2502 *ret
= CGROUP_BLKIO_WEIGHT_INVALID
;
2506 r
= safe_atou64(s
, &u
);
2510 if (u
< CGROUP_BLKIO_WEIGHT_MIN
|| u
> CGROUP_BLKIO_WEIGHT_MAX
)
2517 static const char *cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2518 [CGROUP_CONTROLLER_CPU
] = "cpu",
2519 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2520 [CGROUP_CONTROLLER_IO
] = "io",
2521 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2522 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2523 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2524 [CGROUP_CONTROLLER_PIDS
] = "pids",
2527 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);