1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include <sys/utsname.h>
11 #include <sys/xattr.h>
14 #include "alloc-util.h"
15 #include "cgroup-util.h"
17 #include "dirent-util.h"
18 #include "extract-word.h"
21 #include "format-util.h"
24 #include "login-util.h"
26 #include "missing_magic.h"
28 #include "parse-util.h"
29 #include "path-util.h"
30 #include "process-util.h"
33 #include "stat-util.h"
34 #include "stdio-util.h"
35 #include "string-table.h"
36 #include "string-util.h"
38 #include "unit-name.h"
39 #include "user-util.h"
40 #include "xattr-util.h"
42 static int cg_enumerate_items(const char *controller
, const char *path
, FILE **_f
, const char *item
) {
43 _cleanup_free_
char *fs
= NULL
;
49 r
= cg_get_path(controller
, path
, item
, &fs
);
61 int cg_enumerate_processes(const char *controller
, const char *path
, FILE **_f
) {
62 return cg_enumerate_items(controller
, path
, _f
, "cgroup.procs");
65 int cg_read_pid(FILE *f
, pid_t
*_pid
) {
68 /* Note that the cgroup.procs might contain duplicates! See
69 * cgroups.txt for details. */
75 if (fscanf(f
, "%lu", &ul
) != 1) {
80 return errno_or_else(EIO
);
91 const char *controller
,
96 _cleanup_free_
char *events
= NULL
, *content
= NULL
;
99 r
= cg_get_path(controller
, path
, "cgroup.events", &events
);
103 r
= read_full_file(events
, &content
, NULL
);
107 for (const char *p
= content
;;) {
108 _cleanup_free_
char *line
= NULL
, *key
= NULL
, *val
= NULL
;
111 r
= extract_first_word(&p
, &line
, "\n", 0);
118 r
= extract_first_word(&q
, &key
, " ", 0);
124 if (!streq(key
, event
))
131 *ret
= TAKE_PTR(val
);
136 bool cg_ns_supported(void) {
137 static thread_local
int enabled
= -1;
142 if (access("/proc/self/ns/cgroup", F_OK
) < 0) {
144 log_debug_errno(errno
, "Failed to check whether /proc/self/ns/cgroup is available, assuming not: %m");
152 bool cg_freezer_supported(void) {
153 static thread_local
int supported
= -1;
158 supported
= cg_all_unified() > 0 && access("/sys/fs/cgroup/init.scope/cgroup.freeze", F_OK
) == 0;
163 int cg_enumerate_subgroups(const char *controller
, const char *path
, DIR **_d
) {
164 _cleanup_free_
char *fs
= NULL
;
170 /* This is not recursive! */
172 r
= cg_get_path(controller
, path
, NULL
, &fs
);
184 int cg_read_subgroup(DIR *d
, char **fn
) {
190 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
193 if (de
->d_type
!= DT_DIR
)
196 if (dot_or_dot_dot(de
->d_name
))
199 b
= strdup(de
->d_name
);
210 int cg_rmdir(const char *controller
, const char *path
) {
211 _cleanup_free_
char *p
= NULL
;
214 r
= cg_get_path(controller
, path
, NULL
, &p
);
219 if (r
< 0 && errno
!= ENOENT
)
222 r
= cg_hybrid_unified();
226 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
227 r
= cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
);
229 log_warning_errno(r
, "Failed to remove compat systemd cgroup %s: %m", path
);
235 static int cg_kill_items(
236 const char *controller
,
241 cg_kill_log_func_t log_kill
,
245 _cleanup_set_free_ Set
*allocated_set
= NULL
;
247 int r
, ret
= 0, ret_log_kill
= 0;
252 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
253 * SIGCONT on SIGKILL. */
254 if (IN_SET(sig
, SIGCONT
, SIGKILL
))
255 flags
&= ~CGROUP_SIGCONT
;
257 /* This goes through the tasks list and kills them all. This
258 * is repeated until no further processes are added to the
259 * tasks list, to properly handle forking processes */
262 s
= allocated_set
= set_new(NULL
);
267 my_pid
= getpid_cached();
270 _cleanup_fclose_
FILE *f
= NULL
;
274 r
= cg_enumerate_items(controller
, path
, &f
, item
);
276 if (ret
>= 0 && r
!= -ENOENT
)
282 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
284 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
287 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
291 ret_log_kill
= log_kill(pid
, sig
, userdata
);
293 /* If we haven't killed this process yet, kill
295 if (kill(pid
, sig
) < 0) {
296 if (ret
>= 0 && errno
!= ESRCH
)
299 if (flags
& CGROUP_SIGCONT
)
300 (void) kill(pid
, SIGCONT
);
312 r
= set_put(s
, PID_TO_PTR(pid
));
328 /* To avoid racing against processes which fork
329 * quicker than we can kill them we repeat this until
330 * no new pids need to be killed. */
338 const char *controller
,
343 cg_kill_log_func_t log_kill
,
347 r
= cg_kill_items(controller
, path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.procs");
348 if (r
< 0 || sig
!= SIGKILL
)
351 /* Only in case of killing with SIGKILL and when using cgroupsv2, kill remaining threads manually as
352 a workaround for kernel bug. It was fixed in 5.2-rc5 (c03cd7738a83), backported to 4.19.66
353 (4340d175b898) and 4.14.138 (feb6b123b7dd). */
354 r
= cg_unified_controller(controller
);
358 return cg_kill_items(controller
, path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.threads");
361 int cg_kill_recursive(
362 const char *controller
,
367 cg_kill_log_func_t log_kill
,
370 _cleanup_set_free_ Set
*allocated_set
= NULL
;
371 _cleanup_closedir_
DIR *d
= NULL
;
379 s
= allocated_set
= set_new(NULL
);
384 ret
= cg_kill(controller
, path
, sig
, flags
, s
, log_kill
, userdata
);
386 r
= cg_enumerate_subgroups(controller
, path
, &d
);
388 if (ret
>= 0 && r
!= -ENOENT
)
394 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
395 _cleanup_free_
char *p
= NULL
;
397 p
= path_join(empty_to_root(path
), fn
);
402 r
= cg_kill_recursive(controller
, p
, sig
, flags
, s
, log_kill
, userdata
);
403 if (r
!= 0 && ret
>= 0)
406 if (ret
>= 0 && r
< 0)
409 if (flags
& CGROUP_REMOVE
) {
410 r
= cg_rmdir(controller
, path
);
411 if (r
< 0 && ret
>= 0 && !IN_SET(r
, -ENOENT
, -EBUSY
))
418 static const char *controller_to_dirname(const char *controller
) {
423 /* Converts a controller name to the directory name below
424 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
425 * just cuts off the name= prefixed used for named
426 * hierarchies, if it is specified. */
428 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
429 if (cg_hybrid_unified() > 0)
430 controller
= SYSTEMD_CGROUP_CONTROLLER_HYBRID
;
432 controller
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
435 e
= startswith(controller
, "name=");
442 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
449 dn
= controller_to_dirname(controller
);
451 if (isempty(path
) && isempty(suffix
))
452 t
= path_join("/sys/fs/cgroup", dn
);
453 else if (isempty(path
))
454 t
= path_join("/sys/fs/cgroup", dn
, suffix
);
455 else if (isempty(suffix
))
456 t
= path_join("/sys/fs/cgroup", dn
, path
);
458 t
= path_join("/sys/fs/cgroup", dn
, path
, suffix
);
466 static int join_path_unified(const char *path
, const char *suffix
, char **fs
) {
471 if (isempty(path
) && isempty(suffix
))
472 t
= strdup("/sys/fs/cgroup");
473 else if (isempty(path
))
474 t
= path_join("/sys/fs/cgroup", suffix
);
475 else if (isempty(suffix
))
476 t
= path_join("/sys/fs/cgroup", path
);
478 t
= path_join("/sys/fs/cgroup", path
, suffix
);
486 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
494 /* If no controller is specified, we return the path
495 * *below* the controllers, without any prefix. */
497 if (!path
&& !suffix
)
505 t
= path_join(path
, suffix
);
509 *fs
= path_simplify(t
, false);
513 if (!cg_controller_is_valid(controller
))
516 r
= cg_all_unified();
520 r
= join_path_unified(path
, suffix
, fs
);
522 r
= join_path_legacy(controller
, path
, suffix
, fs
);
526 path_simplify(*fs
, false);
530 static int controller_is_accessible(const char *controller
) {
535 /* Checks whether a specific controller is accessible,
536 * i.e. its hierarchy mounted. In the unified hierarchy all
537 * controllers are considered accessible, except for the named
540 if (!cg_controller_is_valid(controller
))
543 r
= cg_all_unified();
547 /* We don't support named hierarchies if we are using
548 * the unified hierarchy. */
550 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
553 if (startswith(controller
, "name="))
559 dn
= controller_to_dirname(controller
);
560 cc
= strjoina("/sys/fs/cgroup/", dn
);
562 if (laccess(cc
, F_OK
) < 0)
569 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
575 /* Check if the specified controller is actually accessible */
576 r
= controller_is_accessible(controller
);
580 return cg_get_path(controller
, path
, suffix
, fs
);
583 int cg_set_xattr(const char *controller
, const char *path
, const char *name
, const void *value
, size_t size
, int flags
) {
584 _cleanup_free_
char *fs
= NULL
;
589 assert(value
|| size
<= 0);
591 r
= cg_get_path(controller
, path
, NULL
, &fs
);
595 if (setxattr(fs
, name
, value
, size
, flags
) < 0)
601 int cg_get_xattr(const char *controller
, const char *path
, const char *name
, void *value
, size_t size
) {
602 _cleanup_free_
char *fs
= NULL
;
609 r
= cg_get_path(controller
, path
, NULL
, &fs
);
613 n
= getxattr(fs
, name
, value
, size
);
620 int cg_get_xattr_malloc(const char *controller
, const char *path
, const char *name
, char **ret
) {
621 _cleanup_free_
char *fs
= NULL
;
627 r
= cg_get_path(controller
, path
, NULL
, &fs
);
631 r
= getxattr_malloc(fs
, name
, ret
, false);
638 int cg_get_xattr_bool(const char *controller
, const char *path
, const char *name
) {
639 _cleanup_free_
char *val
= NULL
;
645 r
= cg_get_xattr_malloc(controller
, path
, name
, &val
);
649 return parse_boolean(val
);
652 int cg_remove_xattr(const char *controller
, const char *path
, const char *name
) {
653 _cleanup_free_
char *fs
= NULL
;
659 r
= cg_get_path(controller
, path
, NULL
, &fs
);
663 if (removexattr(fs
, name
) < 0)
669 int cg_pid_get_path(const char *controller
, pid_t pid
, char **ret_path
) {
670 _cleanup_fclose_
FILE *f
= NULL
;
671 const char *fs
, *controller_str
;
678 if (!cg_controller_is_valid(controller
))
681 controller
= SYSTEMD_CGROUP_CONTROLLER
;
683 unified
= cg_unified_controller(controller
);
687 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
688 controller_str
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
690 controller_str
= controller
;
693 fs
= procfs_file_alloca(pid
, "cgroup");
694 r
= fopen_unlocked(fs
, "re", &f
);
701 _cleanup_free_
char *line
= NULL
;
704 r
= read_line(f
, LONG_LINE_MAX
, &line
);
711 e
= startswith(line
, "0:");
721 l
= strchr(line
, ':');
731 r
= string_contains_word(l
, ",", controller_str
);
738 char *path
= strdup(e
+ 1);
742 /* Truncate suffix indicating the process is a zombie */
743 e
= endswith(path
, " (deleted)");
752 int cg_install_release_agent(const char *controller
, const char *agent
) {
753 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
759 r
= cg_unified_controller(controller
);
762 if (r
> 0) /* doesn't apply to unified hierarchy */
765 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
769 r
= read_one_line_file(fs
, &contents
);
773 sc
= strstrip(contents
);
775 r
= write_string_file(fs
, agent
, WRITE_STRING_FILE_DISABLE_BUFFER
);
778 } else if (!path_equal(sc
, agent
))
782 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
786 contents
= mfree(contents
);
787 r
= read_one_line_file(fs
, &contents
);
791 sc
= strstrip(contents
);
792 if (streq(sc
, "0")) {
793 r
= write_string_file(fs
, "1", WRITE_STRING_FILE_DISABLE_BUFFER
);
806 int cg_uninstall_release_agent(const char *controller
) {
807 _cleanup_free_
char *fs
= NULL
;
810 r
= cg_unified_controller(controller
);
813 if (r
> 0) /* Doesn't apply to unified hierarchy */
816 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
820 r
= write_string_file(fs
, "0", WRITE_STRING_FILE_DISABLE_BUFFER
);
826 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
830 r
= write_string_file(fs
, "", WRITE_STRING_FILE_DISABLE_BUFFER
);
837 int cg_is_empty(const char *controller
, const char *path
) {
838 _cleanup_fclose_
FILE *f
= NULL
;
844 r
= cg_enumerate_processes(controller
, path
, &f
);
850 r
= cg_read_pid(f
, &pid
);
857 int cg_is_empty_recursive(const char *controller
, const char *path
) {
862 /* The root cgroup is always populated */
863 if (controller
&& empty_or_root(path
))
866 r
= cg_unified_controller(controller
);
870 _cleanup_free_
char *t
= NULL
;
872 /* On the unified hierarchy we can check empty state
873 * via the "populated" attribute of "cgroup.events". */
875 r
= cg_read_event(controller
, path
, "populated", &t
);
881 return streq(t
, "0");
883 _cleanup_closedir_
DIR *d
= NULL
;
886 r
= cg_is_empty(controller
, path
);
890 r
= cg_enumerate_subgroups(controller
, path
, &d
);
896 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
897 _cleanup_free_
char *p
= NULL
;
899 p
= path_join(path
, fn
);
904 r
= cg_is_empty_recursive(controller
, p
);
915 int cg_split_spec(const char *spec
, char **ret_controller
, char **ret_path
) {
916 _cleanup_free_
char *controller
= NULL
, *path
= NULL
;
921 if (!path_is_normalized(spec
))
929 path_simplify(path
, false);
935 e
= strchr(spec
, ':');
937 controller
= strndup(spec
, e
-spec
);
940 if (!cg_controller_is_valid(controller
))
943 if (!isempty(e
+ 1)) {
948 if (!path_is_normalized(path
) ||
949 !path_is_absolute(path
))
952 path_simplify(path
, false);
956 if (!cg_controller_is_valid(spec
))
959 if (ret_controller
) {
960 controller
= strdup(spec
);
968 *ret_controller
= TAKE_PTR(controller
);
970 *ret_path
= TAKE_PTR(path
);
974 int cg_mangle_path(const char *path
, char **result
) {
975 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
982 /* First, check if it already is a filesystem path */
983 if (path_startswith(path
, "/sys/fs/cgroup")) {
989 *result
= path_simplify(t
, false);
993 /* Otherwise, treat it as cg spec */
994 r
= cg_split_spec(path
, &c
, &p
);
998 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, result
);
1001 int cg_get_root_path(char **path
) {
1007 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
1011 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
1013 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
1015 e
= endswith(p
, "/system"); /* even more legacy */
1023 int cg_shift_path(const char *cgroup
, const char *root
, const char **shifted
) {
1024 _cleanup_free_
char *rt
= NULL
;
1032 /* If the root was specified let's use that, otherwise
1033 * let's determine it from PID 1 */
1035 r
= cg_get_root_path(&rt
);
1042 p
= path_startswith(cgroup
, root
);
1043 if (p
&& p
> cgroup
)
1051 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **cgroup
) {
1052 _cleanup_free_
char *raw
= NULL
;
1059 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1063 r
= cg_shift_path(raw
, root
, &c
);
1068 *cgroup
= TAKE_PTR(raw
);
1082 int cg_path_decode_unit(const char *cgroup
, char **unit
) {
1089 n
= strcspn(cgroup
, "/");
1093 c
= strndupa(cgroup
, n
);
1096 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1107 static bool valid_slice_name(const char *p
, size_t n
) {
1112 if (n
< STRLEN("x.slice"))
1115 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1121 c
= cg_unescape(buf
);
1123 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1129 static const char *skip_slices(const char *p
) {
1132 /* Skips over all slice assignments */
1137 p
+= strspn(p
, "/");
1139 n
= strcspn(p
, "/");
1140 if (!valid_slice_name(p
, n
))
1147 int cg_path_get_unit(const char *path
, char **ret
) {
1148 _cleanup_free_
char *unit
= NULL
;
1155 e
= skip_slices(path
);
1157 r
= cg_path_decode_unit(e
, &unit
);
1161 /* We skipped over the slices, don't accept any now */
1162 if (endswith(unit
, ".slice"))
1165 *ret
= TAKE_PTR(unit
);
1169 int cg_pid_get_unit(pid_t pid
, char **unit
) {
1170 _cleanup_free_
char *cgroup
= NULL
;
1175 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1179 return cg_path_get_unit(cgroup
, unit
);
1183 * Skip session-*.scope, but require it to be there.
1185 static const char *skip_session(const char *p
) {
1191 p
+= strspn(p
, "/");
1193 n
= strcspn(p
, "/");
1194 if (n
< STRLEN("session-x.scope"))
1197 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1198 char buf
[n
- 8 - 6 + 1];
1200 memcpy(buf
, p
+ 8, n
- 8 - 6);
1203 /* Note that session scopes never need unescaping,
1204 * since they cannot conflict with the kernel's own
1205 * names, hence we don't need to call cg_unescape()
1208 if (!session_id_valid(buf
))
1212 p
+= strspn(p
, "/");
1220 * Skip user@*.service, but require it to be there.
1222 static const char *skip_user_manager(const char *p
) {
1228 p
+= strspn(p
, "/");
1230 n
= strcspn(p
, "/");
1231 if (n
< STRLEN("user@x.service"))
1234 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1235 char buf
[n
- 5 - 8 + 1];
1237 memcpy(buf
, p
+ 5, n
- 5 - 8);
1240 /* Note that user manager services never need unescaping,
1241 * since they cannot conflict with the kernel's own
1242 * names, hence we don't need to call cg_unescape()
1245 if (parse_uid(buf
, NULL
) < 0)
1249 p
+= strspn(p
, "/");
1257 static const char *skip_user_prefix(const char *path
) {
1262 /* Skip slices, if there are any */
1263 e
= skip_slices(path
);
1265 /* Skip the user manager, if it's in the path now... */
1266 t
= skip_user_manager(e
);
1270 /* Alternatively skip the user session if it is in the path... */
1271 return skip_session(e
);
1274 int cg_path_get_user_unit(const char *path
, char **ret
) {
1280 t
= skip_user_prefix(path
);
1284 /* And from here on it looks pretty much the same as for a system unit, hence let's use the same
1286 return cg_path_get_unit(t
, ret
);
1289 int cg_pid_get_user_unit(pid_t pid
, char **unit
) {
1290 _cleanup_free_
char *cgroup
= NULL
;
1295 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1299 return cg_path_get_user_unit(cgroup
, unit
);
1302 int cg_path_get_machine_name(const char *path
, char **machine
) {
1303 _cleanup_free_
char *u
= NULL
;
1307 r
= cg_path_get_unit(path
, &u
);
1311 sl
= strjoina("/run/systemd/machines/unit:", u
);
1312 return readlink_malloc(sl
, machine
);
1315 int cg_pid_get_machine_name(pid_t pid
, char **machine
) {
1316 _cleanup_free_
char *cgroup
= NULL
;
1321 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1325 return cg_path_get_machine_name(cgroup
, machine
);
1328 int cg_path_get_session(const char *path
, char **session
) {
1329 _cleanup_free_
char *unit
= NULL
;
1335 r
= cg_path_get_unit(path
, &unit
);
1339 start
= startswith(unit
, "session-");
1342 end
= endswith(start
, ".scope");
1347 if (!session_id_valid(start
))
1363 int cg_pid_get_session(pid_t pid
, char **session
) {
1364 _cleanup_free_
char *cgroup
= NULL
;
1367 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1371 return cg_path_get_session(cgroup
, session
);
1374 int cg_path_get_owner_uid(const char *path
, uid_t
*uid
) {
1375 _cleanup_free_
char *slice
= NULL
;
1381 r
= cg_path_get_slice(path
, &slice
);
1385 start
= startswith(slice
, "user-");
1388 end
= endswith(start
, ".slice");
1393 if (parse_uid(start
, uid
) < 0)
1399 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*uid
) {
1400 _cleanup_free_
char *cgroup
= NULL
;
1403 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1407 return cg_path_get_owner_uid(cgroup
, uid
);
1410 int cg_path_get_slice(const char *p
, char **slice
) {
1411 const char *e
= NULL
;
1416 /* Finds the right-most slice unit from the beginning, but
1417 * stops before we come to the first non-slice unit. */
1422 p
+= strspn(p
, "/");
1424 n
= strcspn(p
, "/");
1425 if (!valid_slice_name(p
, n
)) {
1430 s
= strdup(SPECIAL_ROOT_SLICE
);
1438 return cg_path_decode_unit(e
, slice
);
1446 int cg_pid_get_slice(pid_t pid
, char **slice
) {
1447 _cleanup_free_
char *cgroup
= NULL
;
1452 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1456 return cg_path_get_slice(cgroup
, slice
);
1459 int cg_path_get_user_slice(const char *p
, char **slice
) {
1464 t
= skip_user_prefix(p
);
1468 /* And now it looks pretty much the same as for a system
1469 * slice, so let's just use the same parser from here on. */
1470 return cg_path_get_slice(t
, slice
);
1473 int cg_pid_get_user_slice(pid_t pid
, char **slice
) {
1474 _cleanup_free_
char *cgroup
= NULL
;
1479 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1483 return cg_path_get_user_slice(cgroup
, slice
);
1486 char *cg_escape(const char *p
) {
1487 bool need_prefix
= false;
1489 /* This implements very minimal escaping for names to be used
1490 * as file names in the cgroup tree: any name which might
1491 * conflict with a kernel name or is prefixed with '_' is
1492 * prefixed with a '_'. That way, when reading cgroup names it
1493 * is sufficient to remove a single prefixing underscore if
1496 /* The return value of this function (unlike cg_unescape())
1499 if (IN_SET(p
[0], 0, '_', '.') ||
1500 STR_IN_SET(p
, "notify_on_release", "release_agent", "tasks") ||
1501 startswith(p
, "cgroup."))
1506 dot
= strrchr(p
, '.');
1511 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1514 n
= cgroup_controller_to_string(c
);
1519 if (memcmp(p
, n
, l
) != 0)
1529 return strjoin("_", p
);
1534 char *cg_unescape(const char *p
) {
1537 /* The return value of this function (unlike cg_escape())
1538 * doesn't need free()! */
1546 #define CONTROLLER_VALID \
1550 bool cg_controller_is_valid(const char *p
) {
1556 if (streq(p
, SYSTEMD_CGROUP_CONTROLLER
))
1559 s
= startswith(p
, "name=");
1563 if (IN_SET(*p
, 0, '_'))
1566 for (t
= p
; *t
; t
++)
1567 if (!strchr(CONTROLLER_VALID
, *t
))
1570 if (t
- p
> FILENAME_MAX
)
1576 int cg_slice_to_path(const char *unit
, char **ret
) {
1577 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1584 if (streq(unit
, SPECIAL_ROOT_SLICE
)) {
1594 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1597 if (!endswith(unit
, ".slice"))
1600 r
= unit_name_to_prefix(unit
, &p
);
1604 dash
= strchr(p
, '-');
1606 /* Don't allow initial dashes */
1611 _cleanup_free_
char *escaped
= NULL
;
1612 char n
[dash
- p
+ sizeof(".slice")];
1614 #if HAS_FEATURE_MEMORY_SANITIZER
1615 /* msan doesn't instrument stpncpy, so it thinks
1616 * n is later used uninitialized:
1617 * https://github.com/google/sanitizers/issues/926
1622 /* Don't allow trailing or double dashes */
1623 if (IN_SET(dash
[1], 0, '-'))
1626 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1627 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1630 escaped
= cg_escape(n
);
1634 if (!strextend(&s
, escaped
, "/"))
1637 dash
= strchr(dash
+1, '-');
1640 e
= cg_escape(unit
);
1644 if (!strextend(&s
, e
))
1652 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
1653 _cleanup_free_
char *p
= NULL
;
1656 r
= cg_get_path(controller
, path
, attribute
, &p
);
1660 return write_string_file(p
, value
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1663 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
1664 _cleanup_free_
char *p
= NULL
;
1667 r
= cg_get_path(controller
, path
, attribute
, &p
);
1671 return read_one_line_file(p
, ret
);
1674 int cg_get_attribute_as_uint64(const char *controller
, const char *path
, const char *attribute
, uint64_t *ret
) {
1675 _cleanup_free_
char *value
= NULL
;
1681 r
= cg_get_attribute(controller
, path
, attribute
, &value
);
1687 if (streq(value
, "max")) {
1688 *ret
= CGROUP_LIMIT_MAX
;
1692 r
= safe_atou64(value
, &v
);
1700 int cg_get_attribute_as_bool(const char *controller
, const char *path
, const char *attribute
, bool *ret
) {
1701 _cleanup_free_
char *value
= NULL
;
1706 r
= cg_get_attribute(controller
, path
, attribute
, &value
);
1712 r
= parse_boolean(value
);
1720 int cg_get_owner(const char *controller
, const char *path
, uid_t
*ret_uid
) {
1721 _cleanup_free_
char *f
= NULL
;
1727 r
= cg_get_path(controller
, path
, NULL
, &f
);
1731 r
= stat(f
, &stats
);
1735 *ret_uid
= stats
.st_uid
;
1739 int cg_get_keyed_attribute_full(
1740 const char *controller
,
1742 const char *attribute
,
1745 CGroupKeyMode mode
) {
1747 _cleanup_free_
char *filename
= NULL
, *contents
= NULL
;
1749 size_t n
, i
, n_done
= 0;
1753 /* Reads one or more fields of a cgroup v2 keyed attribute file. The 'keys' parameter should be an strv with
1754 * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
1755 * entries as 'keys'. On success each entry will be set to the value of the matching key.
1757 * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. If mode
1758 * is set to GG_KEY_MODE_GRACEFUL we ignore missing keys and return those that were parsed successfully. */
1760 r
= cg_get_path(controller
, path
, attribute
, &filename
);
1764 r
= read_full_file(filename
, &contents
, NULL
);
1768 n
= strv_length(keys
);
1769 if (n
== 0) /* No keys to retrieve? That's easy, we are done then */
1772 /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
1773 v
= newa0(char*, n
);
1775 for (p
= contents
; *p
;) {
1776 const char *w
= NULL
;
1778 for (i
= 0; i
< n
; i
++)
1780 w
= first_word(p
, keys
[i
]);
1788 l
= strcspn(w
, NEWLINE
);
1789 v
[i
] = strndup(w
, l
);
1801 p
+= strcspn(p
, NEWLINE
);
1803 p
+= strspn(p
, NEWLINE
);
1806 if (mode
& CG_KEY_MODE_GRACEFUL
)
1812 for (i
= 0; i
< n
; i
++)
1818 memcpy(ret_values
, v
, sizeof(char*) * n
);
1819 if (mode
& CG_KEY_MODE_GRACEFUL
)
1825 int cg_mask_to_string(CGroupMask mask
, char **ret
) {
1826 _cleanup_free_
char *s
= NULL
;
1827 size_t n
= 0, allocated
= 0;
1838 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1842 if (!FLAGS_SET(mask
, CGROUP_CONTROLLER_TO_MASK(c
)))
1845 k
= cgroup_controller_to_string(c
);
1848 if (!GREEDY_REALLOC(s
, allocated
, n
+ space
+ l
+ 1))
1853 memcpy(s
+ n
+ space
, k
, l
);
1867 int cg_mask_from_string(const char *value
, CGroupMask
*ret
) {
1874 _cleanup_free_
char *n
= NULL
;
1878 r
= extract_first_word(&value
, &n
, NULL
, 0);
1884 v
= cgroup_controller_from_string(n
);
1888 m
|= CGROUP_CONTROLLER_TO_MASK(v
);
1895 int cg_mask_supported(CGroupMask
*ret
) {
1899 /* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
1900 * are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
1901 * pseudo-controllers. */
1903 r
= cg_all_unified();
1907 _cleanup_free_
char *root
= NULL
, *controllers
= NULL
, *path
= NULL
;
1909 /* In the unified hierarchy we can read the supported and accessible controllers from
1910 * the top-level cgroup attribute */
1912 r
= cg_get_root_path(&root
);
1916 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
1920 r
= read_one_line_file(path
, &controllers
);
1924 r
= cg_mask_from_string(controllers
, &mask
);
1928 /* Mask controllers that are not supported in unified hierarchy. */
1929 mask
&= CGROUP_MASK_V2
;
1934 /* In the legacy hierarchy, we check which hierarchies are mounted. */
1937 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1938 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1941 if (!FLAGS_SET(CGROUP_MASK_V1
, bit
))
1944 n
= cgroup_controller_to_string(c
);
1945 if (controller_is_accessible(n
) >= 0)
1954 int cg_kernel_controllers(Set
**ret
) {
1955 _cleanup_set_free_free_ Set
*controllers
= NULL
;
1956 _cleanup_fclose_
FILE *f
= NULL
;
1961 /* Determines the full list of kernel-known controllers. Might include controllers we don't actually support
1962 * and controllers that aren't currently accessible (because not mounted). This does not include "name="
1963 * pseudo-controllers. */
1965 controllers
= set_new(&string_hash_ops
);
1969 r
= fopen_unlocked("/proc/cgroups", "re", &f
);
1977 /* Ignore the header line */
1978 (void) read_line(f
, SIZE_MAX
, NULL
);
1985 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
1991 return errno_or_else(EIO
);
2001 if (!cg_controller_is_valid(controller
)) {
2006 r
= set_consume(controllers
, controller
);
2011 *ret
= TAKE_PTR(controllers
);
2016 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup2 on
2017 * /sys/fs/cgroup/systemd. This unfortunately broke other tools (such as docker) which expected the v1
2018 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mounts v2 on
2019 * /sys/fs/cgroup/unified and maintains "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility
2022 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep
2023 * cgroup v2 process management but disable the compat dual layout, we return true on
2024 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and false on cg_hybrid_unified().
2026 static thread_local
bool unified_systemd_v232
;
2028 int cg_unified_cached(bool flush
) {
2029 static thread_local CGroupUnified unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2033 /* Checks if we support the unified hierarchy. Returns an
2034 * error when the cgroup hierarchies aren't mounted yet or we
2035 * have any other trouble determining if the unified hierarchy
2039 unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2040 else if (unified_cache
>= CGROUP_UNIFIED_NONE
)
2041 return unified_cache
;
2043 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
2044 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/\") failed: %m");
2046 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2047 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
2048 unified_cache
= CGROUP_UNIFIED_ALL
;
2049 } else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
)) {
2050 if (statfs("/sys/fs/cgroup/unified/", &fs
) == 0 &&
2051 F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2052 log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2053 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2054 unified_systemd_v232
= false;
2056 if (statfs("/sys/fs/cgroup/systemd/", &fs
) < 0)
2057 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2059 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2060 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2061 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2062 unified_systemd_v232
= true;
2063 } else if (F_TYPE_EQUAL(fs
.f_type
, CGROUP_SUPER_MAGIC
)) {
2064 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2065 unified_cache
= CGROUP_UNIFIED_NONE
;
2067 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2068 (unsigned long long) fs
.f_type
);
2069 unified_cache
= CGROUP_UNIFIED_NONE
;
2072 } else if (F_TYPE_EQUAL(fs
.f_type
, SYSFS_MAGIC
)) {
2073 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
2074 "No filesystem is currently mounted on /sys/fs/cgroup.");
2076 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
2077 "Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2078 (unsigned long long)fs
.f_type
);
2080 return unified_cache
;
2083 int cg_unified_controller(const char *controller
) {
2086 r
= cg_unified_cached(false);
2090 if (r
== CGROUP_UNIFIED_NONE
)
2093 if (r
>= CGROUP_UNIFIED_ALL
)
2096 return streq_ptr(controller
, SYSTEMD_CGROUP_CONTROLLER
);
2099 int cg_all_unified(void) {
2102 r
= cg_unified_cached(false);
2106 return r
>= CGROUP_UNIFIED_ALL
;
2109 int cg_hybrid_unified(void) {
2112 r
= cg_unified_cached(false);
2116 return r
== CGROUP_UNIFIED_SYSTEMD
&& !unified_systemd_v232
;
2119 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2120 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2121 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2122 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2123 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2126 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2127 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2128 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2129 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2130 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2133 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2135 bool is_cgroup_fs(const struct statfs
*s
) {
2136 return is_fs_type(s
, CGROUP_SUPER_MAGIC
) ||
2137 is_fs_type(s
, CGROUP2_SUPER_MAGIC
);
2140 bool fd_is_cgroup_fs(int fd
) {
2143 if (fstatfs(fd
, &s
) < 0)
2146 return is_cgroup_fs(&s
);
2149 static const char *const cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2150 [CGROUP_CONTROLLER_CPU
] = "cpu",
2151 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2152 [CGROUP_CONTROLLER_CPUSET
] = "cpuset",
2153 [CGROUP_CONTROLLER_IO
] = "io",
2154 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2155 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2156 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2157 [CGROUP_CONTROLLER_PIDS
] = "pids",
2158 [CGROUP_CONTROLLER_BPF_FIREWALL
] = "bpf-firewall",
2159 [CGROUP_CONTROLLER_BPF_DEVICES
] = "bpf-devices",
2162 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);
2164 CGroupMask
get_cpu_accounting_mask(void) {
2165 static CGroupMask needed_mask
= (CGroupMask
) -1;
2167 /* On kernel ≥4.15 with unified hierarchy, cpu.stat's usage_usec is
2168 * provided externally from the CPU controller, which means we don't
2169 * need to enable the CPU controller just to get metrics. This is good,
2170 * because enabling the CPU controller comes at a minor performance
2171 * hit, especially when it's propagated deep into large hierarchies.
2172 * There's also no separate CPU accounting controller available within
2173 * a unified hierarchy.
2175 * This combination of factors results in the desired cgroup mask to
2176 * enable for CPU accounting varying as follows:
2178 * ╔═════════════════════╤═════════════════════╗
2179 * ║ Linux ≥4.15 │ Linux <4.15 ║
2180 * ╔═══════════════╬═════════════════════╪═════════════════════╣
2181 * ║ Unified ║ nothing │ CGROUP_MASK_CPU ║
2182 * ╟───────────────╫─────────────────────┼─────────────────────╢
2183 * ║ Hybrid/Legacy ║ CGROUP_MASK_CPUACCT │ CGROUP_MASK_CPUACCT ║
2184 * ╚═══════════════╩═════════════════════╧═════════════════════╝
2186 * We check kernel version here instead of manually checking whether
2187 * cpu.stat is present for every cgroup, as that check in itself would
2188 * already be fairly expensive.
2190 * Kernels where this patch has been backported will therefore have the
2191 * CPU controller enabled unnecessarily. This is more expensive than
2192 * necessary, but harmless. ☺️
2195 if (needed_mask
== (CGroupMask
) -1) {
2196 if (cg_all_unified()) {
2198 assert_se(uname(&u
) >= 0);
2200 if (strverscmp_improved(u
.release
, "4.15") < 0)
2201 needed_mask
= CGROUP_MASK_CPU
;
2205 needed_mask
= CGROUP_MASK_CPUACCT
;
2211 bool cpu_accounting_is_cheap(void) {
2212 return get_cpu_accounting_mask() == 0;
2215 static const char* const managed_oom_mode_table
[_MANAGED_OOM_MODE_MAX
] = {
2216 [MANAGED_OOM_AUTO
] = "auto",
2217 [MANAGED_OOM_KILL
] = "kill",
2220 DEFINE_STRING_TABLE_LOOKUP(managed_oom_mode
, ManagedOOMMode
);
2222 static const char* const managed_oom_preference_table
[_MANAGED_OOM_PREFERENCE_MAX
] = {
2223 [MANAGED_OOM_PREFERENCE_NONE
] = "none",
2224 [MANAGED_OOM_PREFERENCE_AVOID
] = "avoid",
2225 [MANAGED_OOM_PREFERENCE_OMIT
] = "omit",
2228 DEFINE_STRING_TABLE_LOOKUP(managed_oom_preference
, ManagedOOMPreference
);