HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/cgroup.c

179,588 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 543d1ac8e3c43a5af0861e2f1a038485663554eb

Lines 2001–3000 of 4,696

        assert(u);
        assert(ret);
 
        const CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt || !crt->cgroup_path)
                return unit_default_cgroup_path(u, ret);
 
        return strdup_to_full(ret, crt->cgroup_path); /* returns 1 -> cgroup_path is alive */
}
 
static int unit_watch_cgroup(Unit *u) {
        _cleanup_free_ char *events = NULL;
        int r;
 
        assert(u);
 
        /* Watches the "cgroups.events" attribute of this unit's cgroup for "empty" events. */
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt || !crt->cgroup_path)
                return 0;
 
        if (crt->cgroup_control_inotify_wd >= 0)
                return 0;
 
        /* No point in watch the top-level slice, it's never going to run empty. */
        if (unit_has_name(u, SPECIAL_ROOT_SLICE))
                return 0;
 
        r = hashmap_ensure_allocated(&u->manager->cgroup_control_inotify_wd_unit, &trivial_hash_ops);
        if (r < 0)
                return log_oom();
 
        r = cg_get_path(crt->cgroup_path, "cgroup.events", &events);
        if (r < 0)
                return log_oom();
 
        crt->cgroup_control_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
        if (crt->cgroup_control_inotify_wd < 0) {
 
                if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
                                      * is not an error */
                        return 0;
 
                return log_unit_error_errno(u, errno, "Failed to add control inotify watch descriptor for control group %s: %m", empty_to_root(crt->cgroup_path));
        }
 
        r = hashmap_put(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(crt->cgroup_control_inotify_wd), u);
        if (r < 0)
                return log_unit_error_errno(u, r, "Failed to add control inotify watch descriptor for control group %s to hash map: %m", empty_to_root(crt->cgroup_path));
 
        return 0;
}
 
static int unit_watch_cgroup_memory(Unit *u) {
        _cleanup_free_ char *events = NULL;
        int r;
 
        assert(u);
 
        /* Watches the "memory.events" attribute of this unit's cgroup for "oom_kill" events. */
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt || !crt->cgroup_path)
                return 0;
 
        CGroupContext *c = unit_get_cgroup_context(u);
        if (!c)
                return 0;
 
        /* The "memory.events" attribute is only available if the memory controller is on. Let's hence tie
         * this to memory accounting, in a way watching for OOM kills is a form of memory accounting after
         * all. */
        if (!c->memory_accounting)
                return 0;
 
        /* Don't watch inner nodes, as the kernel doesn't report oom_kill events recursively currently, and
         * we also don't want to generate a log message for each parent cgroup of a process. */
        if (u->type == UNIT_SLICE)
                return 0;
 
        if (crt->cgroup_memory_inotify_wd >= 0)
                return 0;
 
        r = hashmap_ensure_allocated(&u->manager->cgroup_memory_inotify_wd_unit, &trivial_hash_ops);
        if (r < 0)
                return log_oom();
 
        r = cg_get_path(crt->cgroup_path, "memory.events", &events);
        if (r < 0)
                return log_oom();
 
        crt->cgroup_memory_inotify_wd = inotify_add_watch(u->manager->cgroup_inotify_fd, events, IN_MODIFY);
        if (crt->cgroup_memory_inotify_wd < 0) {
 
                if (errno == ENOENT) /* If the directory is already gone we don't need to track it, so this
                                      * is not an error */
                        return 0;
 
                return log_unit_error_errno(u, errno, "Failed to add memory inotify watch descriptor for control group %s: %m", empty_to_root(crt->cgroup_path));
        }
 
        r = hashmap_put(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(crt->cgroup_memory_inotify_wd), u);
        if (r < 0)
                return log_unit_error_errno(u, r, "Failed to add memory inotify watch descriptor for control group %s to hash map: %m", empty_to_root(crt->cgroup_path));
 
        return 0;
}
 
