HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/unit.c

263,853 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 1de634c975a3311494dacb28ce1bb5e67261717a

Lines 1–1000 of 7,295

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fnmatch.h>
#include <linux/capability.h>
#include <unistd.h>
 
#include "sd-bus.h"
#include "sd-id128.h"
#include "sd-messages.h"
#include "sd-varlink.h"
 
#include "all-units.h"
#include "alloc-util.h"
#include "ansi-color.h"
#include "bitfield.h"
#include "bpf-restrict-fs.h"
#include "bus-common-errors.h"
#include "bus-internal.h"
#include "bus-util.h"
#include "cgroup-setup.h"
#include "cgroup-util.h"
#include "chase.h"
#include "chattr-util.h"
#include "condition.h"
#include "dbus-unit.h"
#include "dropin.h"
#include "dynamic-user.h"
#include "env-util.h"
#include "escape.h"
#include "exec-credential.h"
#include "execute.h"
#include "exit-status.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "fs-util.h"
#include "id128-util.h"
#include "install.h"
#include "iovec-util.h"
#include "load-dropin.h"
#include "load-fragment.h"
#include "log.h"
#include "logarithm.h"
#include "mkdir.h"
#include "manager.h"
#include "mount-util.h"
#include "mountpoint-util.h"
#include "netlink-internal.h"
#include "path-util.h"
#include "process-util.h"
#include "quota-util.h"
#include "rm-rf.h"
#include "serialize.h"
#include "set.h"
#include "signal-util.h"
#include "siphash24.h"
#include "sparse-endian.h"
#include "special.h"
#include "specifier.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "tmpfile-util.h"
#include "umask-util.h"
#include "unit.h"
#include "unit-name.h"
#include "user-util.h"
#include "varlink.h"
 
/* Thresholds for logging at INFO level about resource consumption */
#define MENTIONWORTHY_CPU_NSEC     (1 * NSEC_PER_SEC)
#define MENTIONWORTHY_MEMORY_BYTES (64 * U64_MB)
#define MENTIONWORTHY_IO_BYTES     (1 * U64_MB)
#define MENTIONWORTHY_IP_BYTES     UINT64_C(0)
 
/* Thresholds for logging at NOTICE level about resource consumption */
#define NOTICEWORTHY_CPU_NSEC     (10 * NSEC_PER_MINUTE)
#define NOTICEWORTHY_MEMORY_BYTES (512 * U64_MB)
#define NOTICEWORTHY_IO_BYTES     (10 * U64_MB)
#define NOTICEWORTHY_IP_BYTES     (128 * U64_MB)
 
const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
        [UNIT_SERVICE]   = &service_vtable,
        [UNIT_SOCKET]    = &socket_vtable,
        [UNIT_TARGET]    = &target_vtable,
        [UNIT_DEVICE]    = &device_vtable,
        [UNIT_MOUNT]     = &mount_vtable,
        [UNIT_AUTOMOUNT] = &automount_vtable,
        [UNIT_SWAP]      = &swap_vtable,
        [UNIT_TIMER]     = &timer_vtable,
        [UNIT_PATH]      = &path_vtable,
        [UNIT_SLICE]     = &slice_vtable,
        [UNIT_SCOPE]     = &scope_vtable,
};
 
Unit* unit_new(Manager *m, size_t size) {
        Unit *u;
 
        assert(m);
        assert(size >= sizeof(Unit));
 
        u = malloc0(size);
        if (!u)
                return NULL;
 
        u->manager = m;
        u->type = _UNIT_TYPE_INVALID;
        u->default_dependencies = true;
        u->unit_file_state = _UNIT_FILE_STATE_INVALID;
        u->unit_file_preset = _PRESET_ACTION_INVALID;
        u->on_failure_job_mode = JOB_REPLACE;
        u->on_success_job_mode = JOB_FAIL;
        u->job_timeout = USEC_INFINITY;
        u->job_running_timeout = USEC_INFINITY;
        u->ref_uid = UID_INVALID;
        u->ref_gid = GID_INVALID;
 
        u->failure_action_exit_status = u->success_action_exit_status = -1;
 
        u->last_section_private = -1;
 
        u->start_ratelimit = m->defaults.start_limit;
 
        u->auto_start_stop_ratelimit = (const RateLimit) {
                .interval = 10 * USEC_PER_SEC,
                .burst = 16
        };
 
        return u;
}
 
