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 int cg_enumerate_subgroups(const char *controller
, const char *path
, DIR **_d
) {
138 _cleanup_free_
char *fs
= NULL
;
144 /* This is not recursive! */
146 r
= cg_get_path(controller
, path
, NULL
, &fs
);
158 int cg_read_subgroup(DIR *d
, char **fn
) {
164 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
167 if (de
->d_type
!= DT_DIR
)
170 if (streq(de
->d_name
, ".") ||
171 streq(de
->d_name
, ".."))
174 b
= strdup(de
->d_name
);
185 int cg_rmdir(const char *controller
, const char *path
) {
186 _cleanup_free_
char *p
= NULL
;
189 r
= cg_get_path(controller
, path
, NULL
, &p
);
194 if (r
< 0 && errno
!= ENOENT
)
201 const char *controller
,
206 cg_kill_log_func_t log_kill
,
209 _cleanup_set_free_ Set
*allocated_set
= NULL
;
216 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
217 * SIGCONT on SIGKILL. */
218 if (IN_SET(sig
, SIGCONT
, SIGKILL
))
219 flags
&= ~CGROUP_SIGCONT
;
221 /* This goes through the tasks list and kills them all. This
222 * is repeated until no further processes are added to the
223 * tasks list, to properly handle forking processes */
226 s
= allocated_set
= set_new(NULL
);
234 _cleanup_fclose_
FILE *f
= NULL
;
238 r
= cg_enumerate_processes(controller
, path
, &f
);
240 if (ret
>= 0 && r
!= -ENOENT
)
246 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
248 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
251 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
255 log_kill(pid
, sig
, userdata
);
257 /* If we haven't killed this process yet, kill
259 if (kill(pid
, sig
) < 0) {
260 if (ret
>= 0 && errno
!= ESRCH
)
263 if (flags
& CGROUP_SIGCONT
)
264 (void) kill(pid
, SIGCONT
);
272 r
= set_put(s
, PID_TO_PTR(pid
));
288 /* To avoid racing against processes which fork
289 * quicker than we can kill them we repeat this until
290 * no new pids need to be killed. */
297 int cg_kill_recursive(
298 const char *controller
,
303 cg_kill_log_func_t log_kill
,
306 _cleanup_set_free_ Set
*allocated_set
= NULL
;
307 _cleanup_closedir_
DIR *d
= NULL
;
315 s
= allocated_set
= set_new(NULL
);
320 ret
= cg_kill(controller
, path
, sig
, flags
, s
, log_kill
, userdata
);
322 r
= cg_enumerate_subgroups(controller
, path
, &d
);
324 if (ret
>= 0 && r
!= -ENOENT
)
330 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
331 _cleanup_free_
char *p
= NULL
;
333 p
= strjoin(path
, "/", fn
, NULL
);
338 r
= cg_kill_recursive(controller
, p
, sig
, flags
, s
, log_kill
, userdata
);
339 if (r
!= 0 && ret
>= 0)
342 if (ret
>= 0 && r
< 0)
345 if (flags
& CGROUP_REMOVE
) {
346 r
= cg_rmdir(controller
, path
);
347 if (r
< 0 && ret
>= 0 && r
!= -ENOENT
&& r
!= -EBUSY
)
362 _cleanup_set_free_ Set
*s
= NULL
;
378 _cleanup_fclose_
FILE *f
= NULL
;
382 r
= cg_enumerate_processes(cfrom
, pfrom
, &f
);
384 if (ret
>= 0 && r
!= -ENOENT
)
390 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
392 /* This might do weird stuff if we aren't a
393 * single-threaded program. However, we
394 * luckily know we are not */
395 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
398 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
401 /* Ignore kernel threads. Since they can only
402 * exist in the root cgroup, we only check for
405 (isempty(pfrom
) || path_equal(pfrom
, "/")) &&
406 is_kernel_thread(pid
) > 0)
409 r
= cg_attach(cto
, pto
, pid
);
411 if (ret
>= 0 && r
!= -ESRCH
)
418 r
= set_put(s
, PID_TO_PTR(pid
));
438 int cg_migrate_recursive(
445 _cleanup_closedir_
DIR *d
= NULL
;
454 ret
= cg_migrate(cfrom
, pfrom
, cto
, pto
, flags
);
456 r
= cg_enumerate_subgroups(cfrom
, pfrom
, &d
);
458 if (ret
>= 0 && r
!= -ENOENT
)
464 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
465 _cleanup_free_
char *p
= NULL
;
467 p
= strjoin(pfrom
, "/", fn
, NULL
);
472 r
= cg_migrate_recursive(cfrom
, p
, cto
, pto
, flags
);
473 if (r
!= 0 && ret
>= 0)
477 if (r
< 0 && ret
>= 0)
480 if (flags
& CGROUP_REMOVE
) {
481 r
= cg_rmdir(cfrom
, pfrom
);
482 if (r
< 0 && ret
>= 0 && r
!= -ENOENT
&& r
!= -EBUSY
)
489 int cg_migrate_recursive_fallback(
503 r
= cg_migrate_recursive(cfrom
, pfrom
, cto
, pto
, flags
);
505 char prefix
[strlen(pto
) + 1];
507 /* This didn't work? Then let's try all prefixes of the destination */
509 PATH_FOREACH_PREFIX(prefix
, pto
) {
512 q
= cg_migrate_recursive(cfrom
, pfrom
, cto
, prefix
, flags
);
521 static const char *controller_to_dirname(const char *controller
) {
526 /* Converts a controller name to the directory name below
527 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
528 * just cuts off the name= prefixed used for named
529 * hierarchies, if it is specified. */
531 e
= startswith(controller
, "name=");
538 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
545 dn
= controller_to_dirname(controller
);
547 if (isempty(path
) && isempty(suffix
))
548 t
= strappend("/sys/fs/cgroup/", dn
);
549 else if (isempty(path
))
550 t
= strjoin("/sys/fs/cgroup/", dn
, "/", suffix
, NULL
);
551 else if (isempty(suffix
))
552 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
, NULL
);
554 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
, "/", suffix
, NULL
);
562 static int join_path_unified(const char *path
, const char *suffix
, char **fs
) {
567 if (isempty(path
) && isempty(suffix
))
568 t
= strdup("/sys/fs/cgroup");
569 else if (isempty(path
))
570 t
= strappend("/sys/fs/cgroup/", suffix
);
571 else if (isempty(suffix
))
572 t
= strappend("/sys/fs/cgroup/", path
);
574 t
= strjoin("/sys/fs/cgroup/", path
, "/", suffix
, NULL
);
582 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
590 /* If no controller is specified, we return the path
591 * *below* the controllers, without any prefix. */
593 if (!path
&& !suffix
)
601 t
= strjoin(path
, "/", suffix
, NULL
);
605 *fs
= path_kill_slashes(t
);
609 if (!cg_controller_is_valid(controller
))
612 unified
= cg_unified();
617 r
= join_path_unified(path
, suffix
, fs
);
619 r
= join_path_legacy(controller
, path
, suffix
, fs
);
623 path_kill_slashes(*fs
);
627 static int controller_is_accessible(const char *controller
) {
632 /* Checks whether a specific controller is accessible,
633 * i.e. its hierarchy mounted. In the unified hierarchy all
634 * controllers are considered accessible, except for the named
637 if (!cg_controller_is_valid(controller
))
640 unified
= cg_unified();
644 /* We don't support named hierarchies if we are using
645 * the unified hierarchy. */
647 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
650 if (startswith(controller
, "name="))
656 dn
= controller_to_dirname(controller
);
657 cc
= strjoina("/sys/fs/cgroup/", dn
);
659 if (laccess(cc
, F_OK
) < 0)
666 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
672 /* Check if the specified controller is actually accessible */
673 r
= controller_is_accessible(controller
);
677 return cg_get_path(controller
, path
, suffix
, fs
);
680 static int trim_cb(const char *path
, const struct stat
*sb
, int typeflag
, struct FTW
*ftwbuf
) {
685 if (typeflag
!= FTW_DP
)
688 if (ftwbuf
->level
< 1)
695 int cg_trim(const char *controller
, const char *path
, bool delete_root
) {
696 _cleanup_free_
char *fs
= NULL
;
701 r
= cg_get_path(controller
, path
, NULL
, &fs
);
706 if (nftw(fs
, trim_cb
, 64, FTW_DEPTH
|FTW_MOUNT
|FTW_PHYS
) != 0) {
716 if (rmdir(fs
) < 0 && errno
!= ENOENT
)
723 int cg_create(const char *controller
, const char *path
) {
724 _cleanup_free_
char *fs
= NULL
;
727 r
= cg_get_path_and_check(controller
, path
, NULL
, &fs
);
731 r
= mkdir_parents(fs
, 0755);
735 if (mkdir(fs
, 0755) < 0) {
746 int cg_create_and_attach(const char *controller
, const char *path
, pid_t pid
) {
751 r
= cg_create(controller
, path
);
755 q
= cg_attach(controller
, path
, pid
);
759 /* This does not remove the cgroup on failure */
763 int cg_attach(const char *controller
, const char *path
, pid_t pid
) {
764 _cleanup_free_
char *fs
= NULL
;
765 char c
[DECIMAL_STR_MAX(pid_t
) + 2];
771 r
= cg_get_path_and_check(controller
, path
, "cgroup.procs", &fs
);
778 xsprintf(c
, PID_FMT
"\n", pid
);
780 return write_string_file(fs
, c
, 0);
783 int cg_attach_fallback(const char *controller
, const char *path
, pid_t pid
) {
790 r
= cg_attach(controller
, path
, pid
);
792 char prefix
[strlen(path
) + 1];
794 /* This didn't work? Then let's try all prefixes of
797 PATH_FOREACH_PREFIX(prefix
, path
) {
800 q
= cg_attach(controller
, prefix
, pid
);
809 int cg_set_group_access(
810 const char *controller
,
816 _cleanup_free_
char *fs
= NULL
;
819 if (mode
== MODE_INVALID
&& uid
== UID_INVALID
&& gid
== GID_INVALID
)
822 if (mode
!= MODE_INVALID
)
825 r
= cg_get_path(controller
, path
, NULL
, &fs
);
829 return chmod_and_chown(fs
, mode
, uid
, gid
);
832 int cg_set_task_access(
833 const char *controller
,
839 _cleanup_free_
char *fs
= NULL
, *procs
= NULL
;
844 if (mode
== MODE_INVALID
&& uid
== UID_INVALID
&& gid
== GID_INVALID
)
847 if (mode
!= MODE_INVALID
)
850 r
= cg_get_path(controller
, path
, "cgroup.procs", &fs
);
854 r
= chmod_and_chown(fs
, mode
, uid
, gid
);
858 unified
= cg_unified();
864 /* Compatibility, Always keep values for "tasks" in sync with
866 if (cg_get_path(controller
, path
, "tasks", &procs
) >= 0)
867 (void) chmod_and_chown(procs
, mode
, uid
, gid
);
872 int cg_pid_get_path(const char *controller
, pid_t pid
, char **path
) {
873 _cleanup_fclose_
FILE *f
= NULL
;
882 unified
= cg_unified();
887 if (!cg_controller_is_valid(controller
))
890 controller
= SYSTEMD_CGROUP_CONTROLLER
;
892 cs
= strlen(controller
);
895 fs
= procfs_file_alloca(pid
, "cgroup");
898 return errno
== ENOENT
? -ESRCH
: -errno
;
900 FOREACH_LINE(line
, f
, return -errno
) {
906 e
= startswith(line
, "0:");
916 const char *word
, *state
;
919 l
= strchr(line
, ':');
929 FOREACH_WORD_SEPARATOR(word
, k
, l
, ",", state
) {
930 if (k
== cs
&& memcmp(word
, controller
, cs
) == 0) {
951 int cg_install_release_agent(const char *controller
, const char *agent
) {
952 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
958 unified
= cg_unified();
961 if (unified
) /* doesn't apply to unified hierarchy */
964 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
968 r
= read_one_line_file(fs
, &contents
);
972 sc
= strstrip(contents
);
974 r
= write_string_file(fs
, agent
, 0);
977 } else if (!path_equal(sc
, agent
))
981 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
985 contents
= mfree(contents
);
986 r
= read_one_line_file(fs
, &contents
);
990 sc
= strstrip(contents
);
991 if (streq(sc
, "0")) {
992 r
= write_string_file(fs
, "1", 0);
1005 int cg_uninstall_release_agent(const char *controller
) {
1006 _cleanup_free_
char *fs
= NULL
;
1009 unified
= cg_unified();
1012 if (unified
) /* Doesn't apply to unified hierarchy */
1015 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
1019 r
= write_string_file(fs
, "0", 0);
1025 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
1029 r
= write_string_file(fs
, "", 0);
1036 int cg_is_empty(const char *controller
, const char *path
) {
1037 _cleanup_fclose_
FILE *f
= NULL
;
1043 r
= cg_enumerate_processes(controller
, path
, &f
);
1049 r
= cg_read_pid(f
, &pid
);
1056 int cg_is_empty_recursive(const char *controller
, const char *path
) {
1061 /* The root cgroup is always populated */
1062 if (controller
&& (isempty(path
) || path_equal(path
, "/")))
1065 unified
= cg_unified();
1070 _cleanup_free_
char *t
= NULL
;
1072 /* On the unified hierarchy we can check empty state
1073 * via the "populated" attribute of "cgroup.events". */
1075 r
= cg_read_event(controller
, path
, "populated", &t
);
1079 return streq(t
, "0");
1081 _cleanup_closedir_
DIR *d
= NULL
;
1084 r
= cg_is_empty(controller
, path
);
1088 r
= cg_enumerate_subgroups(controller
, path
, &d
);
1094 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1095 _cleanup_free_
char *p
= NULL
;
1097 p
= strjoin(path
, "/", fn
, NULL
);
1102 r
= cg_is_empty_recursive(controller
, p
);
1113 int cg_split_spec(const char *spec
, char **controller
, char **path
) {
1114 char *t
= NULL
, *u
= NULL
;
1120 if (!path_is_safe(spec
))
1128 *path
= path_kill_slashes(t
);
1137 e
= strchr(spec
, ':');
1139 if (!cg_controller_is_valid(spec
))
1156 t
= strndup(spec
, e
-spec
);
1159 if (!cg_controller_is_valid(t
)) {
1173 if (!path_is_safe(u
) ||
1174 !path_is_absolute(u
)) {
1180 path_kill_slashes(u
);
1196 int cg_mangle_path(const char *path
, char **result
) {
1197 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
1204 /* First, check if it already is a filesystem path */
1205 if (path_startswith(path
, "/sys/fs/cgroup")) {
1211 *result
= path_kill_slashes(t
);
1215 /* Otherwise, treat it as cg spec */
1216 r
= cg_split_spec(path
, &c
, &p
);
1220 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, result
);
1223 int cg_get_root_path(char **path
) {
1229 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
1233 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
1235 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
1237 e
= endswith(p
, "/system"); /* even more legacy */
1245 int cg_shift_path(const char *cgroup
, const char *root
, const char **shifted
) {
1246 _cleanup_free_
char *rt
= NULL
;
1254 /* If the root was specified let's use that, otherwise
1255 * let's determine it from PID 1 */
1257 r
= cg_get_root_path(&rt
);
1264 p
= path_startswith(cgroup
, root
);
1265 if (p
&& p
> cgroup
)
1273 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **cgroup
) {
1274 _cleanup_free_
char *raw
= NULL
;
1281 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1285 r
= cg_shift_path(raw
, root
, &c
);
1305 int cg_path_decode_unit(const char *cgroup
, char **unit
) {
1312 n
= strcspn(cgroup
, "/");
1316 c
= strndupa(cgroup
, n
);
1319 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1330 static bool valid_slice_name(const char *p
, size_t n
) {
1335 if (n
< strlen("x.slice"))
1338 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1344 c
= cg_unescape(buf
);
1346 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1352 static const char *skip_slices(const char *p
) {
1355 /* Skips over all slice assignments */
1360 p
+= strspn(p
, "/");
1362 n
= strcspn(p
, "/");
1363 if (!valid_slice_name(p
, n
))
1370 int cg_path_get_unit(const char *path
, char **ret
) {
1378 e
= skip_slices(path
);
1380 r
= cg_path_decode_unit(e
, &unit
);
1384 /* We skipped over the slices, don't accept any now */
1385 if (endswith(unit
, ".slice")) {
1394 int cg_pid_get_unit(pid_t pid
, char **unit
) {
1395 _cleanup_free_
char *cgroup
= NULL
;
1400 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1404 return cg_path_get_unit(cgroup
, unit
);
1408 * Skip session-*.scope, but require it to be there.
1410 static const char *skip_session(const char *p
) {
1416 p
+= strspn(p
, "/");
1418 n
= strcspn(p
, "/");
1419 if (n
< strlen("session-x.scope"))
1422 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1423 char buf
[n
- 8 - 6 + 1];
1425 memcpy(buf
, p
+ 8, n
- 8 - 6);
1428 /* Note that session scopes never need unescaping,
1429 * since they cannot conflict with the kernel's own
1430 * names, hence we don't need to call cg_unescape()
1433 if (!session_id_valid(buf
))
1437 p
+= strspn(p
, "/");
1445 * Skip user@*.service, but require it to be there.
1447 static const char *skip_user_manager(const char *p
) {
1453 p
+= strspn(p
, "/");
1455 n
= strcspn(p
, "/");
1456 if (n
< strlen("user@x.service"))
1459 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1460 char buf
[n
- 5 - 8 + 1];
1462 memcpy(buf
, p
+ 5, n
- 5 - 8);
1465 /* Note that user manager services never need unescaping,
1466 * since they cannot conflict with the kernel's own
1467 * names, hence we don't need to call cg_unescape()
1470 if (parse_uid(buf
, NULL
) < 0)
1474 p
+= strspn(p
, "/");
1482 static const char *skip_user_prefix(const char *path
) {
1487 /* Skip slices, if there are any */
1488 e
= skip_slices(path
);
1490 /* Skip the user manager, if it's in the path now... */
1491 t
= skip_user_manager(e
);
1495 /* Alternatively skip the user session if it is in the path... */
1496 return skip_session(e
);
1499 int cg_path_get_user_unit(const char *path
, char **ret
) {
1505 t
= skip_user_prefix(path
);
1509 /* And from here on it looks pretty much the same as for a
1510 * system unit, hence let's use the same parser from here
1512 return cg_path_get_unit(t
, ret
);
1515 int cg_pid_get_user_unit(pid_t pid
, char **unit
) {
1516 _cleanup_free_
char *cgroup
= NULL
;
1521 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1525 return cg_path_get_user_unit(cgroup
, unit
);
1528 int cg_path_get_machine_name(const char *path
, char **machine
) {
1529 _cleanup_free_
char *u
= NULL
;
1533 r
= cg_path_get_unit(path
, &u
);
1537 sl
= strjoina("/run/systemd/machines/unit:", u
);
1538 return readlink_malloc(sl
, machine
);
1541 int cg_pid_get_machine_name(pid_t pid
, char **machine
) {
1542 _cleanup_free_
char *cgroup
= NULL
;
1547 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1551 return cg_path_get_machine_name(cgroup
, machine
);
1554 int cg_path_get_session(const char *path
, char **session
) {
1555 _cleanup_free_
char *unit
= NULL
;
1561 r
= cg_path_get_unit(path
, &unit
);
1565 start
= startswith(unit
, "session-");
1568 end
= endswith(start
, ".scope");
1573 if (!session_id_valid(start
))
1589 int cg_pid_get_session(pid_t pid
, char **session
) {
1590 _cleanup_free_
char *cgroup
= NULL
;
1593 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1597 return cg_path_get_session(cgroup
, session
);
1600 int cg_path_get_owner_uid(const char *path
, uid_t
*uid
) {
1601 _cleanup_free_
char *slice
= NULL
;
1607 r
= cg_path_get_slice(path
, &slice
);
1611 start
= startswith(slice
, "user-");
1614 end
= endswith(start
, ".slice");
1619 if (parse_uid(start
, uid
) < 0)
1625 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*uid
) {
1626 _cleanup_free_
char *cgroup
= NULL
;
1629 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1633 return cg_path_get_owner_uid(cgroup
, uid
);
1636 int cg_path_get_slice(const char *p
, char **slice
) {
1637 const char *e
= NULL
;
1642 /* Finds the right-most slice unit from the beginning, but
1643 * stops before we come to the first non-slice unit. */
1648 p
+= strspn(p
, "/");
1650 n
= strcspn(p
, "/");
1651 if (!valid_slice_name(p
, n
)) {
1656 s
= strdup("-.slice");
1664 return cg_path_decode_unit(e
, slice
);
1672 int cg_pid_get_slice(pid_t pid
, char **slice
) {
1673 _cleanup_free_
char *cgroup
= NULL
;
1678 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1682 return cg_path_get_slice(cgroup
, slice
);
1685 int cg_path_get_user_slice(const char *p
, char **slice
) {
1690 t
= skip_user_prefix(p
);
1694 /* And now it looks pretty much the same as for a system
1695 * slice, so let's just use the same parser from here on. */
1696 return cg_path_get_slice(t
, slice
);
1699 int cg_pid_get_user_slice(pid_t pid
, char **slice
) {
1700 _cleanup_free_
char *cgroup
= NULL
;
1705 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1709 return cg_path_get_user_slice(cgroup
, slice
);
1712 char *cg_escape(const char *p
) {
1713 bool need_prefix
= false;
1715 /* This implements very minimal escaping for names to be used
1716 * as file names in the cgroup tree: any name which might
1717 * conflict with a kernel name or is prefixed with '_' is
1718 * prefixed with a '_'. That way, when reading cgroup names it
1719 * is sufficient to remove a single prefixing underscore if
1722 /* The return value of this function (unlike cg_unescape())
1728 streq(p
, "notify_on_release") ||
1729 streq(p
, "release_agent") ||
1730 streq(p
, "tasks") ||
1731 startswith(p
, "cgroup."))
1736 dot
= strrchr(p
, '.');
1741 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1744 n
= cgroup_controller_to_string(c
);
1749 if (memcmp(p
, n
, l
) != 0)
1759 return strappend("_", p
);
1764 char *cg_unescape(const char *p
) {
1767 /* The return value of this function (unlike cg_escape())
1768 * doesn't need free()! */
1776 #define CONTROLLER_VALID \
1780 bool cg_controller_is_valid(const char *p
) {
1786 s
= startswith(p
, "name=");
1790 if (*p
== 0 || *p
== '_')
1793 for (t
= p
; *t
; t
++)
1794 if (!strchr(CONTROLLER_VALID
, *t
))
1797 if (t
- p
> FILENAME_MAX
)
1803 int cg_slice_to_path(const char *unit
, char **ret
) {
1804 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1811 if (streq(unit
, "-.slice")) {
1821 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1824 if (!endswith(unit
, ".slice"))
1827 r
= unit_name_to_prefix(unit
, &p
);
1831 dash
= strchr(p
, '-');
1833 /* Don't allow initial dashes */
1838 _cleanup_free_
char *escaped
= NULL
;
1839 char n
[dash
- p
+ sizeof(".slice")];
1841 /* Don't allow trailing or double dashes */
1842 if (dash
[1] == 0 || dash
[1] == '-')
1845 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1846 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1849 escaped
= cg_escape(n
);
1853 if (!strextend(&s
, escaped
, "/", NULL
))
1856 dash
= strchr(dash
+1, '-');
1859 e
= cg_escape(unit
);
1863 if (!strextend(&s
, e
, NULL
))
1872 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
1873 _cleanup_free_
char *p
= NULL
;
1876 r
= cg_get_path(controller
, path
, attribute
, &p
);
1880 return write_string_file(p
, value
, 0);
1883 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
1884 _cleanup_free_
char *p
= NULL
;
1887 r
= cg_get_path(controller
, path
, attribute
, &p
);
1891 return read_one_line_file(p
, ret
);
1894 int cg_create_everywhere(CGroupMask supported
, CGroupMask mask
, const char *path
) {
1898 /* This one will create a cgroup in our private tree, but also
1899 * duplicate it in the trees specified in mask, and remove it
1902 /* First create the cgroup in our own hierarchy. */
1903 r
= cg_create(SYSTEMD_CGROUP_CONTROLLER
, path
);
1907 /* If we are in the unified hierarchy, we are done now */
1908 unified
= cg_unified();
1914 /* Otherwise, do the same in the other hierarchies */
1915 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1916 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1919 n
= cgroup_controller_to_string(c
);
1922 (void) cg_create(n
, path
);
1923 else if (supported
& bit
)
1924 (void) cg_trim(n
, path
, true);
1930 int cg_attach_everywhere(CGroupMask supported
, const char *path
, pid_t pid
, cg_migrate_callback_t path_callback
, void *userdata
) {
1934 r
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, path
, pid
);
1938 unified
= cg_unified();
1944 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1945 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1946 const char *p
= NULL
;
1948 if (!(supported
& bit
))
1952 p
= path_callback(bit
, userdata
);
1957 (void) cg_attach_fallback(cgroup_controller_to_string(c
), p
, pid
);
1963 int cg_attach_many_everywhere(CGroupMask supported
, const char *path
, Set
* pids
, cg_migrate_callback_t path_callback
, void *userdata
) {
1968 SET_FOREACH(pidp
, pids
, i
) {
1969 pid_t pid
= PTR_TO_PID(pidp
);
1972 q
= cg_attach_everywhere(supported
, path
, pid
, path_callback
, userdata
);
1973 if (q
< 0 && r
>= 0)
1980 int cg_migrate_everywhere(CGroupMask supported
, const char *from
, const char *to
, cg_migrate_callback_t to_callback
, void *userdata
) {
1984 if (!path_equal(from
, to
)) {
1985 r
= cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER
, from
, SYSTEMD_CGROUP_CONTROLLER
, to
, CGROUP_REMOVE
);
1990 unified
= cg_unified();
1996 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1997 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1998 const char *p
= NULL
;
2000 if (!(supported
& bit
))
2004 p
= to_callback(bit
, userdata
);
2009 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER
, to
, cgroup_controller_to_string(c
), p
, 0);
2015 int cg_trim_everywhere(CGroupMask supported
, const char *path
, bool delete_root
) {
2019 r
= cg_trim(SYSTEMD_CGROUP_CONTROLLER
, path
, delete_root
);
2023 unified
= cg_unified();
2029 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2030 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2032 if (!(supported
& bit
))
2035 (void) cg_trim(cgroup_controller_to_string(c
), path
, delete_root
);
2041 int cg_mask_supported(CGroupMask
*ret
) {
2042 CGroupMask mask
= 0;
2045 /* Determines the mask of supported cgroup controllers. Only
2046 * includes controllers we can make sense of and that are
2047 * actually accessible. */
2049 unified
= cg_unified();
2053 _cleanup_free_
char *root
= NULL
, *controllers
= NULL
, *path
= NULL
;
2056 /* In the unified hierarchy we can read the supported
2057 * and accessible controllers from a the top-level
2058 * cgroup attribute */
2060 r
= cg_get_root_path(&root
);
2064 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
2068 r
= read_one_line_file(path
, &controllers
);
2074 _cleanup_free_
char *n
= NULL
;
2077 r
= extract_first_word(&c
, &n
, NULL
, 0);
2083 v
= cgroup_controller_from_string(n
);
2087 mask
|= CGROUP_CONTROLLER_TO_MASK(v
);
2090 /* Currently, we only support the memory, io and pids
2091 * controller in the unified hierarchy, mask
2092 * everything else off. */
2093 mask
&= CGROUP_MASK_MEMORY
| CGROUP_MASK_IO
| CGROUP_MASK_PIDS
;
2098 /* In the legacy hierarchy, we check whether which
2099 * hierarchies are mounted. */
2101 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2104 n
= cgroup_controller_to_string(c
);
2105 if (controller_is_accessible(n
) >= 0)
2106 mask
|= CGROUP_CONTROLLER_TO_MASK(c
);
2114 int cg_kernel_controllers(Set
*controllers
) {
2115 _cleanup_fclose_
FILE *f
= NULL
;
2119 assert(controllers
);
2121 /* Determines the full list of kernel-known controllers. Might
2122 * include controllers we don't actually support, arbitrary
2123 * named hierarchies and controllers that aren't currently
2124 * accessible (because not mounted). */
2126 f
= fopen("/proc/cgroups", "re");
2128 if (errno
== ENOENT
)
2133 /* Ignore the header line */
2134 (void) fgets(buf
, sizeof(buf
), f
);
2141 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
2146 if (ferror(f
) && errno
> 0)
2157 if (!cg_controller_is_valid(controller
)) {
2162 r
= set_consume(controllers
, controller
);
2170 static thread_local
int unified_cache
= -1;
2172 int cg_unified(void) {
2175 /* Checks if we support the unified hierarchy. Returns an
2176 * error when the cgroup hierarchies aren't mounted yet or we
2177 * have any other trouble determining if the unified hierarchy
2180 if (unified_cache
>= 0)
2181 return unified_cache
;
2183 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
2186 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
))
2187 unified_cache
= true;
2188 else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
))
2189 unified_cache
= false;
2193 return unified_cache
;
2196 void cg_unified_flush(void) {
2200 int cg_enable_everywhere(CGroupMask supported
, CGroupMask mask
, const char *p
) {
2201 _cleanup_free_
char *fs
= NULL
;
2210 unified
= cg_unified();
2213 if (!unified
) /* on the legacy hiearchy there's no joining of controllers defined */
2216 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, p
, "cgroup.subtree_control", &fs
);
2220 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2221 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2224 if (!(supported
& bit
))
2227 n
= cgroup_controller_to_string(c
);
2229 char s
[1 + strlen(n
) + 1];
2231 s
[0] = mask
& bit
? '+' : '-';
2234 r
= write_string_file(fs
, s
, 0);
2236 log_debug_errno(r
, "Failed to enable controller %s for %s (%s): %m", n
, p
, fs
);
2243 bool cg_is_unified_wanted(void) {
2244 static thread_local
int wanted
= -1;
2247 /* If the hierarchy is already mounted, then follow whatever
2248 * was chosen for it. */
2249 unified
= cg_unified();
2253 /* Otherwise, let's see what the kernel command line has to
2254 * say. Since checking that is expensive, let's cache the
2259 r
= get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL
);
2261 return (wanted
= true);
2263 _cleanup_free_
char *value
= NULL
;
2265 r
= get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value
);
2269 return (wanted
= false);
2271 return (wanted
= parse_boolean(value
) > 0);
2275 bool cg_is_legacy_wanted(void) {
2276 return !cg_is_unified_wanted();
2279 int cg_weight_parse(const char *s
, uint64_t *ret
) {
2284 *ret
= CGROUP_WEIGHT_INVALID
;
2288 r
= safe_atou64(s
, &u
);
2292 if (u
< CGROUP_WEIGHT_MIN
|| u
> CGROUP_WEIGHT_MAX
)
2299 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2300 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2301 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2302 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2303 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2306 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2307 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2308 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2309 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2310 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2313 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2315 int cg_cpu_shares_parse(const char *s
, uint64_t *ret
) {
2320 *ret
= CGROUP_CPU_SHARES_INVALID
;
2324 r
= safe_atou64(s
, &u
);
2328 if (u
< CGROUP_CPU_SHARES_MIN
|| u
> CGROUP_CPU_SHARES_MAX
)
2335 int cg_blkio_weight_parse(const char *s
, uint64_t *ret
) {
2340 *ret
= CGROUP_BLKIO_WEIGHT_INVALID
;
2344 r
= safe_atou64(s
, &u
);
2348 if (u
< CGROUP_BLKIO_WEIGHT_MIN
|| u
> CGROUP_BLKIO_WEIGHT_MAX
)
2355 static const char *cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2356 [CGROUP_CONTROLLER_CPU
] = "cpu",
2357 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2358 [CGROUP_CONTROLLER_IO
] = "io",
2359 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2360 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2361 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2362 [CGROUP_CONTROLLER_PIDS
] = "pids",
2365 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);