static int unit_update_cgroup(
                Unit *u,
                CGroupMask target_mask,
                CGroupMask enable_mask,
                ManagerState state) {
 
        _cleanup_free_ char *cgroup = NULL, *cgroup_full_path = NULL;
        bool set_path, created;
        int r;
 
        assert(u);
 
        if (!UNIT_HAS_CGROUP_CONTEXT(u))
                return 0;
 
        r = unit_get_cgroup_path_with_fallback(u, &cgroup);
        if (r < 0)
                return log_unit_error_errno(u, r, "Failed to get cgroup path: %m");
        set_path = r == 0;
 
        /* First, create our own group */
        r = cg_create(cgroup);
        if (r < 0)
                return log_unit_error_errno(u, r, "Failed to create cgroup %s: %m", empty_to_root(cgroup));
        created = r;
 
        if (set_path) {
                r = unit_set_cgroup_path(u, cgroup);
                if (r == -EEXIST)
                        return log_unit_error_errno(u, r, "Picked control group '%s' as default, but it's in use already.", empty_to_root(cgroup));
                if (r < 0)
                        return log_unit_error_errno(u, r, "Failed to set unit's control group path to '%s': %m", empty_to_root(cgroup));
                assert(r > 0);
        }
 
        CGroupRuntime *crt = ASSERT_PTR(unit_get_cgroup_runtime(u));
 
        uint64_t cgroup_id = 0;
        r = cg_get_path(crt->cgroup_path, /* suffix= */ NULL, &cgroup_full_path);
        if (r < 0)
                log_unit_warning_errno(u, r, "Failed to get full cgroup path on cgroup %s, ignoring: %m", empty_to_root(crt->cgroup_path));
        else {
                r = path_to_handle_u64(cgroup_full_path, &cgroup_id);
                if (r < 0)
                        log_unit_full_errno(u, ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
                                            "Failed to get cgroup ID of cgroup %s, ignoring: %m", cgroup_full_path);
        }
 
        crt->cgroup_id = cgroup_id;
 
        /* Start watching it */
        (void) unit_watch_cgroup(u);
        (void) unit_watch_cgroup_memory(u);
 
        /* For v2 we preserve enabled controllers in delegated units, adjust others, */
        if (created || !unit_cgroup_delegate(u)) {
                CGroupMask result_mask = 0;
 
                /* Enable all controllers we need */
                r = cg_enable(u->manager->cgroup_supported, enable_mask, crt->cgroup_path, &result_mask);
                if (r < 0)
                        log_unit_warning_errno(u, r, "Failed to enable/disable controllers on cgroup %s, ignoring: %m", empty_to_root(crt->cgroup_path));
 
                /* Remember what's actually enabled now */
                crt->cgroup_enabled_mask = result_mask;
        }
 
        /* Keep track that this is now realized */
        crt->cgroup_realized_mask = target_mask;
 
        /* Set attributes */
        cgroup_context_apply(u, target_mask, state);
        cgroup_xattr_apply(u);
 
        /* For most units we expect that pressure monitoring is set up before the unit is started and we
         * won't touch it after. For PID 1 this is different though, because we couldn't possibly do that
         * given that PID 1 runs before init.scope is even set up. Hence, whenever init.scope is realized,
         * let's try to open the pressure interfaces anew. */
        if (unit_has_name(u, SPECIAL_INIT_SCOPE))
                for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++)
                        (void) manager_setup_pressure_event_source(u->manager, t);
 
        return 0;
}
 
static int unit_attach_pid_to_cgroup_via_bus(Unit *u, const char *cgroup_path, pid_t pid) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        int r;
 
        assert(u);
        assert(cgroup_path);
        assert(pid_is_valid(pid));
 
        if (MANAGER_IS_SYSTEM(u->manager))
                return -EINVAL;
 
        if (!u->manager->system_bus)
                return -EIO;
 
        /* Determine this unit's cgroup path relative to our cgroup root */
        const char *pp = path_startswith_full(cgroup_path,
                                              u->manager->cgroup_root,
                                              PATH_STARTSWITH_RETURN_LEADING_SLASH|PATH_STARTSWITH_REFUSE_DOT_DOT);
        if (!pp)
                return -EINVAL;
 
        r = bus_call_method(u->manager->system_bus,
                            bus_systemd_mgr,
                            "AttachProcessesToUnit",
                            &error, NULL,
                            "ssau",
                            NULL /* empty unit name means client's unit, i.e. us */, pp, 1, (uint32_t) pid);
        if (r < 0)
                return log_unit_debug_errno(u, r, "Failed to attach unit process " PID_FMT " via the bus: %s", pid, bus_error_message(&error, r));
 
        return 0;
}
 