int unit_new_for_name(Manager *m, size_t size, const char *name, Unit **ret) {
        _cleanup_(unit_freep) Unit *u = NULL;
        int r;
 
        assert(ret);
 
        u = unit_new(m, size);
        if (!u)
                return -ENOMEM;
 
        r = unit_add_name(u, name);
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(u);
 
        return r;
}
 
bool unit_has_name(const Unit *u, const char *name) {
        assert(u);
        assert(name);
 
        return streq_ptr(name, u->id) ||
               set_contains(u->aliases, name);
}
 
static void unit_init(Unit *u) {
        CGroupContext *cc;
        ExecContext *ec;
        KillContext *kc;
 
        assert(u);
        assert(u->manager);
        assert(u->type >= 0);
 
        cc = unit_get_cgroup_context(u);
        if (cc) {
                cgroup_context_init(cc);
 
                /* Copy in the manager defaults into the cgroup
                 * context, _before_ the rest of the settings have
                 * been initialized */
 
                cc->io_accounting = u->manager->defaults.io_accounting;
                cc->memory_accounting = u->manager->defaults.memory_accounting;
                cc->tasks_accounting = u->manager->defaults.tasks_accounting;
                cc->ip_accounting = u->manager->defaults.ip_accounting;
 
                if (u->type != UNIT_SLICE)
                        cc->tasks_max = u->manager->defaults.tasks_max;
 
                cc->memory_zswap_writeback = u->manager->defaults.memory_zswap_writeback;
 
                memcpy(cc->pressure, u->manager->defaults.pressure, sizeof(cc->pressure));
        }
 
        ec = unit_get_exec_context(u);
        if (ec) {
                exec_context_init(ec);
 
                if (u->manager->defaults.oom_score_adjust_set) {
                        ec->oom_score_adjust = u->manager->defaults.oom_score_adjust;
                        ec->oom_score_adjust_set = true;
                }
 
                ec->restrict_suid_sgid = u->manager->defaults.restrict_suid_sgid;
 
                if (MANAGER_IS_SYSTEM(u->manager))
                        ec->keyring_mode = EXEC_KEYRING_SHARED;
                else {
                        ec->keyring_mode = EXEC_KEYRING_INHERIT;
 
                        /* User manager might have its umask redefined by PAM or UMask=. In this
                         * case let the units it manages inherit this value by default. They can
                         * still tune this value through their own unit file */
                        (void) get_process_umask(0, &ec->umask);
                }
        }
 
        kc = unit_get_kill_context(u);
        if (kc)
                kill_context_init(kc);
 
        if (UNIT_VTABLE(u)->init)
                UNIT_VTABLE(u)->init(u);
}
 
static int unit_add_alias(Unit *u, char *donated_name) {
        int r;
 
        /* Make sure that u->names is allocated. We may leave u->names
         * empty if we fail later, but this is not a problem. */
        r = set_ensure_put(&u->aliases, &string_hash_ops_free, donated_name);
        if (r < 0)
                return r;
        assert(r > 0);
 
        return 0;
}
 
