HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/basic/cgroup-util.c
Git blob: f120ac143df121a59d7f7a64724a2feb913781c8
Lines 1001–1825 of 1,825
const char *t;
assert(path);
t = skip_user_prefix(path);
if (!t)
return -ENXIO;
/* And from here on it looks pretty much the same as for a system unit, hence let's use the same
* parser. */
return cg_path_get_unit_full(t, ret_unit, ret_subgroup);
}
int cg_pid_get_user_unit_full(pid_t pid, char **ret_unit, char **ret_subgroup) {
int r;
_cleanup_free_ char *cgroup = NULL;
r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
if (r < 0)
return r;
return cg_path_get_user_unit_full(cgroup, ret_unit, ret_subgroup);
}
int cg_pidref_get_user_unit_full(const PidRef *pidref, char **ret_unit, char **ret_subgroup) {
int r;
if (!pidref_is_set(pidref))
return -ESRCH;
if (pidref_is_remote(pidref))
return -EREMOTE;
_cleanup_free_ char *unit = NULL, *subgroup = NULL;
r = cg_pid_get_user_unit_full(pidref->pid, &unit, &subgroup);
if (r < 0)
return r;
r = pidref_verify(pidref);
if (r < 0)
return r;
if (ret_unit)
*ret_unit = TAKE_PTR(unit);
if (ret_subgroup)
*ret_subgroup = TAKE_PTR(subgroup);
return 0;
}
int cg_path_get_machine_name(const char *path, char **ret_machine) {
_cleanup_free_ char *u = NULL;
const char *sl;
int r;
r = cg_path_get_unit(path, &u);
if (r < 0)
return r;
sl = strjoina("/run/systemd/machines/unit:", u);
return readlink_malloc(sl, ret_machine);
}
int cg_pid_get_machine_name(pid_t pid, char **ret_machine) {
_cleanup_free_ char *cgroup = NULL;
int r;
r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
if (r < 0)
return r;
return cg_path_get_machine_name(cgroup, ret_machine);
}
int cg_path_get_session(const char *path, char **ret_session) {
_cleanup_free_ char *unit = NULL;
char *start, *end;
int r;
assert(path);
r = cg_path_get_unit(path, &unit);
if (r < 0)
return r;
start = startswith(unit, "session-");
if (!start)
return -ENXIO;
end = endswith(start, ".scope");
if (!end)
return -ENXIO;
*end = 0;
if (!session_id_valid(start))
return -ENXIO;
if (!ret_session)
return 0;
return strdup_to(ret_session, start);
}
int cg_pid_get_session(pid_t pid, char **ret_session) {
_cleanup_free_ char *cgroup = NULL;
int r;
r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
if (r < 0)
return r;
return cg_path_get_session(cgroup, ret_session);
}
int cg_pidref_get_session(const PidRef *pidref, char **ret) {
int r;
if (!pidref_is_set(pidref))
return -ESRCH;
if (pidref_is_remote(pidref))
return -EREMOTE;
_cleanup_free_ char *session = NULL;
r = cg_pid_get_session(pidref->pid, &session);
if (r < 0)
return r;
r = pidref_verify(pidref);
if (r < 0)
return r;
if (ret)
*ret = TAKE_PTR(session);
return 0;
}
int cg_path_get_owner_uid(const char *path, uid_t *ret_uid) {
_cleanup_free_ char *slice = NULL;
char *start, *end;
int r;
assert(path);
r = cg_path_get_slice(path, &slice);
if (r < 0)
return r;
start = startswith(slice, "user-");
if (!start)
return -ENXIO;
end = endswith(start, ".slice");
if (!end)
return -ENXIO;
*end = 0;
if (parse_uid(start, ret_uid) < 0)
return -ENXIO;
return 0;
}
int cg_pid_get_owner_uid(pid_t pid, uid_t *ret_uid) {
_cleanup_free_ char *cgroup = NULL;
int r;
r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
if (r < 0)
return r;
return cg_path_get_owner_uid(cgroup, ret_uid);
}
int cg_pidref_get_owner_uid(const PidRef *pidref, uid_t *ret) {
int r;
if (!pidref_is_set(pidref))
return -ESRCH;
if (pidref_is_remote(pidref))
return -EREMOTE;
uid_t uid;
r = cg_pid_get_owner_uid(pidref->pid, &uid);
if (r < 0)
return r;
r = pidref_verify(pidref);
if (r < 0)
return r;
if (ret)
*ret = uid;
return 0;
}
int cg_path_get_slice(const char *p, char **ret_slice) {
const char *e = NULL;
assert(p);
/* Finds the right-most slice unit from the beginning, but stops before we come to
* the first non-slice unit. */
for (;;) {
const char *s;
int n;
n = path_find_first_component(&p, /* accept_dot_dot= */ false, &s);
if (n < 0)
return n;
if (!valid_slice_name(s, n))
break;
e = s;
}
if (e)
return cg_path_decode_unit(e, ret_slice);
if (ret_slice)
return strdup_to(ret_slice, SPECIAL_ROOT_SLICE);
return 0;
}
int cg_pid_get_slice(pid_t pid, char **ret_slice) {
_cleanup_free_ char *cgroup = NULL;
int r;
r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
if (r < 0)
return r;
return cg_path_get_slice(cgroup, ret_slice);
}
int cg_path_get_user_slice(const char *p, char **ret_slice) {
const char *t;
assert(p);
t = skip_user_prefix(p);
if (!t)
return -ENXIO;
/* And now it looks pretty much the same as for a system slice, so let's just use the same parser
* from here on. */
return cg_path_get_slice(t, ret_slice);
}
int cg_pid_get_user_slice(pid_t pid, char **ret_slice) {
_cleanup_free_ char *cgroup = NULL;
int r;
r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
if (r < 0)
return r;
return cg_path_get_user_slice(cgroup, ret_slice);
}
bool cg_needs_escape(const char *p) {
/* Checks if the specified path is a valid cgroup name by our rules, or if it must be escaped. Note
* that we consider escaped cgroup names invalid here, as they need to be escaped a second time if
* they shall be used. Also note that various names cannot be made valid by escaping even if we
* return true here (because too long, or contain the forbidden character "/"). */
if (!filename_is_valid(p))
return true;
if (IN_SET(p[0], '_', '.'))
return true;
if (STR_IN_SET(p, "notify_on_release", "release_agent", "tasks"))
return true;
if (startswith(p, "cgroup."))
return true;
for (CGroupController c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
const char *q;
q = startswith(p, cgroup_controller_to_string(c));
if (!q)
continue;
if (q[0] == '.')
return true;
}
return false;
}
int cg_escape(const char *p, char **ret) {
_cleanup_free_ char *n = NULL;
assert(ret);
/* This implements very minimal escaping for names to be used as file names in the cgroup tree: any
* name which might conflict with a kernel name or is prefixed with '_' is prefixed with a '_'. That
* way, when reading cgroup names it is sufficient to remove a single prefixing underscore if there
* is one. */
/* The return value of this function (unlike cg_unescape()) needs free()! */
if (cg_needs_escape(p)) {
n = strjoin("_", p);
if (!n)
return -ENOMEM;
if (!filename_is_valid(n)) /* became invalid due to the prefixing? Or contained things like a slash that cannot be fixed by prefixing? */
return -EINVAL;
} else {
n = strdup(p);
if (!n)
return -ENOMEM;
}
*ret = TAKE_PTR(n);
return 0;
}
char* cg_unescape(const char *p) {
assert(p);
/* The return value of this function (unlike cg_escape())
* doesn't need free()! */
if (p[0] == '_')
return (char*) p+1;
return (char*) p;
}
int cg_slice_to_path(const char *unit, char **ret) {
_cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
const char *dash;
int r;
assert(unit);
assert(ret);
if (streq(unit, SPECIAL_ROOT_SLICE))
return strdup_to(ret, "");
if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
return -EINVAL;
if (!endswith(unit, ".slice"))
return -EINVAL;
r = unit_name_to_prefix(unit, &p);
if (r < 0)
return r;
dash = strchr(p, '-');
/* Don't allow initial dashes */
if (dash == p)
return -EINVAL;
while (dash) {
_cleanup_free_ char *escaped = NULL;
char n[dash - p + sizeof(".slice")];
#if HAS_FEATURE_MEMORY_SANITIZER
/* msan doesn't instrument stpncpy, so it thinks
* n is later used uninitialized:
* https://github.com/google/sanitizers/issues/926
*/
zero(n);
#endif
/* Don't allow trailing or double dashes */
if (IN_SET(dash[1], 0, '-'))
return -EINVAL;
strcpy(stpncpy(n, p, dash - p), ".slice");
if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
return -EINVAL;
r = cg_escape(n, &escaped);
if (r < 0)
return r;
if (!strextend(&s, escaped, "/"))
return -ENOMEM;
dash = strchr(dash+1, '-');
}
r = cg_escape(unit, &e);
if (r < 0)
return r;
if (!strextend(&s, e))
return -ENOMEM;
*ret = TAKE_PTR(s);
return 0;
}
int cg_is_threaded(const char *path) {
_cleanup_free_ char *fs = NULL, *contents = NULL;
_cleanup_strv_free_ char **v = NULL;
int r;
r = cg_get_path(path, "cgroup.type", &fs);
if (r < 0)
return r;
r = read_full_virtual_file(fs, &contents, NULL);
if (r == -ENOENT)
return false; /* Assume no. */
if (r < 0)
return r;
v = strv_split(contents, NULL);
if (!v)
return -ENOMEM;
/* If the cgroup is in the threaded mode, it contains "threaded".
* If one of the parents or siblings is in the threaded mode, it may contain "invalid". */
return strv_contains(v, "threaded") || strv_contains(v, "invalid");
}
int cg_set_attribute(const char *path, const char *attribute, const char *value) {
_cleanup_free_ char *p = NULL;
int r;
assert(attribute);
r = cg_get_path(path, attribute, &p);
if (r < 0)
return r;
/* https://lore.kernel.org/all/20250419183545.1982187-1-shakeel.butt@linux.dev/ adds O_NONBLOCK
* semantics to memory.max and memory.high to skip synchronous memory reclaim when O_NONBLOCK is
* enabled. Let's always open cgroupv2 attribute files in nonblocking mode to immediately take
* advantage of this and any other asynchronous resource reclaim that's added to the cgroupv2 API in
* the future. */
return write_string_file(p, value, WRITE_STRING_FILE_DISABLE_BUFFER|WRITE_STRING_FILE_OPEN_NONBLOCKING);
}
int cg_get_attribute(const char *path, const char *attribute, char **ret) {
_cleanup_free_ char *p = NULL;
int r;
assert(attribute);
r = cg_get_path(path, attribute, &p);
if (r < 0)
return r;
return read_one_line_file(p, ret);
}
int cg_get_attribute_as_uint64(const char *path, const char *attribute, uint64_t *ret) {
_cleanup_free_ char *value = NULL;
uint64_t v;
int r;
assert(ret);
r = cg_get_attribute(path, attribute, &value);
if (r == -ENOENT)
return -ENODATA;
if (r < 0)
return r;
if (streq(value, "max")) {
*ret = CGROUP_LIMIT_MAX;
return 0;
}
r = safe_atou64(value, &v);
if (r < 0)
return r;
*ret = v;
return 0;
}
int cg_get_attribute_as_bool(const char *path, const char *attribute) {
_cleanup_free_ char *value = NULL;
int r;
r = cg_get_attribute(path, attribute, &value);
if (r == -ENOENT)
return -ENODATA;
if (r < 0)
return r;
return parse_boolean(value);
}
int cg_get_owner(const char *path, uid_t *ret_uid) {
_cleanup_free_ char *f = NULL;
struct stat stats;
int r;
assert(ret_uid);
r = cg_get_path(path, /* suffix= */ NULL, &f);
if (r < 0)
return r;
if (stat(f, &stats) < 0)
return -errno;
r = stat_verify_directory(&stats);
if (r < 0)
return r;
*ret_uid = stats.st_uid;
return 0;
}
int cg_get_keyed_attribute(
const char *path,
const char *attribute,
char * const *keys,
char **values) {
_cleanup_free_ char *filename = NULL, *contents = NULL;
size_t n;
int r;
assert(path);
assert(attribute);
/* Reads one or more fields of a cgroup v2 keyed attribute file. The 'keys' parameter should be an strv with
* all keys to retrieve. The 'values' parameter should be passed as string size with the same number of
* entries as 'keys'. On success each entry will be set to the value of the matching key.
*
* If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
r = cg_get_path(path, attribute, &filename);
if (r < 0)
return r;
r = read_full_file(filename, &contents, /* ret_size= */ NULL);
if (r < 0)
return r;
n = strv_length(keys);
if (n == 0) /* No keys to retrieve? That's easy, we are done then */
return 0;
assert(strv_is_uniq(keys));
/* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
char **v = newa0(char*, n);
size_t n_done = 0;
for (const char *p = contents; *p;) {
const char *w;
size_t i;
for (i = 0; i < n; i++) {
w = first_word(p, keys[i]);
if (w)
break;
}
if (w) {
if (v[i]) { /* duplicate entry? */
r = -EBADMSG;
goto fail;
}
size_t l = strcspn(w, NEWLINE);
v[i] = strndup(w, l);
if (!v[i]) {
r = -ENOMEM;
goto fail;
}
n_done++;
if (n_done >= n)
break;
p = w + l;
} else
p += strcspn(p, NEWLINE);
p += strspn(p, NEWLINE);
}
if (n_done < n) {
r = -ENXIO;
goto fail;
}
memcpy(values, v, sizeof(char*) * n);
return 0;
fail:
free_many_charp(v, n);
return r;
}
int cg_get_keyed_attribute_uint64(const char *path, const char *attribute, const char *key, uint64_t *ret) {
_cleanup_free_ char *val = NULL;
int r;
assert(key);
assert(ret);
r = cg_get_keyed_attribute(path, attribute, STRV_MAKE(key), &val);
if (r < 0)
return r;
r = safe_atou64(val, ret);
if (r < 0)
return log_debug_errno(r, "Failed to parse value '%s' of key '%s' in cgroup attribute '%s': %m", val, key, attribute);
return 0;
}
int cg_mask_to_string(CGroupMask mask, char **ret) {
_cleanup_free_ char *s = NULL;
bool space = false;
CGroupController c;
size_t n = 0;
assert(ret);
if (mask == 0) {
*ret = NULL;
return 0;
}
for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
const char *k;
size_t l;
if (!FLAGS_SET(mask, CGROUP_CONTROLLER_TO_MASK(c)))
continue;
k = cgroup_controller_to_string(c);
l = strlen(k);
if (!GREEDY_REALLOC(s, n + space + l + 1))
return -ENOMEM;
if (space)
s[n] = ' ';
memcpy(s + n + space, k, l);
n += space + l;
space = true;
}
assert(s);
s[n] = 0;
*ret = TAKE_PTR(s);
return 0;
}
int cg_mask_from_string(const char *s, CGroupMask *ret) {
CGroupMask m = 0;
assert(ret);
assert(s);
for (;;) {
_cleanup_free_ char *n = NULL;
CGroupController v;
int r;
r = extract_first_word(&s, &n, NULL, 0);
if (r < 0)
return r;
if (r == 0)
break;
v = cgroup_controller_from_string(n);
if (v < 0)
continue;
m |= CGROUP_CONTROLLER_TO_MASK(v);
}
*ret = m;
return 0;
}
int cg_mask_supported_subtree(const char *root, CGroupMask *ret) {
CGroupMask mask;
int r;
assert(ret);
/* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
* are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
* pseudo-controllers. */
/* We can read the supported and accessible controllers from the top-level cgroup attribute */
_cleanup_free_ char *controllers = NULL, *path = NULL;
r = cg_get_path(root, "cgroup.controllers", &path);
if (r < 0)
return r;
r = read_one_line_file(path, &controllers);
if (r < 0)
return r;
r = cg_mask_from_string(controllers, &mask);
if (r < 0)
return r;
/* Mask controllers that are not supported in cgroup v2. */
mask &= CGROUP_MASK_V2;
*ret = mask;
return 0;
}
int cg_mask_supported(CGroupMask *ret) {
_cleanup_free_ char *root = NULL;
int r;
r = cg_get_root_path(&root);
if (r < 0)
return r;
return cg_mask_supported_subtree(root, ret);
}
int cg_is_delegated(const char *path) {
int r;
assert(path);
r = cg_get_xattr_bool(path, "trusted.delegate");
if (!ERRNO_IS_NEG_XATTR_ABSENT(r))
return r;
/* If the trusted xattr isn't set (preferred), then check the untrusted one. Under the assumption
* that whoever is trusted enough to own the cgroup, is also trusted enough to decide if it is
* delegated or not this should be safe. */
r = cg_get_xattr_bool(path, "user.delegate");
return ERRNO_IS_NEG_XATTR_ABSENT(r) ? false : r;
}
int cg_is_delegated_fd(int fd) {
int r;
assert(fd >= 0);
r = getxattr_at_bool(fd, /* path= */ NULL, "trusted.delegate", /* at_flags= */ 0);
if (!ERRNO_IS_NEG_XATTR_ABSENT(r))
return r;
r = getxattr_at_bool(fd, /* path= */ NULL, "user.delegate", /* at_flags= */ 0);
return ERRNO_IS_NEG_XATTR_ABSENT(r) ? false : r;
}
int cg_has_coredump_receive(const char *path) {
int r;
assert(path);
r = cg_get_xattr_bool(path, "user.coredump_receive");
if (ERRNO_IS_NEG_XATTR_ABSENT(r))
return false;
return r;
}
const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
[CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
[CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
[CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
[CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
};
static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
[CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
[CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
[CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
[CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
};
DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
void cgroup_io_limits_list(void) {
DUMP_STRING_TABLE(cgroup_io_limit_type, CGroupIOLimitType, _CGROUP_IO_LIMIT_TYPE_MAX);
}
static const char *const cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
[CGROUP_CONTROLLER_CPU] = "cpu",
[CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
[CGROUP_CONTROLLER_CPUSET] = "cpuset",
[CGROUP_CONTROLLER_IO] = "io",
[CGROUP_CONTROLLER_BLKIO] = "blkio",
[CGROUP_CONTROLLER_MEMORY] = "memory",
[CGROUP_CONTROLLER_DEVICES] = "devices",
[CGROUP_CONTROLLER_PIDS] = "pids",
[CGROUP_CONTROLLER_BPF_FIREWALL] = "bpf-firewall",
[CGROUP_CONTROLLER_BPF_DEVICES] = "bpf-devices",
[CGROUP_CONTROLLER_BPF_FOREIGN] = "bpf-foreign",
[CGROUP_CONTROLLER_BPF_SOCKET_BIND] = "bpf-socket-bind",
[CGROUP_CONTROLLER_BPF_RESTRICT_NETWORK_INTERFACES] = "bpf-restrict-network-interfaces",
[CGROUP_CONTROLLER_BPF_BIND_NETWORK_INTERFACE] = "bpf-bind-network-interface",
};
DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);
static const char* const managed_oom_mode_table[_MANAGED_OOM_MODE_MAX] = {
[MANAGED_OOM_AUTO] = "auto",
[MANAGED_OOM_KILL] = "kill",
};
DEFINE_STRING_TABLE_LOOKUP(managed_oom_mode, ManagedOOMMode);
static const char* const managed_oom_preference_table[_MANAGED_OOM_PREFERENCE_MAX] = {
[MANAGED_OOM_PREFERENCE_NONE] = "none",
[MANAGED_OOM_PREFERENCE_AVOID] = "avoid",
[MANAGED_OOM_PREFERENCE_OMIT] = "omit",
};
DEFINE_STRING_TABLE_LOOKUP(managed_oom_preference, ManagedOOMPreference);