int unit_attach_pids_to_cgroup(Unit *u, Set *pids, const char *suffix_path) {
        _cleanup_free_ char *joined = NULL;
        const char *p;
        int ret = 0, r;
 
        assert(u);
 
        if (!UNIT_HAS_CGROUP_CONTEXT(u))
                return -EINVAL;
 
        if (set_isempty(pids))
                return 0;
 
        r = unit_realize_cgroup(u);
        if (r < 0)
                return r;
 
        CGroupRuntime *crt = ASSERT_PTR(unit_get_cgroup_runtime(u));
 
        if (isempty(suffix_path))
                p = empty_to_root(crt->cgroup_path);
        else {
                assert(path_is_absolute(suffix_path));
 
                joined = path_join(crt->cgroup_path, suffix_path);
                if (!joined)
                        return -ENOMEM;
 
                p = joined;
        }
 
        PidRef *pid;
        SET_FOREACH(pid, pids) {
 
                /* Unfortunately we cannot add pids by pidfd to a cgroup. Hence we have to use PIDs instead,
                 * which of course is racy. Let's shorten the race a bit though, and re-validate the PID
                 * before we use it */
                r = pidref_verify(pid);
                if (r < 0) {
                        log_unit_info_errno(u, r, "PID " PID_FMT " vanished before we could move it to target cgroup '%s', skipping: %m", pid->pid, p);
                        continue;
                }
 
                r = cg_attach(p, pid->pid);
                if (r < 0) {
                        bool again = MANAGER_IS_USER(u->manager) && ERRNO_IS_NEG_PRIVILEGE(r);
 
                        log_unit_full_errno(u, again ? LOG_DEBUG : LOG_INFO,  r,
                                            "Couldn't move process "PID_FMT" to%s requested cgroup '%s': %m",
                                            pid->pid, again ? " directly" : "", p);
 
                        if (again) {
                                int z;
 
                                /* If we are in a user instance, and we can't move the process ourselves due
                                 * to permission problems, let's ask the system instance about it instead.
                                 * Since it's more privileged it might be able to move the process across the
                                 * leaves of a subtree whose top node is not owned by us. */
 
                                z = unit_attach_pid_to_cgroup_via_bus(u, p, pid->pid);
                                if (z >= 0)
                                        goto success;
 
                                log_unit_info_errno(u, z, "Couldn't move process "PID_FMT" to requested cgroup '%s' (directly or via the system bus): %m", pid->pid, p);
                        }
 
                        RET_GATHER(ret, r);
                        continue;
                }
 
        success:
                /* the cgroup is definitely not empty now. in case the unit was in the cgroup empty queue,
                 * drop it from there */
                unit_remove_from_cgroup_empty_queue(u);
 
                if (ret >= 0)
                        ret++; /* Count successful additions */
        }
 
        return ret;
}
 
int unit_remove_subcgroup(Unit *u, const char *suffix_path) {
        int r;
 
        assert(u);
 
        if (!UNIT_HAS_CGROUP_CONTEXT(u))
                return -EINVAL;
 
        if (!unit_cgroup_delegate(u))
                return -ENOMEDIUM;
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt || !crt->cgroup_path)
                return -EOWNERDEAD;
 
        _cleanup_free_ char *j = NULL;
        bool delete_root;
        const char *d;
        if (empty_or_root(suffix_path)) {
                d = empty_to_root(crt->cgroup_path);
                delete_root = false; /* Don't attempt to delete the main cgroup of this unit */
        } else {
                j = path_join(crt->cgroup_path, suffix_path);
                if (!j)
                        return -ENOMEM;
 
                d = j;
                delete_root = true;
        }
 
        log_unit_debug(u, "Removing subcgroup '%s'...", d);
 
        r = cg_trim(d, delete_root);
        if (r < 0)
                return log_unit_debug_errno(u, r, "Failed to fully %s cgroup '%s': %m", delete_root ? "remove" : "trim", d);
 
        return 0;
}
 
static bool unit_has_mask_realized(
                Unit *u,
                CGroupMask target_mask,
                CGroupMask enable_mask) {
 
        assert(u);
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt)
                return false;
 
        /* Returns true if this unit is fully realized. We check four things:
         *
         * 1. Whether the cgroup was created at all
         * 2. Whether the cgroup was created in all the hierarchies we need it to be created in (in case of cgroup v1)
         * 3. Whether the cgroup has all the right controllers enabled (in case of cgroup v2)
         * 4. Whether the invalidation mask is currently zero
         *
         * If you wonder why we mask the target realization and enable mask with CGROUP_MASK_V1/CGROUP_MASK_V2: note
         * that there are three sets of bitmasks: CGROUP_MASK_V1 (for real cgroup v1 controllers), CGROUP_MASK_V2 (for
         * real cgroup v2 controllers) and CGROUP_MASK_BPF (for BPF-based pseudo-controllers). Now, cgroup_realized_mask
         * is only matters for cgroup v1 controllers, and cgroup_enabled_mask only used for cgroup v2, and if they
         * differ in the others, we don't really care. (After all, the cgroup_enabled_mask tracks with controllers are
         * enabled through cgroup.subtree_control, and since the BPF pseudo-controllers don't show up there, they
         * simply don't matter. */
 
        return crt->cgroup_path &&
                ((crt->cgroup_realized_mask ^ target_mask) & CGROUP_MASK_V1) == 0 &&
                ((crt->cgroup_enabled_mask ^ enable_mask) & CGROUP_MASK_V2) == 0 &&
                crt->cgroup_invalidated_mask == 0;
}
 