int unit_add_name(Unit *u, const char *text) {
        _cleanup_free_ char *name = NULL, *instance = NULL;
        UnitType t;
        int r;
 
        assert(u);
        assert(text);
 
        if (unit_name_is_valid(text, UNIT_NAME_TEMPLATE)) {
                if (!u->instance)
                        return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
                                                    "Instance is not set when adding name '%s'.", text);
 
                r = unit_name_replace_instance(text, u->instance, &name);
                if (r < 0)
                        return log_unit_debug_errno(u, r,
                                                    "Failed to build instance name from '%s': %m", text);
        } else {
                name = strdup(text);
                if (!name)
                        return -ENOMEM;
        }
 
        if (unit_has_name(u, name))
                return 0;
 
        if (hashmap_contains(u->manager->units, name))
                return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EEXIST),
                                            "Unit already exist when adding name '%s'.", name);
 
        if (!unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
                return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
                                            "Name '%s' is invalid.", name);
 
        t = unit_name_to_type(name);
        if (t < 0)
                return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
                                            "failed to derive unit type from name '%s'.", name);
 
        if (u->type != _UNIT_TYPE_INVALID && t != u->type)
                return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
                                            "Unit type is illegal: u->type(%d) and t(%d) for name '%s'.",
                                            u->type, t, name);
 
        r = unit_name_to_instance(name, &instance);
        if (r < 0)
                return log_unit_debug_errno(u, r, "Failed to extract instance from name '%s': %m", name);
 
        if (instance && !unit_type_may_template(t))
                return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL), "Templates are not allowed for name '%s'.", name);
 
        /* Ensure that this unit either has no instance, or that the instance matches. */
        if (u->type != _UNIT_TYPE_INVALID && !streq_ptr(u->instance, instance))
                return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
                                            "Cannot add name %s, the instances don't match (\"%s\" != \"%s\").",
                                            name, instance, u->instance);
 
        if (u->id && !unit_type_may_alias(t))
                return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EEXIST),
                                            "Cannot add name %s, aliases are not allowed for %s units.",
                                            name, unit_type_to_string(t));
 
        if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES)
                return log_unit_warning_errno(u, SYNTHETIC_ERRNO(E2BIG), "Cannot add name, manager has too many units.");
 
        /* Add name to the global hashmap first, because that's easier to undo */
        r = hashmap_put(u->manager->units, name, u);
        if (r < 0)
                return log_unit_debug_errno(u, r, "Add unit to hashmap failed for name '%s': %m", text);
 
        if (u->id) {
                r = unit_add_alias(u, name); /* unit_add_alias() takes ownership of the name on success */
                if (r < 0) {
                        hashmap_remove(u->manager->units, name);
                        return r;
                }
                TAKE_PTR(name);
 
        } else {
                /* A new name, we don't need the set yet. */
                assert(u->type == _UNIT_TYPE_INVALID);
                assert(!u->instance);
 
                u->type = t;
                u->id = TAKE_PTR(name);
                u->instance = TAKE_PTR(instance);
 
                LIST_PREPEND(units_by_type, u->manager->units_by_type[t], u);
                unit_init(u);
        }
 
        unit_add_to_dbus_queue(u);
        return 0;
}
 
int unit_choose_id(Unit *u, const char *name) {
        _cleanup_free_ char *t = NULL;
        char *s;
        int r;
 
        assert(u);
        assert(name);
 
        if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
                if (!u->instance)
                        return -EINVAL;
 
                r = unit_name_replace_instance(name, u->instance, &t);
                if (r < 0)
                        return r;
 
                name = t;
        }
 
        if (streq_ptr(u->id, name))
                return 0; /* Nothing to do. */
 
        /* Selects one of the aliases of this unit as the id */
        s = set_get(u->aliases, (char*) name);
        if (!s)
                return -ENOENT;
 
        if (u->id) {
                r = set_remove_and_put(u->aliases, name, u->id);
                if (r < 0)
                        return r;
        } else
                assert_se(set_remove(u->aliases, name)); /* see set_get() above… */
 
        u->id = s; /* Old u->id is now stored in the set, and s is not stored anywhere */
        unit_add_to_dbus_queue(u);
 
        return 0;
}
 
int unit_set_description(Unit *u, const char *description) {
        int r;
 
        assert(u);
 
        r = free_and_strdup(&u->description, empty_to_null(description));
        if (r < 0)
                return r;
        if (r > 0)
                unit_add_to_dbus_queue(u);
 
        return 0;
}
 
static bool unit_success_failure_handler_has_jobs(Unit *unit) {
        Unit *other;
 
        UNIT_FOREACH_DEPENDENCY(other, unit, UNIT_ATOM_ON_SUCCESS)
                if (other->job || other->nop_job)
                        return true;
 
        UNIT_FOREACH_DEPENDENCY(other, unit, UNIT_ATOM_ON_FAILURE)
                if (other->job || other->nop_job)
                        return true;
 
        return false;
}
 
void unit_release_resources(Unit *u) {
        UnitActiveState state;
        ExecContext *ec;
 
        assert(u);
 
        if (u->job || u->nop_job)
                return;
 
        if (u->perpetual)
                return;
 
        state = unit_active_state(u);
        if (!UNIT_IS_INACTIVE_OR_FAILED(state))
                return;
 
        if (unit_will_restart(u))
                return;
 
        ec = unit_get_exec_context(u);
        if (ec && ec->runtime_directory_preserve_mode == EXEC_PRESERVE_RESTART)
                exec_context_destroy_runtime_directory(ec, u->manager->prefix[EXEC_DIRECTORY_RUNTIME]);
 
        if (UNIT_VTABLE(u)->release_resources)
                UNIT_VTABLE(u)->release_resources(u);
}
 
