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
)
200 int cg_kill(const char *controller
, const char *path
, int sig
, bool sigcont
, bool ignore_self
, Set
*s
) {
201 _cleanup_set_free_ Set
*allocated_set
= NULL
;
208 /* This goes through the tasks list and kills them all. This
209 * is repeated until no further processes are added to the
210 * tasks list, to properly handle forking processes */
213 s
= allocated_set
= set_new(NULL
);
221 _cleanup_fclose_
FILE *f
= NULL
;
225 r
= cg_enumerate_processes(controller
, path
, &f
);
227 if (ret
>= 0 && r
!= -ENOENT
)
233 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
235 if (ignore_self
&& pid
== my_pid
)
238 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
241 /* If we haven't killed this process yet, kill
243 if (kill(pid
, sig
) < 0) {
244 if (ret
>= 0 && errno
!= ESRCH
)
247 if (sigcont
&& sig
!= SIGKILL
)
248 (void) kill(pid
, SIGCONT
);
256 r
= set_put(s
, PID_TO_PTR(pid
));
272 /* To avoid racing against processes which fork
273 * quicker than we can kill them we repeat this until
274 * no new pids need to be killed. */
281 int cg_kill_recursive(const char *controller
, const char *path
, int sig
, bool sigcont
, bool ignore_self
, bool rem
, Set
*s
) {
282 _cleanup_set_free_ Set
*allocated_set
= NULL
;
283 _cleanup_closedir_
DIR *d
= NULL
;
291 s
= allocated_set
= set_new(NULL
);
296 ret
= cg_kill(controller
, path
, sig
, sigcont
, ignore_self
, s
);
298 r
= cg_enumerate_subgroups(controller
, path
, &d
);
300 if (ret
>= 0 && r
!= -ENOENT
)
306 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
307 _cleanup_free_
char *p
= NULL
;
309 p
= strjoin(path
, "/", fn
, NULL
);
314 r
= cg_kill_recursive(controller
, p
, sig
, sigcont
, ignore_self
, rem
, s
);
315 if (r
!= 0 && ret
>= 0)
319 if (ret
>= 0 && r
< 0)
323 r
= cg_rmdir(controller
, path
);
324 if (r
< 0 && ret
>= 0 && r
!= -ENOENT
&& r
!= -EBUSY
)
331 int cg_migrate(const char *cfrom
, const char *pfrom
, const char *cto
, const char *pto
, bool ignore_self
) {
333 _cleanup_set_free_ Set
*s
= NULL
;
349 _cleanup_fclose_
FILE *f
= NULL
;
353 r
= cg_enumerate_processes(cfrom
, pfrom
, &f
);
355 if (ret
>= 0 && r
!= -ENOENT
)
361 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
363 /* This might do weird stuff if we aren't a
364 * single-threaded program. However, we
365 * luckily know we are not */
366 if (ignore_self
&& pid
== my_pid
)
369 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
372 /* Ignore kernel threads. Since they can only
373 * exist in the root cgroup, we only check for
376 (isempty(pfrom
) || path_equal(pfrom
, "/")) &&
377 is_kernel_thread(pid
) > 0)
380 r
= cg_attach(cto
, pto
, pid
);
382 if (ret
>= 0 && r
!= -ESRCH
)
389 r
= set_put(s
, PID_TO_PTR(pid
));
409 int cg_migrate_recursive(
417 _cleanup_closedir_
DIR *d
= NULL
;
426 ret
= cg_migrate(cfrom
, pfrom
, cto
, pto
, ignore_self
);
428 r
= cg_enumerate_subgroups(cfrom
, pfrom
, &d
);
430 if (ret
>= 0 && r
!= -ENOENT
)
436 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
437 _cleanup_free_
char *p
= NULL
;
439 p
= strjoin(pfrom
, "/", fn
, NULL
);
444 r
= cg_migrate_recursive(cfrom
, p
, cto
, pto
, ignore_self
, rem
);
445 if (r
!= 0 && ret
>= 0)
449 if (r
< 0 && ret
>= 0)
453 r
= cg_rmdir(cfrom
, pfrom
);
454 if (r
< 0 && ret
>= 0 && r
!= -ENOENT
&& r
!= -EBUSY
)
461 int cg_migrate_recursive_fallback(
476 r
= cg_migrate_recursive(cfrom
, pfrom
, cto
, pto
, ignore_self
, rem
);
478 char prefix
[strlen(pto
) + 1];
480 /* This didn't work? Then let's try all prefixes of the destination */
482 PATH_FOREACH_PREFIX(prefix
, pto
) {
485 q
= cg_migrate_recursive(cfrom
, pfrom
, cto
, prefix
, ignore_self
, rem
);
494 static const char *controller_to_dirname(const char *controller
) {
499 /* Converts a controller name to the directory name below
500 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
501 * just cuts off the name= prefixed used for named
502 * hierarchies, if it is specified. */
504 e
= startswith(controller
, "name=");
511 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
518 dn
= controller_to_dirname(controller
);
520 if (isempty(path
) && isempty(suffix
))
521 t
= strappend("/sys/fs/cgroup/", dn
);
522 else if (isempty(path
))
523 t
= strjoin("/sys/fs/cgroup/", dn
, "/", suffix
, NULL
);
524 else if (isempty(suffix
))
525 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
, NULL
);
527 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
, "/", suffix
, NULL
);
535 static int join_path_unified(const char *path
, const char *suffix
, char **fs
) {
540 if (isempty(path
) && isempty(suffix
))
541 t
= strdup("/sys/fs/cgroup");
542 else if (isempty(path
))
543 t
= strappend("/sys/fs/cgroup/", suffix
);
544 else if (isempty(suffix
))
545 t
= strappend("/sys/fs/cgroup/", path
);
547 t
= strjoin("/sys/fs/cgroup/", path
, "/", suffix
, NULL
);
555 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
563 /* If no controller is specified, we return the path
564 * *below* the controllers, without any prefix. */
566 if (!path
&& !suffix
)
574 t
= strjoin(path
, "/", suffix
, NULL
);
578 *fs
= path_kill_slashes(t
);
582 if (!cg_controller_is_valid(controller
))
585 unified
= cg_unified();
590 r
= join_path_unified(path
, suffix
, fs
);
592 r
= join_path_legacy(controller
, path
, suffix
, fs
);
596 path_kill_slashes(*fs
);
600 static int controller_is_accessible(const char *controller
) {
605 /* Checks whether a specific controller is accessible,
606 * i.e. its hierarchy mounted. In the unified hierarchy all
607 * controllers are considered accessible, except for the named
610 if (!cg_controller_is_valid(controller
))
613 unified
= cg_unified();
617 /* We don't support named hierarchies if we are using
618 * the unified hierarchy. */
620 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
623 if (startswith(controller
, "name="))
629 dn
= controller_to_dirname(controller
);
630 cc
= strjoina("/sys/fs/cgroup/", dn
);
632 if (laccess(cc
, F_OK
) < 0)
639 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
645 /* Check if the specified controller is actually accessible */
646 r
= controller_is_accessible(controller
);
650 return cg_get_path(controller
, path
, suffix
, fs
);
653 static int trim_cb(const char *path
, const struct stat
*sb
, int typeflag
, struct FTW
*ftwbuf
) {
658 if (typeflag
!= FTW_DP
)
661 if (ftwbuf
->level
< 1)
668 int cg_trim(const char *controller
, const char *path
, bool delete_root
) {
669 _cleanup_free_
char *fs
= NULL
;
674 r
= cg_get_path(controller
, path
, NULL
, &fs
);
679 if (nftw(fs
, trim_cb
, 64, FTW_DEPTH
|FTW_MOUNT
|FTW_PHYS
) != 0) {
689 if (rmdir(fs
) < 0 && errno
!= ENOENT
)
696 int cg_create(const char *controller
, const char *path
) {
697 _cleanup_free_
char *fs
= NULL
;
700 r
= cg_get_path_and_check(controller
, path
, NULL
, &fs
);
704 r
= mkdir_parents(fs
, 0755);
708 if (mkdir(fs
, 0755) < 0) {
719 int cg_create_and_attach(const char *controller
, const char *path
, pid_t pid
) {
724 r
= cg_create(controller
, path
);
728 q
= cg_attach(controller
, path
, pid
);
732 /* This does not remove the cgroup on failure */
736 int cg_attach(const char *controller
, const char *path
, pid_t pid
) {
737 _cleanup_free_
char *fs
= NULL
;
738 char c
[DECIMAL_STR_MAX(pid_t
) + 2];
744 r
= cg_get_path_and_check(controller
, path
, "cgroup.procs", &fs
);
751 xsprintf(c
, PID_FMT
"\n", pid
);
753 return write_string_file(fs
, c
, 0);
756 int cg_attach_fallback(const char *controller
, const char *path
, pid_t pid
) {
763 r
= cg_attach(controller
, path
, pid
);
765 char prefix
[strlen(path
) + 1];
767 /* This didn't work? Then let's try all prefixes of
770 PATH_FOREACH_PREFIX(prefix
, path
) {
773 q
= cg_attach(controller
, prefix
, pid
);
782 int cg_set_group_access(
783 const char *controller
,
789 _cleanup_free_
char *fs
= NULL
;
792 if (mode
== MODE_INVALID
&& uid
== UID_INVALID
&& gid
== GID_INVALID
)
795 if (mode
!= MODE_INVALID
)
798 r
= cg_get_path(controller
, path
, NULL
, &fs
);
802 return chmod_and_chown(fs
, mode
, uid
, gid
);
805 int cg_set_task_access(
806 const char *controller
,
812 _cleanup_free_
char *fs
= NULL
, *procs
= NULL
;
817 if (mode
== MODE_INVALID
&& uid
== UID_INVALID
&& gid
== GID_INVALID
)
820 if (mode
!= MODE_INVALID
)
823 r
= cg_get_path(controller
, path
, "cgroup.procs", &fs
);
827 r
= chmod_and_chown(fs
, mode
, uid
, gid
);
831 unified
= cg_unified();
837 /* Compatibility, Always keep values for "tasks" in sync with
839 if (cg_get_path(controller
, path
, "tasks", &procs
) >= 0)
840 (void) chmod_and_chown(procs
, mode
, uid
, gid
);
845 int cg_pid_get_path(const char *controller
, pid_t pid
, char **path
) {
846 _cleanup_fclose_
FILE *f
= NULL
;
855 unified
= cg_unified();
860 if (!cg_controller_is_valid(controller
))
863 controller
= SYSTEMD_CGROUP_CONTROLLER
;
865 cs
= strlen(controller
);
868 fs
= procfs_file_alloca(pid
, "cgroup");
871 return errno
== ENOENT
? -ESRCH
: -errno
;
873 FOREACH_LINE(line
, f
, return -errno
) {
879 e
= startswith(line
, "0:");
889 const char *word
, *state
;
892 l
= strchr(line
, ':');
902 FOREACH_WORD_SEPARATOR(word
, k
, l
, ",", state
) {
903 if (k
== cs
&& memcmp(word
, controller
, cs
) == 0) {
924 int cg_install_release_agent(const char *controller
, const char *agent
) {
925 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
931 unified
= cg_unified();
934 if (unified
) /* doesn't apply to unified hierarchy */
937 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
941 r
= read_one_line_file(fs
, &contents
);
945 sc
= strstrip(contents
);
947 r
= write_string_file(fs
, agent
, 0);
950 } else if (!path_equal(sc
, agent
))
954 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
958 contents
= mfree(contents
);
959 r
= read_one_line_file(fs
, &contents
);
963 sc
= strstrip(contents
);
964 if (streq(sc
, "0")) {
965 r
= write_string_file(fs
, "1", 0);
978 int cg_uninstall_release_agent(const char *controller
) {
979 _cleanup_free_
char *fs
= NULL
;
982 unified
= cg_unified();
985 if (unified
) /* Doesn't apply to unified hierarchy */
988 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
992 r
= write_string_file(fs
, "0", 0);
998 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
1002 r
= write_string_file(fs
, "", 0);
1009 int cg_is_empty(const char *controller
, const char *path
) {
1010 _cleanup_fclose_
FILE *f
= NULL
;
1016 r
= cg_enumerate_processes(controller
, path
, &f
);
1022 r
= cg_read_pid(f
, &pid
);
1029 int cg_is_empty_recursive(const char *controller
, const char *path
) {
1034 /* The root cgroup is always populated */
1035 if (controller
&& (isempty(path
) || path_equal(path
, "/")))
1038 unified
= cg_unified();
1043 _cleanup_free_
char *t
= NULL
;
1045 /* On the unified hierarchy we can check empty state
1046 * via the "populated" attribute of "cgroup.events". */
1048 r
= cg_read_event(controller
, path
, "populated", &t
);
1052 return streq(t
, "0");
1054 _cleanup_closedir_
DIR *d
= NULL
;
1057 r
= cg_is_empty(controller
, path
);
1061 r
= cg_enumerate_subgroups(controller
, path
, &d
);
1067 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1068 _cleanup_free_
char *p
= NULL
;
1070 p
= strjoin(path
, "/", fn
, NULL
);
1075 r
= cg_is_empty_recursive(controller
, p
);
1086 int cg_split_spec(const char *spec
, char **controller
, char **path
) {
1087 char *t
= NULL
, *u
= NULL
;
1093 if (!path_is_safe(spec
))
1101 *path
= path_kill_slashes(t
);
1110 e
= strchr(spec
, ':');
1112 if (!cg_controller_is_valid(spec
))
1129 t
= strndup(spec
, e
-spec
);
1132 if (!cg_controller_is_valid(t
)) {
1146 if (!path_is_safe(u
) ||
1147 !path_is_absolute(u
)) {
1153 path_kill_slashes(u
);
1169 int cg_mangle_path(const char *path
, char **result
) {
1170 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
1177 /* First, check if it already is a filesystem path */
1178 if (path_startswith(path
, "/sys/fs/cgroup")) {
1184 *result
= path_kill_slashes(t
);
1188 /* Otherwise, treat it as cg spec */
1189 r
= cg_split_spec(path
, &c
, &p
);
1193 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, result
);
1196 int cg_get_root_path(char **path
) {
1202 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
1206 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
1208 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
1210 e
= endswith(p
, "/system"); /* even more legacy */
1218 int cg_shift_path(const char *cgroup
, const char *root
, const char **shifted
) {
1219 _cleanup_free_
char *rt
= NULL
;
1227 /* If the root was specified let's use that, otherwise
1228 * let's determine it from PID 1 */
1230 r
= cg_get_root_path(&rt
);
1237 p
= path_startswith(cgroup
, root
);
1238 if (p
&& p
> cgroup
)
1246 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **cgroup
) {
1247 _cleanup_free_
char *raw
= NULL
;
1254 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1258 r
= cg_shift_path(raw
, root
, &c
);
1278 int cg_path_decode_unit(const char *cgroup
, char **unit
) {
1285 n
= strcspn(cgroup
, "/");
1289 c
= strndupa(cgroup
, n
);
1292 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1303 static bool valid_slice_name(const char *p
, size_t n
) {
1308 if (n
< strlen("x.slice"))
1311 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1317 c
= cg_unescape(buf
);
1319 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1325 static const char *skip_slices(const char *p
) {
1328 /* Skips over all slice assignments */
1333 p
+= strspn(p
, "/");
1335 n
= strcspn(p
, "/");
1336 if (!valid_slice_name(p
, n
))
1343 int cg_path_get_unit(const char *path
, char **ret
) {
1351 e
= skip_slices(path
);
1353 r
= cg_path_decode_unit(e
, &unit
);
1357 /* We skipped over the slices, don't accept any now */
1358 if (endswith(unit
, ".slice")) {
1367 int cg_pid_get_unit(pid_t pid
, char **unit
) {
1368 _cleanup_free_
char *cgroup
= NULL
;
1373 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1377 return cg_path_get_unit(cgroup
, unit
);
1381 * Skip session-*.scope, but require it to be there.
1383 static const char *skip_session(const char *p
) {
1389 p
+= strspn(p
, "/");
1391 n
= strcspn(p
, "/");
1392 if (n
< strlen("session-x.scope"))
1395 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1396 char buf
[n
- 8 - 6 + 1];
1398 memcpy(buf
, p
+ 8, n
- 8 - 6);
1401 /* Note that session scopes never need unescaping,
1402 * since they cannot conflict with the kernel's own
1403 * names, hence we don't need to call cg_unescape()
1406 if (!session_id_valid(buf
))
1410 p
+= strspn(p
, "/");
1418 * Skip user@*.service, but require it to be there.
1420 static const char *skip_user_manager(const char *p
) {
1426 p
+= strspn(p
, "/");
1428 n
= strcspn(p
, "/");
1429 if (n
< strlen("user@x.service"))
1432 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1433 char buf
[n
- 5 - 8 + 1];
1435 memcpy(buf
, p
+ 5, n
- 5 - 8);
1438 /* Note that user manager services never need unescaping,
1439 * since they cannot conflict with the kernel's own
1440 * names, hence we don't need to call cg_unescape()
1443 if (parse_uid(buf
, NULL
) < 0)
1447 p
+= strspn(p
, "/");
1455 static const char *skip_user_prefix(const char *path
) {
1460 /* Skip slices, if there are any */
1461 e
= skip_slices(path
);
1463 /* Skip the user manager, if it's in the path now... */
1464 t
= skip_user_manager(e
);
1468 /* Alternatively skip the user session if it is in the path... */
1469 return skip_session(e
);
1472 int cg_path_get_user_unit(const char *path
, char **ret
) {
1478 t
= skip_user_prefix(path
);
1482 /* And from here on it looks pretty much the same as for a
1483 * system unit, hence let's use the same parser from here
1485 return cg_path_get_unit(t
, ret
);
1488 int cg_pid_get_user_unit(pid_t pid
, char **unit
) {
1489 _cleanup_free_
char *cgroup
= NULL
;
1494 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1498 return cg_path_get_user_unit(cgroup
, unit
);
1501 int cg_path_get_machine_name(const char *path
, char **machine
) {
1502 _cleanup_free_
char *u
= NULL
;
1506 r
= cg_path_get_unit(path
, &u
);
1510 sl
= strjoina("/run/systemd/machines/unit:", u
);
1511 return readlink_malloc(sl
, machine
);
1514 int cg_pid_get_machine_name(pid_t pid
, char **machine
) {
1515 _cleanup_free_
char *cgroup
= NULL
;
1520 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1524 return cg_path_get_machine_name(cgroup
, machine
);
1527 int cg_path_get_session(const char *path
, char **session
) {
1528 _cleanup_free_
char *unit
= NULL
;
1534 r
= cg_path_get_unit(path
, &unit
);
1538 start
= startswith(unit
, "session-");
1541 end
= endswith(start
, ".scope");
1546 if (!session_id_valid(start
))
1562 int cg_pid_get_session(pid_t pid
, char **session
) {
1563 _cleanup_free_
char *cgroup
= NULL
;
1566 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1570 return cg_path_get_session(cgroup
, session
);
1573 int cg_path_get_owner_uid(const char *path
, uid_t
*uid
) {
1574 _cleanup_free_
char *slice
= NULL
;
1580 r
= cg_path_get_slice(path
, &slice
);
1584 start
= startswith(slice
, "user-");
1587 end
= endswith(start
, ".slice");
1592 if (parse_uid(start
, uid
) < 0)
1598 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*uid
) {
1599 _cleanup_free_
char *cgroup
= NULL
;
1602 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1606 return cg_path_get_owner_uid(cgroup
, uid
);
1609 int cg_path_get_slice(const char *p
, char **slice
) {
1610 const char *e
= NULL
;
1615 /* Finds the right-most slice unit from the beginning, but
1616 * stops before we come to the first non-slice unit. */
1621 p
+= strspn(p
, "/");
1623 n
= strcspn(p
, "/");
1624 if (!valid_slice_name(p
, n
)) {
1629 s
= strdup("-.slice");
1637 return cg_path_decode_unit(e
, slice
);
1645 int cg_pid_get_slice(pid_t pid
, char **slice
) {
1646 _cleanup_free_
char *cgroup
= NULL
;
1651 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1655 return cg_path_get_slice(cgroup
, slice
);
1658 int cg_path_get_user_slice(const char *p
, char **slice
) {
1663 t
= skip_user_prefix(p
);
1667 /* And now it looks pretty much the same as for a system
1668 * slice, so let's just use the same parser from here on. */
1669 return cg_path_get_slice(t
, slice
);
1672 int cg_pid_get_user_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_user_slice(cgroup
, slice
);
1685 char *cg_escape(const char *p
) {
1686 bool need_prefix
= false;
1688 /* This implements very minimal escaping for names to be used
1689 * as file names in the cgroup tree: any name which might
1690 * conflict with a kernel name or is prefixed with '_' is
1691 * prefixed with a '_'. That way, when reading cgroup names it
1692 * is sufficient to remove a single prefixing underscore if
1695 /* The return value of this function (unlike cg_unescape())
1701 streq(p
, "notify_on_release") ||
1702 streq(p
, "release_agent") ||
1703 streq(p
, "tasks") ||
1704 startswith(p
, "cgroup."))
1709 dot
= strrchr(p
, '.');
1714 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1717 n
= cgroup_controller_to_string(c
);
1722 if (memcmp(p
, n
, l
) != 0)
1732 return strappend("_", p
);
1737 char *cg_unescape(const char *p
) {
1740 /* The return value of this function (unlike cg_escape())
1741 * doesn't need free()! */
1749 #define CONTROLLER_VALID \
1753 bool cg_controller_is_valid(const char *p
) {
1759 s
= startswith(p
, "name=");
1763 if (*p
== 0 || *p
== '_')
1766 for (t
= p
; *t
; t
++)
1767 if (!strchr(CONTROLLER_VALID
, *t
))
1770 if (t
- p
> FILENAME_MAX
)
1776 int cg_slice_to_path(const char *unit
, char **ret
) {
1777 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1784 if (streq(unit
, "-.slice")) {
1794 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1797 if (!endswith(unit
, ".slice"))
1800 r
= unit_name_to_prefix(unit
, &p
);
1804 dash
= strchr(p
, '-');
1806 /* Don't allow initial dashes */
1811 _cleanup_free_
char *escaped
= NULL
;
1812 char n
[dash
- p
+ sizeof(".slice")];
1814 /* Don't allow trailing or double dashes */
1815 if (dash
[1] == 0 || dash
[1] == '-')
1818 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1819 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1822 escaped
= cg_escape(n
);
1826 if (!strextend(&s
, escaped
, "/", NULL
))
1829 dash
= strchr(dash
+1, '-');
1832 e
= cg_escape(unit
);
1836 if (!strextend(&s
, e
, NULL
))
1845 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
1846 _cleanup_free_
char *p
= NULL
;
1849 r
= cg_get_path(controller
, path
, attribute
, &p
);
1853 return write_string_file(p
, value
, 0);
1856 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
1857 _cleanup_free_
char *p
= NULL
;
1860 r
= cg_get_path(controller
, path
, attribute
, &p
);
1864 return read_one_line_file(p
, ret
);
1867 int cg_create_everywhere(CGroupMask supported
, CGroupMask mask
, const char *path
) {
1871 /* This one will create a cgroup in our private tree, but also
1872 * duplicate it in the trees specified in mask, and remove it
1875 /* First create the cgroup in our own hierarchy. */
1876 r
= cg_create(SYSTEMD_CGROUP_CONTROLLER
, path
);
1880 /* If we are in the unified hierarchy, we are done now */
1881 unified
= cg_unified();
1887 /* Otherwise, do the same in the other hierarchies */
1888 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1889 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1892 n
= cgroup_controller_to_string(c
);
1895 (void) cg_create(n
, path
);
1896 else if (supported
& bit
)
1897 (void) cg_trim(n
, path
, true);
1903 int cg_attach_everywhere(CGroupMask supported
, const char *path
, pid_t pid
, cg_migrate_callback_t path_callback
, void *userdata
) {
1907 r
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, path
, pid
);
1911 unified
= cg_unified();
1917 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1918 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1919 const char *p
= NULL
;
1921 if (!(supported
& bit
))
1925 p
= path_callback(bit
, userdata
);
1930 (void) cg_attach_fallback(cgroup_controller_to_string(c
), p
, pid
);
1936 int cg_attach_many_everywhere(CGroupMask supported
, const char *path
, Set
* pids
, cg_migrate_callback_t path_callback
, void *userdata
) {
1941 SET_FOREACH(pidp
, pids
, i
) {
1942 pid_t pid
= PTR_TO_PID(pidp
);
1945 q
= cg_attach_everywhere(supported
, path
, pid
, path_callback
, userdata
);
1946 if (q
< 0 && r
>= 0)
1953 int cg_migrate_everywhere(CGroupMask supported
, const char *from
, const char *to
, cg_migrate_callback_t to_callback
, void *userdata
) {
1957 if (!path_equal(from
, to
)) {
1958 r
= cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER
, from
, SYSTEMD_CGROUP_CONTROLLER
, to
, false, true);
1963 unified
= cg_unified();
1969 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1970 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1971 const char *p
= NULL
;
1973 if (!(supported
& bit
))
1977 p
= to_callback(bit
, userdata
);
1982 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER
, to
, cgroup_controller_to_string(c
), p
, false, false);
1988 int cg_trim_everywhere(CGroupMask supported
, const char *path
, bool delete_root
) {
1992 r
= cg_trim(SYSTEMD_CGROUP_CONTROLLER
, path
, delete_root
);
1996 unified
= cg_unified();
2002 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2003 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2005 if (!(supported
& bit
))
2008 (void) cg_trim(cgroup_controller_to_string(c
), path
, delete_root
);
2014 int cg_mask_supported(CGroupMask
*ret
) {
2015 CGroupMask mask
= 0;
2018 /* Determines the mask of supported cgroup controllers. Only
2019 * includes controllers we can make sense of and that are
2020 * actually accessible. */
2022 unified
= cg_unified();
2026 _cleanup_free_
char *root
= NULL
, *controllers
= NULL
, *path
= NULL
;
2029 /* In the unified hierarchy we can read the supported
2030 * and accessible controllers from a the top-level
2031 * cgroup attribute */
2033 r
= cg_get_root_path(&root
);
2037 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
2041 r
= read_one_line_file(path
, &controllers
);
2047 _cleanup_free_
char *n
= NULL
;
2050 r
= extract_first_word(&c
, &n
, NULL
, 0);
2056 v
= cgroup_controller_from_string(n
);
2060 mask
|= CGROUP_CONTROLLER_TO_MASK(v
);
2063 /* Currently, we only support the memory, io and pids
2064 * controller in the unified hierarchy, mask
2065 * everything else off. */
2066 mask
&= CGROUP_MASK_MEMORY
| CGROUP_MASK_IO
| CGROUP_MASK_PIDS
;
2071 /* In the legacy hierarchy, we check whether which
2072 * hierarchies are mounted. */
2074 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2077 n
= cgroup_controller_to_string(c
);
2078 if (controller_is_accessible(n
) >= 0)
2079 mask
|= CGROUP_CONTROLLER_TO_MASK(c
);
2087 int cg_kernel_controllers(Set
*controllers
) {
2088 _cleanup_fclose_
FILE *f
= NULL
;
2092 assert(controllers
);
2094 /* Determines the full list of kernel-known controllers. Might
2095 * include controllers we don't actually support, arbitrary
2096 * named hierarchies and controllers that aren't currently
2097 * accessible (because not mounted). */
2099 f
= fopen("/proc/cgroups", "re");
2101 if (errno
== ENOENT
)
2106 /* Ignore the header line */
2107 (void) fgets(buf
, sizeof(buf
), f
);
2114 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
2119 if (ferror(f
) && errno
> 0)
2130 if (!cg_controller_is_valid(controller
)) {
2135 r
= set_consume(controllers
, controller
);
2143 static thread_local
int unified_cache
= -1;
2145 int cg_unified(void) {
2148 /* Checks if we support the unified hierarchy. Returns an
2149 * error when the cgroup hierarchies aren't mounted yet or we
2150 * have any other trouble determining if the unified hierarchy
2153 if (unified_cache
>= 0)
2154 return unified_cache
;
2156 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
2159 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
))
2160 unified_cache
= true;
2161 else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
))
2162 unified_cache
= false;
2166 return unified_cache
;
2169 void cg_unified_flush(void) {
2173 int cg_enable_everywhere(CGroupMask supported
, CGroupMask mask
, const char *p
) {
2174 _cleanup_free_
char *fs
= NULL
;
2183 unified
= cg_unified();
2186 if (!unified
) /* on the legacy hiearchy there's no joining of controllers defined */
2189 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, p
, "cgroup.subtree_control", &fs
);
2193 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2194 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2197 if (!(supported
& bit
))
2200 n
= cgroup_controller_to_string(c
);
2202 char s
[1 + strlen(n
) + 1];
2204 s
[0] = mask
& bit
? '+' : '-';
2207 r
= write_string_file(fs
, s
, 0);
2209 log_debug_errno(r
, "Failed to enable controller %s for %s (%s): %m", n
, p
, fs
);
2216 bool cg_is_unified_wanted(void) {
2217 static thread_local
int wanted
= -1;
2220 /* If the hierarchy is already mounted, then follow whatever
2221 * was chosen for it. */
2222 unified
= cg_unified();
2226 /* Otherwise, let's see what the kernel command line has to
2227 * say. Since checking that is expensive, let's cache the
2232 r
= get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL
);
2234 return (wanted
= true);
2236 _cleanup_free_
char *value
= NULL
;
2238 r
= get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value
);
2242 return (wanted
= false);
2244 return (wanted
= parse_boolean(value
) > 0);
2248 bool cg_is_legacy_wanted(void) {
2249 return !cg_is_unified_wanted();
2252 int cg_weight_parse(const char *s
, uint64_t *ret
) {
2257 *ret
= CGROUP_WEIGHT_INVALID
;
2261 r
= safe_atou64(s
, &u
);
2265 if (u
< CGROUP_WEIGHT_MIN
|| u
> CGROUP_WEIGHT_MAX
)
2272 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2273 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2274 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2275 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2276 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2279 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2280 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2281 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2282 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2283 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2286 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2288 int cg_cpu_shares_parse(const char *s
, uint64_t *ret
) {
2293 *ret
= CGROUP_CPU_SHARES_INVALID
;
2297 r
= safe_atou64(s
, &u
);
2301 if (u
< CGROUP_CPU_SHARES_MIN
|| u
> CGROUP_CPU_SHARES_MAX
)
2308 int cg_blkio_weight_parse(const char *s
, uint64_t *ret
) {
2313 *ret
= CGROUP_BLKIO_WEIGHT_INVALID
;
2317 r
= safe_atou64(s
, &u
);
2321 if (u
< CGROUP_BLKIO_WEIGHT_MIN
|| u
> CGROUP_BLKIO_WEIGHT_MAX
)
2328 static const char *cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2329 [CGROUP_CONTROLLER_CPU
] = "cpu",
2330 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2331 [CGROUP_CONTROLLER_IO
] = "io",
2332 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2333 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2334 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2335 [CGROUP_CONTROLLER_PIDS
] = "pids",
2338 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);