static bool unit_has_mask_disables_realized(
                Unit *u,
                CGroupMask target_mask,
                CGroupMask enable_mask) {
 
        assert(u);
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt)
                return true;
 
        /* Returns true if all controllers which should be disabled are indeed disabled.
         *
         * Unlike unit_has_mask_realized, we don't care what was enabled, only that anything we want to remove is
         * already removed. */
 
        return !crt->cgroup_path ||
                (FLAGS_SET(crt->cgroup_realized_mask, target_mask & CGROUP_MASK_V1) &&
                 FLAGS_SET(crt->cgroup_enabled_mask, enable_mask & CGROUP_MASK_V2));
}
 
static bool unit_has_mask_enables_realized(
                Unit *u,
                CGroupMask target_mask,
                CGroupMask enable_mask) {
 
        assert(u);
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt)
                return false;
 
        /* Returns true if all controllers which should be enabled are indeed enabled.
         *
         * Unlike unit_has_mask_realized, we don't care about the controllers that are not present, only that anything
         * we want to add is already added. */
 
        return crt->cgroup_path &&
                ((crt->cgroup_realized_mask | target_mask) & CGROUP_MASK_V1) == (crt->cgroup_realized_mask & CGROUP_MASK_V1) &&
                ((crt->cgroup_enabled_mask | enable_mask) & CGROUP_MASK_V2) == (crt->cgroup_enabled_mask & CGROUP_MASK_V2);
}
 