bool unit_may_gc(Unit *u) {
        UnitActiveState state;
        int r;
 
        assert(u);
 
        /* Checks whether the unit is ready to be unloaded for garbage collection.  Returns true when the
         * unit may be collected, and false if there's some reason to keep it loaded.
         *
         * References from other units are *not* checked here. Instead, this is done in unit_gc_sweep(), but
         * using markers to properly collect dependency loops.
         */
 
        if (u->job || u->nop_job)
                return false;
 
        if (u->perpetual)
                return false;
 
        /* if we saw a cgroup empty event for this unit, stay around until we processed it so that we remove
         * the empty cgroup if possible. Similar, process any pending OOM events if they are already queued
         * before we release the unit. */
        if (u->in_cgroup_empty_queue || u->in_cgroup_oom_queue)
                return false;
 
        /* Make sure to send out D-Bus events before we unload the unit */
        if (u->in_dbus_queue)
                return false;
 
        if (sd_bus_track_count(u->bus_track) > 0)
                return false;
 
        state = unit_active_state(u);
 
        /* But we keep the unit object around for longer when it is referenced or configured to not be
         * gc'ed */
        switch (u->collect_mode) {
 
        case COLLECT_INACTIVE:
                if (state != UNIT_INACTIVE)
                        return false;
 
                break;
 
        case COLLECT_INACTIVE_OR_FAILED:
                if (!UNIT_IS_INACTIVE_OR_FAILED(state))
                        return false;
 
                break;
 
        default:
                assert_not_reached();
        }
 
        /* Check if any OnFailure= or on Success= jobs may be pending */
        if (unit_success_failure_handler_has_jobs(u))
                return false;
 
        /* If the unit has a cgroup, then check whether there's anything in it. If so, we should stay
         * around. Units with active processes should never be collected. */
        r = unit_cgroup_is_empty(u);
        if (r <= 0 && !IN_SET(r, -ENXIO, -EOWNERDEAD))
                return false; /* ENXIO/EOWNERDEAD means: currently not realized */
 
        if (unit_can_start(u) && BIT_SET(u->markers, UNIT_MARKER_NEEDS_START))
                return false;
 
        if (!UNIT_VTABLE(u)->may_gc)
                return true;
 
        return UNIT_VTABLE(u)->may_gc(u);
}
 
void unit_add_to_load_queue(Unit *u) {
        assert(u);
        assert(u->type != _UNIT_TYPE_INVALID);
 
        if (u->load_state != UNIT_STUB || u->in_load_queue)
                return;
 
        LIST_PREPEND(load_queue, u->manager->load_queue, u);
        u->in_load_queue = true;
}
 
void unit_add_to_cleanup_queue(Unit *u) {
        assert(u);
 
        if (u->in_cleanup_queue)
                return;
 
        LIST_PREPEND(cleanup_queue, u->manager->cleanup_queue, u);
        u->in_cleanup_queue = true;
}
 
void unit_add_to_gc_queue(Unit *u) {
        assert(u);
 
        if (u->in_gc_queue || u->in_cleanup_queue)
                return;
 
        if (!unit_may_gc(u))
                return;
 
        LIST_PREPEND(gc_queue, u->manager->gc_unit_queue, u);
        u->in_gc_queue = true;
}
 
void unit_add_to_dbus_queue(Unit *u) {
        assert(u);
        assert(u->type != _UNIT_TYPE_INVALID);
 
        if (u->load_state == UNIT_STUB || u->in_dbus_queue)
                return;
 
        /* Shortcut things if nobody cares */
        if (sd_bus_track_count(u->manager->subscribed) <= 0 &&
            sd_bus_track_count(u->bus_track) <= 0 &&
            set_isempty(u->manager->private_buses)) {
                u->sent_dbus_new_signal = true;
                return;
        }
 
        LIST_PREPEND(dbus_queue, u->manager->dbus_unit_queue, u);
        u->in_dbus_queue = true;
}
 
void unit_submit_to_stop_when_unneeded_queue(Unit *u) {
        assert(u);
 
        if (u->in_stop_when_unneeded_queue)
                return;
 
        if (!u->stop_when_unneeded)
                return;
 
        if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
                return;
 
        LIST_PREPEND(stop_when_unneeded_queue, u->manager->stop_when_unneeded_queue, u);
        u->in_stop_when_unneeded_queue = true;
}
 
void unit_submit_to_start_when_upheld_queue(Unit *u) {
        assert(u);
 
        if (u->in_start_when_upheld_queue)
                return;
 
        if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)))
                return;
 
        if (!unit_has_dependency(u, UNIT_ATOM_START_STEADILY, NULL))
                return;
 
        LIST_PREPEND(start_when_upheld_queue, u->manager->start_when_upheld_queue, u);
        u->in_start_when_upheld_queue = true;
}
 
void unit_submit_to_stop_when_bound_queue(Unit *u) {
        assert(u);
 
        if (u->in_stop_when_bound_queue)
                return;
 
        if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
                return;
 
        if (!unit_has_dependency(u, UNIT_ATOM_CANNOT_BE_ACTIVE_WITHOUT, NULL))
                return;
 
        LIST_PREPEND(stop_when_bound_queue, u->manager->stop_when_bound_queue, u);
        u->in_stop_when_bound_queue = true;
}
 
static bool unit_can_release_resources(Unit *u) {
        ExecContext *ec;
 
        assert(u);
 
        if (UNIT_VTABLE(u)->release_resources)
                return true;
 
        ec = unit_get_exec_context(u);
        if (ec && ec->runtime_directory_preserve_mode == EXEC_PRESERVE_RESTART)
                return true;
 
        return false;
}
 
void unit_submit_to_release_resources_queue(Unit *u) {
        assert(u);
 
        if (u->in_release_resources_queue)
                return;
 
        if (u->job || u->nop_job)
                return;
 
        if (u->perpetual)
                return;
 
        if (!unit_can_release_resources(u))
                return;
 
        LIST_PREPEND(release_resources_queue, u->manager->release_resources_queue, u);
        u->in_release_resources_queue = true;
}
 
void unit_add_to_stop_notify_queue(Unit *u) {
        assert(u);
 
        if (u->in_stop_notify_queue)
                return;
 
        assert(UNIT_VTABLE(u)->stop_notify);
 
        LIST_PREPEND(stop_notify_queue, u->manager->stop_notify_queue, u);
        u->in_stop_notify_queue = true;
}
 
void unit_remove_from_stop_notify_queue(Unit *u) {
        assert(u);
 
        if (!u->in_stop_notify_queue)
                return;
 
        LIST_REMOVE(stop_notify_queue, u->manager->stop_notify_queue, u);
        u->in_stop_notify_queue = false;
}
 
static void unit_clear_dependencies(Unit *u) {
        assert(u);
 
        /* Removes all dependencies configured on u and their reverse dependencies. */
 
        for (Hashmap *deps; (deps = hashmap_steal_first(u->dependencies));) {
 
                for (Unit *other; (other = hashmap_steal_first_key(deps));) {
                        Hashmap *other_deps;
 
                        HASHMAP_FOREACH(other_deps, other->dependencies)
                                hashmap_remove(other_deps, u);
 
                        unit_add_to_gc_queue(other);
                        other->dependency_generation++;
                }
 
                hashmap_free(deps);
        }
 
        u->dependencies = hashmap_free(u->dependencies);
        u->dependency_generation++;
}
 
static void unit_remove_transient(Unit *u) {
        assert(u);
        assert(u->manager);
 
        if (!u->transient)
                return;
 
        const char *dropin_directory = strjoina(u->id, ".d");
 
        STRV_FOREACH(i, u->dropin_paths) {
                _cleanup_free_ char *p = NULL, *pp = NULL;
 
                if (path_extract_directory(*i, &p) < 0) /* Get the drop-in directory from the drop-in file */
                        continue;
 
                if (path_extract_directory(p, &pp) < 0) /* Get the config directory from the drop-in directory */
                        continue;
 
                /* Only drop transient drop-ins */
                if (!path_equal(u->manager->lookup_paths.transient, pp))
                        continue;
 
                /* Drop the transient drop-in directory also from unit path cache. */
                if (path_equal(last_path_component(p), dropin_directory))
                        free(set_remove(u->manager->unit_path_cache, p));
 
                (void) unlink(*i);
                (void) rmdir(p);
        }
 
        if (u->fragment_path) {
                (void) unlink(u->fragment_path);
                (void) unit_file_remove_from_name_map(
                                &u->manager->lookup_paths,
                                &u->manager->unit_cache_timestamp_hash,
                                &u->manager->unit_id_map,
                                &u->manager->unit_name_map,
                                &u->manager->unit_path_cache,
                                u->fragment_path);
        }
}
 