void unit_add_to_cgroup_realize_queue(Unit *u) {
        assert(u);
 
        if (u->in_cgroup_realize_queue)
                return;
 
        LIST_APPEND(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
        u->in_cgroup_realize_queue = true;
}
 
static void unit_remove_from_cgroup_realize_queue(Unit *u) {
        assert(u);
 
        if (!u->in_cgroup_realize_queue)
                return;
 
        LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
        u->in_cgroup_realize_queue = false;
}
 
/* Controllers can only be enabled breadth-first, from the root of the
 * hierarchy downwards to the unit in question. */
static int unit_realize_cgroup_now_enable(Unit *u, ManagerState state) {
        CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
        Unit *slice;
        int r;
 
        assert(u);
 
        /* First go deal with this unit's parent, or we won't be able to enable
         * any new controllers at this layer. */
        slice = UNIT_GET_SLICE(u);
        if (slice) {
                r = unit_realize_cgroup_now_enable(slice, state);
                if (r < 0)
                        return r;
        }
 
        target_mask = unit_get_target_mask(u);
        enable_mask = unit_get_enable_mask(u);
 
        /* We can only enable in this direction, don't try to disable anything.
         */
        if (unit_has_mask_enables_realized(u, target_mask, enable_mask))
                return 0;
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
 
        new_target_mask = (crt ? crt->cgroup_realized_mask : 0) | target_mask;
        new_enable_mask = (crt ? crt->cgroup_enabled_mask : 0) | enable_mask;
 
        return unit_update_cgroup(u, new_target_mask, new_enable_mask, state);
}
 
/* Controllers can only be disabled depth-first, from the leaves of the
 * hierarchy upwards to the unit in question. */
static int unit_realize_cgroup_now_disable(Unit *u, ManagerState state) {
        Unit *m;
 
        assert(u);
 
        if (u->type != UNIT_SLICE)
                return 0;
 
        UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
                CGroupMask target_mask, enable_mask, new_target_mask, new_enable_mask;
                int r;
 
                CGroupRuntime *rt = unit_get_cgroup_runtime(m);
                if (!rt)
                        continue;
 
                /* The cgroup for this unit might not actually be fully realised yet, in which case it isn't
                 * holding any controllers open anyway. */
                if (!rt->cgroup_path)
                        continue;
 
                /* We must disable those below us first in order to release the controller. */
                (void) unit_realize_cgroup_now_disable(m, state);
 
                target_mask = unit_get_target_mask(m);
                enable_mask = unit_get_enable_mask(m);
 
                /* We can only disable in this direction, don't try to enable anything. */
                if (unit_has_mask_disables_realized(m, target_mask, enable_mask))
                        continue;
 
                new_target_mask = rt->cgroup_realized_mask & target_mask;
                new_enable_mask = rt->cgroup_enabled_mask & enable_mask;
 
                r = unit_update_cgroup(m, new_target_mask, new_enable_mask, state);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
/* Check if necessary controllers and attributes for a unit are in place.
 *
 * - If so, do nothing.
 * - If not, create paths, move processes over, and set attributes.
 *
 * Controllers can only be *enabled* in a breadth-first way, and *disabled* in
 * a depth-first way. As such the process looks like this:
 *
 * Suppose we have a cgroup hierarchy which looks like this:
 *
 *             root
 *            /    \
 *           /      \
 *          /        \
 *         a          b
 *        / \        / \
 *       /   \      /   \
 *      c     d    e     f
 *     / \   / \  / \   / \
 *     h i   j k  l m   n o
 *
 * 1. We want to realise cgroup "d" now.
 * 2. cgroup "a" has DisableControllers=cpu in the associated unit.
 * 3. cgroup "k" just started requesting the memory controller.
 *
 * To make this work we must do the following in order:
 *
 * 1. Disable CPU controller in k, j
 * 2. Disable CPU controller in d
 * 3. Enable memory controller in root
 * 4. Enable memory controller in a
 * 5. Enable memory controller in d
 * 6. Enable memory controller in k
 *
 * Notice that we need to touch j in one direction, but not the other. We also
 * don't go beyond d when disabling -- it's up to "a" to get realized if it
 * wants to disable further. The basic rules are therefore:
 *
 * - If you're disabling something, you need to realise all of the cgroups from
 *   your recursive descendants to the root. This starts from the leaves.
 * - If you're enabling something, you need to realise from the root cgroup
 *   downwards, but you don't need to iterate your recursive descendants.
 *
 * Returns 0 on success and < 0 on failure. */
static int unit_realize_cgroup_now(Unit *u, ManagerState state) {
        CGroupMask target_mask, enable_mask;
        Unit *slice;
        int r;
 
        assert(u);
 
        unit_remove_from_cgroup_realize_queue(u);
 
        target_mask = unit_get_target_mask(u);
        enable_mask = unit_get_enable_mask(u);
 
        if (unit_has_mask_realized(u, target_mask, enable_mask))
                return 0;
 
        /* Disable controllers below us, if there are any */
        r = unit_realize_cgroup_now_disable(u, state);
        if (r < 0)
                return r;
 
        /* Enable controllers above us, if there are any */
        slice = UNIT_GET_SLICE(u);
        if (slice) {
                r = unit_realize_cgroup_now_enable(slice, state);
                if (r < 0)
                        return r;
        }
 
        /* Now actually deal with the cgroup we were trying to realise and set attributes */
        r = unit_update_cgroup(u, target_mask, enable_mask, state);
        if (r < 0)
                return r;
 
        CGroupRuntime *crt = ASSERT_PTR(unit_get_cgroup_runtime(u));
 
        /* Now, reset the invalidation mask */
        crt->cgroup_invalidated_mask = 0;
        return 0;
}
 
unsigned manager_dispatch_cgroup_realize_queue(Manager *m) {
        ManagerState state;
        unsigned n = 0;
        Unit *i;
        int r;
 
        assert(m);
 
        state = manager_state(m);
 
        while ((i = m->cgroup_realize_queue)) {
                assert(i->in_cgroup_realize_queue);
 
                if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(i))) {
                        /* Maybe things changed, and the unit is not actually active anymore? */
                        unit_remove_from_cgroup_realize_queue(i);
                        continue;
                }
 
                r = unit_realize_cgroup_now(i, state);
                if (r < 0)
                        log_warning_errno(r, "Failed to realize cgroups for queued unit %s, ignoring: %m", i->id);
 
                n++;
        }
 
        return n;
}
 