static void unit_free_mounts_for(Unit *u) {
        assert(u);
 
        for (UnitMountDependencyType t = 0; t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX; ++t) {
                for (;;) {
                        _cleanup_free_ char *path = NULL;
 
                        path = hashmap_steal_first_key(u->mounts_for[t]);
                        if (!path)
                                break;
 
                        char s[strlen(path) + 1];
 
                        PATH_FOREACH_PREFIX_MORE(s, path) {
                                char *y;
                                Set *x;
 
                                x = hashmap_get2(u->manager->units_needing_mounts_for[t], s, (void**) &y);
                                if (!x)
                                        continue;
 
                                (void) set_remove(x, u);
 
                                if (set_isempty(x)) {
                                        assert_se(hashmap_remove(u->manager->units_needing_mounts_for[t], y));
                                        free(y);
                                        set_free(x);
                                }
                        }
                }
 
                u->mounts_for[t] = hashmap_free(u->mounts_for[t]);
        }
}
 
static void unit_done(Unit *u) {
        ExecContext *ec;
        CGroupContext *cc;
 
        assert(u);
 
        if (u->type < 0)
                return;
 
        if (UNIT_VTABLE(u)->done)
                UNIT_VTABLE(u)->done(u);
 
        ec = unit_get_exec_context(u);
        if (ec)
                exec_context_done(ec);
 
        cc = unit_get_cgroup_context(u);
        if (cc)
                cgroup_context_done(cc);
}
 
Unit* unit_free(Unit *u) {
        Unit *slice;
        char *t;
 
        if (!u)
                return NULL;
 
        sd_event_source_disable_unref(u->auto_start_stop_event_source);
 
        u->transient_file = safe_fclose(u->transient_file);
 
        if (!MANAGER_IS_RELOADING(u->manager))
                unit_remove_transient(u);
 
        bus_unit_send_removed_signal(u);
 
        unit_done(u);
 
        u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
        u->bus_track = sd_bus_track_unref(u->bus_track);
        u->varlink_unit_change = sd_varlink_unref(u->varlink_unit_change);
        u->deserialized_refs = strv_free(u->deserialized_refs);
        u->pending_freezer_invocation = sd_bus_message_unref(u->pending_freezer_invocation);
 
        unit_free_mounts_for(u);
 
        SET_FOREACH(t, u->aliases)
                hashmap_remove_value(u->manager->units, t, u);
        if (u->id)
                hashmap_remove_value(u->manager->units, u->id, u);
 
        if (!sd_id128_is_null(u->invocation_id))
                hashmap_remove_value(u->manager->units_by_invocation_id, &u->invocation_id, u);
 
        if (u->job) {
                Job *j = u->job;
                job_uninstall(j);
                job_free(j);
        }
 
        if (u->nop_job) {
                Job *j = u->nop_job;
                job_uninstall(j);
                job_free(j);
        }
 
        /* A unit is being dropped from the tree, make sure our family is realized properly. Do this after we
         * detach the unit from slice tree in order to eliminate its effect on controller masks. */
        slice = UNIT_GET_SLICE(u);
        unit_clear_dependencies(u);
        if (slice)
                unit_add_family_to_cgroup_realize_queue(slice);
 
        if (u->on_console)
                manager_unref_console(u->manager);
 
        unit_release_cgroup(u, /* drop_cgroup_runtime= */ true);
 
        if (!MANAGER_IS_RELOADING(u->manager))
                unit_unlink_state_files(u);
 
        unit_unref_uid_gid(u, false);
 
        (void) manager_update_failed_units(u->manager, u, false);
        set_remove(u->manager->startup_units, u);
 
        unit_unwatch_all_pids(u);
 
        while (u->refs_by_target)
                unit_ref_unset(u->refs_by_target);
 
        if (u->type != _UNIT_TYPE_INVALID)
                LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u);
 
        if (u->in_load_queue)
                LIST_REMOVE(load_queue, u->manager->load_queue, u);
 
        if (u->in_dbus_queue)
                LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u);
 
        if (u->in_cleanup_queue)
                LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u);
 
        if (u->in_gc_queue)
                LIST_REMOVE(gc_queue, u->manager->gc_unit_queue, u);
 
        if (u->in_cgroup_realize_queue)
                LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
 
        if (u->in_cgroup_empty_queue)
                LIST_REMOVE(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
 
        if (u->in_cgroup_oom_queue)
                LIST_REMOVE(cgroup_oom_queue, u->manager->cgroup_oom_queue, u);
 
        if (u->in_target_deps_queue)
                LIST_REMOVE(target_deps_queue, u->manager->target_deps_queue, u);
 
        if (u->in_stop_when_unneeded_queue)
                LIST_REMOVE(stop_when_unneeded_queue, u->manager->stop_when_unneeded_queue, u);
 
        if (u->in_start_when_upheld_queue)
                LIST_REMOVE(start_when_upheld_queue, u->manager->start_when_upheld_queue, u);
 
        if (u->in_stop_when_bound_queue)
                LIST_REMOVE(stop_when_bound_queue, u->manager->stop_when_bound_queue, u);
 
        if (u->in_release_resources_queue)
                LIST_REMOVE(release_resources_queue, u->manager->release_resources_queue, u);
 
        unit_remove_from_stop_notify_queue(u);
 
        condition_free_list(u->conditions);
        condition_free_list(u->asserts);
 
        free(u->description);
        strv_free(u->documentation);
        free(u->fragment_path);
        free(u->source_path);
        strv_free(u->dropin_paths);
        free(u->instance);
 
        free(u->job_timeout_reboot_arg);
        free(u->reboot_arg);
 
        free(u->access_selinux_context);
 
        set_free(u->aliases);
        free(u->id);
 
        activation_details_unref(u->activation_details);
 
        return mfree(u);
}
 
UnitActiveState unit_active_state(Unit *u) {
        assert(u);
 
        if (u->load_state == UNIT_MERGED)
                return unit_active_state(unit_follow_merge(u));
 
        /* After a reload it might happen that a unit is not correctly
         * loaded but still has a process around. That's why we won't
         * shortcut failed loading to UNIT_INACTIVE_FAILED. */
 
        return UNIT_VTABLE(u)->active_state(u);
}
 
const char* unit_sub_state_to_string(Unit *u) {
        assert(u);
 
        return UNIT_VTABLE(u)->sub_state_to_string(u);
}
 
static int unit_merge_names(Unit *u, Unit *other) {
        char *name;
        int r;
 
        assert(u);
        assert(other);
 
        r = unit_add_alias(u, other->id);
        if (r < 0)
                return r;
 
        r = set_move(u->aliases, other->aliases);
        if (r < 0) {
                set_remove(u->aliases, other->id);
                return r;
        }
 
        TAKE_PTR(other->id);
        other->aliases = set_free(other->aliases);
 
        SET_FOREACH(name, u->aliases)
                assert_se(hashmap_replace(u->manager->units, name, u) == 0);
 
        return 0;
}
 
static int unit_reserve_dependencies(Unit *u, Unit *other) {
        size_t n_reserve;
        Hashmap* deps;
        void *d;
        int r;
 
        assert(u);
        assert(other);
 
        /* Let's reserve some space in the dependency hashmaps so that later on merging the units cannot
         * fail.
         *
         * First make some room in the per dependency type hashmaps. Using the summed size of both units'
         * hashmaps is an estimate that is likely too high since they probably use some of the same
         * types. But it's never too low, and that's all we need. */
 
        n_reserve = MIN(hashmap_size(other->dependencies), LESS_BY((size_t) _UNIT_DEPENDENCY_MAX, hashmap_size(u->dependencies)));
        if (n_reserve > 0) {
                r = hashmap_ensure_allocated(&u->dependencies, NULL);
                if (r < 0)
                        return r;
 
                r = hashmap_reserve(u->dependencies, n_reserve);
                if (r < 0)
                        return r;
        }
 
        /* Now, enlarge our per dependency type hashmaps by the number of entries in the same hashmap of the
         * other unit's dependencies.
         *
         * NB: If u does not have a dependency set allocated for some dependency type, there is no need to
         * reserve anything for. In that case other's set will be transferred as a whole to u by
         * complete_move(). */
 
        HASHMAP_FOREACH_KEY(deps, d, u->dependencies) {
                Hashmap *other_deps;
 
                other_deps = hashmap_get(other->dependencies, d);
 
                r = hashmap_reserve(deps, hashmap_size(other_deps));
                if (r < 0)
                        return r;
        }
 
        return 0;