void unit_add_family_to_cgroup_realize_queue(Unit *u) {
        assert(u);
        assert(u->type == UNIT_SLICE);
 
        /* Family of a unit for is defined as (immediate) children of the unit and immediate children of all
         * its ancestors.
         *
         * Ideally we would enqueue ancestor path only (bottom up). However, on cgroup-v1 scheduling becomes
         * very weird if two units that own processes reside in the same slice, but one is realized in the
         * "cpu" hierarchy and one is not (for example because one has CPUWeight= set and the other does
         * not), because that means individual processes need to be scheduled against whole cgroups. Let's
         * avoid this asymmetry by always ensuring that siblings of a unit are always realized in their v1
         * controller hierarchies too (if unit requires the controller to be realized).
         *
         * The function must invalidate cgroup_members_mask of all ancestors in order to calculate up to date
         * masks. */
 
        do {
                CGroupRuntime *crt = unit_get_cgroup_runtime(u);
 
                /* Children of u likely changed when we're called */
                if (crt)
                        crt->cgroup_members_mask_valid = false;
 
                Unit *m;
                UNIT_FOREACH_DEPENDENCY(m, u, UNIT_ATOM_SLICE_OF) {
 
                        /* No point in doing cgroup application for units without active processes. */
                        if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m)))
                                continue;
 
                        /* We only enqueue siblings if they were realized once at least, in the main
                         * hierarchy. */
                        crt = unit_get_cgroup_runtime(m);
                        if (!crt || !crt->cgroup_path)
                                continue;
 
                        /* If the unit doesn't need any new controllers and has current ones
                         * realized, it doesn't need any changes. */
                        if (unit_has_mask_realized(m,
                                                   unit_get_target_mask(m),
                                                   unit_get_enable_mask(m)))
                                continue;
 
                        unit_add_to_cgroup_realize_queue(m);
                }
 
                /* Parent comes after children */
                unit_add_to_cgroup_realize_queue(u);
 
                u = UNIT_GET_SLICE(u);
        } while (u);
}
 
int unit_realize_cgroup(Unit *u) {
        Unit *slice;
 
        assert(u);
 
        if (!UNIT_HAS_CGROUP_CONTEXT(u))
                return 0;
 
        /* So, here's the deal: when realizing the cgroups for this unit, we need to first create all
         * parents, but there's more actually: for the weight-based controllers we also need to make sure
         * that all our siblings (i.e. units that are in the same slice as we are) have cgroups, too.  On the
         * other hand, when a controller is removed from realized set, it may become unnecessary in siblings
         * and ancestors and they should be (de)realized too.
         *
         * This call will defer work on the siblings and derealized ancestors to the next event loop
         * iteration and synchronously creates the parent cgroups (unit_realize_cgroup_now). */
 
        slice = UNIT_GET_SLICE(u);
        if (slice)
                unit_add_family_to_cgroup_realize_queue(slice);
 
        /* And realize this one now (and apply the values) */
        return unit_realize_cgroup_now(u, manager_state(u->manager));
}
 
void unit_release_cgroup(Unit *u, bool drop_cgroup_runtime) {
        assert(u);
 
        /* Forgets all cgroup details for this cgroup — but does *not* destroy the cgroup. This is hence OK to call
         * when we close down everything for reexecution, where we really want to leave the cgroup in place. */
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt)
                return;
 
        if (crt->cgroup_path) {
                (void) hashmap_remove(u->manager->cgroup_unit, crt->cgroup_path);
                crt->cgroup_path = mfree(crt->cgroup_path);
        }
 
        if (crt->cgroup_control_inotify_wd >= 0) {
                if (inotify_rm_watch(u->manager->cgroup_inotify_fd, crt->cgroup_control_inotify_wd) < 0)
                        log_unit_debug_errno(u, errno, "Failed to remove cgroup control inotify watch %i for %s, ignoring: %m", crt->cgroup_control_inotify_wd, u->id);
 
                (void) hashmap_remove(u->manager->cgroup_control_inotify_wd_unit, INT_TO_PTR(crt->cgroup_control_inotify_wd));
                crt->cgroup_control_inotify_wd = -1;
        }
 
        if (crt->cgroup_memory_inotify_wd >= 0) {
                if (inotify_rm_watch(u->manager->cgroup_inotify_fd, crt->cgroup_memory_inotify_wd) < 0)
                        log_unit_debug_errno(u, errno, "Failed to remove cgroup memory inotify watch %i for %s, ignoring: %m", crt->cgroup_memory_inotify_wd, u->id);
 
                (void) hashmap_remove(u->manager->cgroup_memory_inotify_wd_unit, INT_TO_PTR(crt->cgroup_memory_inotify_wd));
                crt->cgroup_memory_inotify_wd = -1;
        }
 
        if (drop_cgroup_runtime)
                *(CGroupRuntime**) ((uint8_t*) u + UNIT_VTABLE(u)->cgroup_runtime_offset) = cgroup_runtime_free(crt);
}
 
int unit_cgroup_is_empty(Unit *u) {
        int r;
 
        assert(u);
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt)
                return -ENXIO;
        if (!crt->cgroup_path)
                return -EOWNERDEAD;
 
        r = cg_is_empty(crt->cgroup_path);
        if (r < 0)
                log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", empty_to_root(crt->cgroup_path));
        return r;
}
 
static bool unit_maybe_release_cgroup(Unit *u) {
        int r;
 
        /* Releases the cgroup only if it is recursively empty.
         * Returns true if the cgroup was released, false otherwise. */
 
        assert(u);
 
        /* Don't release the cgroup if there are still processes under it. If we get notified later when all
         * the processes exit (e.g. the processes were in D-state and exited after the unit was marked as
         * failed) we need the cgroup paths to continue to be tracked by the manager so they can be looked up
         * and cleaned up later. */
        r = unit_cgroup_is_empty(u);
        if (r > 0) {
                /* Do not free CGroupRuntime when called from unit_prune_cgroup. Various accounting data
                 * we should keep, especially CPU usage and *_peak ones which would be shown even after
                 * the unit stops. */
                unit_release_cgroup(u, /* drop_cgroup_runtime= */ false);
                return true;
        }
 
        return false;
}
 
static int unit_prune_cgroup_via_bus(Unit *u) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        int r;
 
        assert(u);
        assert(u->manager);
 
        if (MANAGER_IS_SYSTEM(u->manager))
                return -EINVAL;
 
        if (!u->manager->system_bus)
                return -EIO;
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt || !crt->cgroup_path)
                return -EOWNERDEAD;
 
        /* Determine this unit's cgroup path relative to our cgroup root */
        const char *pp = path_startswith_full(
                        crt->cgroup_path,
                        u->manager->cgroup_root,
                        PATH_STARTSWITH_RETURN_LEADING_SLASH|PATH_STARTSWITH_REFUSE_DOT_DOT);
        if (!pp)
                return -EINVAL;
 
        r = bus_call_method(u->manager->system_bus,
                            bus_systemd_mgr,
                            "RemoveSubgroupFromUnit",
                            &error, NULL,
                            "sst",
                            NULL /* empty unit name means client's unit, i.e. us */,
                            pp,
                            (uint64_t) 0);
        if (r < 0)
                return log_unit_debug_errno(u, r, "Failed to trim cgroup via the bus: %s", bus_error_message(&error, r));
 
        return 0;
}
 
void unit_prune_cgroup(Unit *u) {
        bool is_root_slice;
        int r;
 
        assert(u);
 
        /* Removes the cgroup, if empty and possible, and stops watching it. */
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt || !crt->cgroup_path)
                return;
 
        /* Cache the last resource usage values before we destroy the cgroup */
        (void) unit_get_cpu_usage(u, /* ret= */ NULL);
 
        for (CGroupMemoryAccountingMetric metric = 0; metric <= _CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST; metric++)
                (void) unit_get_memory_accounting(u, metric, /* ret= */ NULL);
 
        /* All IO metrics are read at once from the underlying cgroup, so issue just a single call */
        (void) unit_get_io_accounting(u, _CGROUP_IO_ACCOUNTING_METRIC_INVALID, /* ret= */ NULL);
 
        /* We do not cache IP metrics here because the firewall objects are not freed with cgroups */
 
#if BPF_FRAMEWORK
        (void) bpf_restrict_fs_cleanup(u); /* Remove cgroup from the global LSM BPF map */
#endif
 
        unit_modify_nft_set(u, /* add= */ false);
 
        is_root_slice = unit_has_name(u, SPECIAL_ROOT_SLICE);
 
        r = cg_trim(crt->cgroup_path, !is_root_slice);
        if (r < 0) {
                int k = unit_prune_cgroup_via_bus(u);
 
                if (k >= 0)
                        log_unit_debug_errno(u, r, "Failed to destroy cgroup %s on our own (%m), but worked when talking to PID 1.", empty_to_root(crt->cgroup_path));
                else {
                        /* One reason we could have failed here is, that the cgroup still contains a process.
                         * However, if the cgroup becomes removable at a later time, it might be removed when
                         * the containing slice is stopped. So even if we failed now, this unit shouldn't
                         * assume that the cgroup is still realized the next time it is started. Do not
                         * return early on error, continue cleanup. */
                        log_unit_full_errno(u, r == -EBUSY ? LOG_DEBUG : LOG_WARNING, r,
                                            "Failed to destroy cgroup %s, ignoring: %m", empty_to_root(crt->cgroup_path));
                }
        }
 
        if (is_root_slice)
                return;
 
        if (!unit_maybe_release_cgroup(u)) /* Returns true if the cgroup was released */
                return;
 
        assert(crt == unit_get_cgroup_runtime(u));
        assert(!crt->cgroup_path);
 
        crt->cgroup_realized_mask = 0;
        crt->cgroup_enabled_mask = 0;
 
        crt->bpf_device_control_installed = bpf_program_free(crt->bpf_device_control_installed);
}
 
int unit_search_main_pid(Unit *u, PidRef *ret) {
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
        _cleanup_fclose_ FILE *f = NULL;
        int r;
 
        assert(u);
        assert(ret);
 
        CGroupRuntime *crt = unit_get_cgroup_runtime(u);
        if (!crt || !crt->cgroup_path)
                return -ENXIO;
 
        r = cg_enumerate_processes(crt->cgroup_path, &f);
        if (r < 0)
                return r;
 
        for (;;) {
                _cleanup_(pidref_done) PidRef npidref = PIDREF_NULL;
 
                /* cg_read_pidref() will return an error on unmapped PIDs.
                 * We can't reasonably deal with units that contain those. */
                r = cg_read_pidref(f, &npidref, CGROUP_DONT_SKIP_UNMAPPED);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                if (pidref_equal(&pidref, &npidref)) /* seen already, cgroupfs reports duplicates! */
                        continue;
 
                if (pidref_is_my_child(&npidref) <= 0) /* ignore processes further down the tree */
                        continue;
 
                if (pidref_is_set(&pidref) != 0)
                        /* Dang, there's more than one daemonized PID in this group, so we don't know what
                         * process is the main process. */
                        return -ENODATA;
 
                pidref = TAKE_PIDREF(npidref);
        }
 
        if (!pidref_is_set(&pidref))
                return -ENODATA;
 
        *ret = TAKE_PIDREF(pidref);
        return 0;
}
 
static int on_cgroup_empty_event(sd_event_source *s, void *userdata) {
        Manager *m = ASSERT_PTR(userdata);
        Unit *u;
        int r;
 
        assert(s);
 
        u = m->cgroup_empty_queue;
        if (!u)
                return 0;
 
        assert(u->in_cgroup_empty_queue);
        u->in_cgroup_empty_queue = false;
        LIST_REMOVE(cgroup_empty_queue, m->cgroup_empty_queue, u);
 
        if (m->cgroup_empty_queue) {
                /* More stuff queued, let's make sure we remain enabled */
                r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
                if (r < 0)
                        log_debug_errno(r, "Failed to reenable cgroup empty event source, ignoring: %m");
        }
 
        /* Update state based on OOM kills before we notify about cgroup empty event */
        (void) unit_check_oom(u);
        (void) unit_check_oomd_kill(u);
 
        unit_add_to_gc_queue(u);
 
        if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)))
                unit_prune_cgroup(u);
        else if (UNIT_VTABLE(u)->notify_cgroup_empty)
                UNIT_VTABLE(u)->notify_cgroup_empty(u);
 
        return 0;
}
 
static void unit_add_to_cgroup_empty_queue(Unit *u) {
        int r;
 
        assert(u);
 
        /* Note that cgroup empty events are dispatched in a separate queue with a lower priority than
         * the SIGCHLD handler, so that we always use SIGCHLD if we can get it first, and only use
         * the cgroup empty notifications if there's no SIGCHLD pending (which might happen if the cgroup
         * doesn't contain processes that are our own child, which is typically the case for scope units). */
 
        if (u->in_cgroup_empty_queue)
                return;
 
        LIST_PREPEND(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
        u->in_cgroup_empty_queue = true;
 
        /* Trigger the defer event */
        r = sd_event_source_set_enabled(u->manager->cgroup_empty_event_source, SD_EVENT_ONESHOT);
        if (r < 0)
                log_debug_errno(r, "Failed to enable cgroup empty event source: %m");
}
 
static void unit_remove_from_cgroup_empty_queue(Unit *u) {
        assert(u);
 
        if (!u->in_cgroup_empty_queue)
                return;