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 1001–2000 of 7,295

}
 
static bool unit_should_warn_about_dependency(UnitDependency dependency) {
        /* Only warn about some unit types */
        return IN_SET(dependency,
                      UNIT_CONFLICTS,
                      UNIT_CONFLICTED_BY,
                      UNIT_BEFORE,
                      UNIT_AFTER,
                      UNIT_ON_SUCCESS,
                      UNIT_ON_FAILURE,
                      UNIT_TRIGGERS,
                      UNIT_TRIGGERED_BY);
}
 
static int unit_per_dependency_type_hashmap_update(
                Hashmap *per_type,
                Unit *other,
                UnitDependencyMask origin_mask,
                UnitDependencyMask destination_mask) {
 
        UnitDependencyInfo info;
        int r;
 
        assert(other);
        assert_cc(sizeof(void*) == sizeof(info));
 
        /* Acquire the UnitDependencyInfo entry for the Unit* we are interested in, and update it if it
         * exists, or insert it anew if not. */
 
        info.data = hashmap_get(per_type, other);
        if (info.data) {
                /* Entry already exists. Add in our mask. */
 
                if (FLAGS_SET(origin_mask, info.origin_mask) &&
                    FLAGS_SET(destination_mask, info.destination_mask))
                        return 0; /* NOP */
 
                info.origin_mask |= origin_mask;
                info.destination_mask |= destination_mask;
 
                r = hashmap_update(per_type, other, info.data);
        } else {
                info = (UnitDependencyInfo) {
                        .origin_mask = origin_mask,
                        .destination_mask = destination_mask,
                };
 
                r = hashmap_put(per_type, other, info.data);
        }
        if (r < 0)
                return r;
 
        return 1;
}
 
static void unit_merge_dependencies(Unit *u, Unit *other) {
        Hashmap *deps;
        void *dt; /* Actually of type UnitDependency, except that we don't bother casting it here,
                   * since the hashmaps all want it as void pointer. */
 
        assert(u);
        assert(other);
 
        if (u == other)
                return;
 
        /* First, remove dependency to other. */
        HASHMAP_FOREACH_KEY(deps, dt, u->dependencies) {
                if (hashmap_remove(deps, other) && unit_should_warn_about_dependency(UNIT_DEPENDENCY_FROM_PTR(dt)))
                        log_unit_warning(u, "Dependency %s=%s is dropped, as %s is merged into %s.",
                                         unit_dependency_to_string(UNIT_DEPENDENCY_FROM_PTR(dt)),
                                         other->id, other->id, u->id);
 
                if (hashmap_isempty(deps))
                        hashmap_free(hashmap_remove(u->dependencies, dt));
        }
 
        for (;;) {
                _cleanup_hashmap_free_ Hashmap *other_deps = NULL;
                UnitDependencyInfo di_back;
                Unit *back;
 
                /* Let's focus on one dependency type at a time, that 'other' has defined. */
                other_deps = hashmap_steal_first_key_and_value(other->dependencies, &dt);
                if (!other_deps)
                        break; /* done! */
 
                deps = hashmap_get(u->dependencies, dt);
 
                /* Now iterate through all dependencies of this dependency type, of 'other'. We refer to the
                 * referenced units as 'back'. */
                HASHMAP_FOREACH_KEY(di_back.data, back, other_deps) {
                        Hashmap *back_deps;
                        void *back_dt;
 
                        if (back == u) {
                                /* This is a dependency pointing back to the unit we want to merge with?
                                 * Suppress it (but warn) */
                                if (unit_should_warn_about_dependency(UNIT_DEPENDENCY_FROM_PTR(dt)))
                                        log_unit_warning(u, "Dependency %s=%s in %s is dropped, as %s is merged into %s.",
                                                         unit_dependency_to_string(UNIT_DEPENDENCY_FROM_PTR(dt)),
                                                         u->id, other->id, other->id, u->id);
 
                                hashmap_remove(other_deps, back);
                                continue;
                        }
 
                        /* Now iterate through all deps of 'back', and fix the ones pointing to 'other' to
                         * point to 'u' instead. */
                        HASHMAP_FOREACH_KEY(back_deps, back_dt, back->dependencies) {
                                UnitDependencyInfo di_move;
 
                                di_move.data = hashmap_remove(back_deps, other);
                                if (!di_move.data)
                                        continue;
 
                                assert_se(unit_per_dependency_type_hashmap_update(
                                                          back_deps,
                                                          u,
                                                          di_move.origin_mask,
                                                          di_move.destination_mask) >= 0);
                        }
 
                        /* The target unit already has dependencies of this type, let's then merge this individually. */
                        if (deps)
                                assert_se(unit_per_dependency_type_hashmap_update(
                                                          deps,
                                                          back,
                                                          di_back.origin_mask,
                                                          di_back.destination_mask) >= 0);
                }
 
                /* Now all references towards 'other' of the current type 'dt' are corrected to point to 'u'.
                 * Lets's now move the deps of type 'dt' from 'other' to 'u'. If the unit does not have
                 * dependencies of this type, let's move them per type wholesale. */
                if (!deps)
                        assert_se(hashmap_put(u->dependencies, dt, TAKE_PTR(other_deps)) >= 0);
        }
 
        other->dependencies = hashmap_free(other->dependencies);
 
        u->dependency_generation++;
        other->dependency_generation++;
}
 
int unit_merge(Unit *u, Unit *other) {
        int r;
 
        assert(u);
        assert(other);
        assert(u->manager == other->manager);
        assert(u->type != _UNIT_TYPE_INVALID);
 
        other = unit_follow_merge(other);
 
        if (other == u)
                return 0;
 
        if (u->type != other->type)
                return -EINVAL;
 
        if (!unit_type_may_alias(u->type)) /* Merging only applies to unit names that support aliases */
                return -EEXIST;
 
        if (!IN_SET(other->load_state, UNIT_STUB, UNIT_NOT_FOUND))
                return -EEXIST;
 
        if (!streq_ptr(u->instance, other->instance))
                return -EINVAL;
 
        if (other->job)
                return -EEXIST;
 
        if (other->nop_job)
                return -EEXIST;
 
        if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
                return -EEXIST;
 
        /* Make reservations to ensure merge_dependencies() won't fail. We don't rollback reservations if we
         * fail. We don't have a way to undo reservations. A reservation is not a leak. */
        r = unit_reserve_dependencies(u, other);
        if (r < 0)
                return r;
 
        /* Redirect all references */
        while (other->refs_by_target)
                unit_ref_set(other->refs_by_target, other->refs_by_target->source, u);
 
        /* Merge dependencies */
        unit_merge_dependencies(u, other);
 
        /* Merge names. It is better to do that after merging deps, otherwise the log message contains n/a. */
        r = unit_merge_names(u, other);
        if (r < 0)
                return r;
 
        UnitLoadState saved_load_state = other->load_state;
 
        other->load_state = UNIT_MERGED;
        other->merged_into = u;
 
        if (!u->activation_details)
                u->activation_details = activation_details_ref(other->activation_details);
 
        /* If there is still some data attached to the other node, we
         * don't need it anymore, and can free it. */
        if (saved_load_state != UNIT_STUB)
                if (UNIT_VTABLE(other)->done)
                        UNIT_VTABLE(other)->done(other);
 
        unit_add_to_dbus_queue(u);
        unit_add_to_cleanup_queue(other);
 
        return 0;
}
 
int unit_merge_by_name(Unit *u, const char *name) {
        _cleanup_free_ char *s = NULL;
        Unit *other;
        int r;
 
        /* Either add name to u, or if a unit with name already exists, merge it with u.
         * If name is a template, do the same for name@instance, where instance is u's instance. */
 
        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, &s);
                if (r < 0)
                        return r;
 
                name = s;
        }
 
        other = manager_get_unit(u->manager, name);
        if (other)
                return unit_merge(u, other);
 
        return unit_add_name(u, name);
}
 
Unit* unit_follow_merge(Unit *u) {
        assert(u);
 
        while (u->load_state == UNIT_MERGED)
                assert_se(u = u->merged_into);
 
        return u;
}
 
int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
        int r;
 
        assert(u);
        assert(c);
 
        /* Unlike unit_add_dependency() or friends, this always returns 0 on success. */
 
        if (c->working_directory) {
                r = unit_add_mounts_for(
                                u,
                                c->working_directory,
                                UNIT_DEPENDENCY_FILE,
                                c->working_directory_missing_ok ? UNIT_MOUNT_WANTS : UNIT_MOUNT_REQUIRES);
                if (r < 0)
                        return r;
        }
 
        if (c->root_directory) {
                r = unit_add_mounts_for(u, c->root_directory, UNIT_DEPENDENCY_FILE, UNIT_MOUNT_WANTS);
                if (r < 0)
                        return r;
        }
 
        if (c->root_image) {
                r = unit_add_mounts_for(u, c->root_image, UNIT_DEPENDENCY_FILE, UNIT_MOUNT_WANTS);
                if (r < 0)
                        return r;
        }
 
        if (c->root_mstack) {
                r = unit_add_mounts_for(u, c->root_mstack, UNIT_DEPENDENCY_FILE, UNIT_MOUNT_WANTS);
                if (r < 0)
                        return r;
        }
 
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
                if (!u->manager->prefix[dt])
                        continue;
 
                FOREACH_ARRAY(i, c->directories[dt].items, c->directories[dt].n_items) {
                        _cleanup_free_ char *p = NULL;
 
                        p = path_join(u->manager->prefix[dt], i->path);
                        if (!p)
                                return -ENOMEM;
 
                        r = unit_add_mounts_for(u, p, UNIT_DEPENDENCY_FILE, UNIT_MOUNT_REQUIRES);
                        if (r < 0)
                                return r;
                }
        }
 
        if (!MANAGER_IS_SYSTEM(u->manager))
                return 0;
 
        /* For the following three directory types we need write access, and /var/ is possibly on the root
         * fs. Hence order after systemd-remount-fs.service, to ensure things are writable. */
        if (c->directories[EXEC_DIRECTORY_STATE].n_items > 0 ||
            c->directories[EXEC_DIRECTORY_CACHE].n_items > 0 ||
            c->directories[EXEC_DIRECTORY_LOGS].n_items > 0) {
                r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_REMOUNT_FS_SERVICE, true, UNIT_DEPENDENCY_FILE);
                if (r < 0)
                        return r;
        }
 
        /* This must be already set in unit_patch_contexts(). */
        assert(c->private_var_tmp >= 0 && c->private_var_tmp < _PRIVATE_TMP_MAX);
 
        if (c->private_tmp == PRIVATE_TMP_CONNECTED) {
                r = unit_add_mounts_for(u, "/tmp/", UNIT_DEPENDENCY_FILE, UNIT_MOUNT_WANTS);
                if (r < 0)
                        return r;
        }
 
        if (c->private_var_tmp == PRIVATE_TMP_CONNECTED) {
                r = unit_add_mounts_for(u, "/var/tmp/", UNIT_DEPENDENCY_FILE, UNIT_MOUNT_WANTS);
                if (r < 0)
                        return r;
        } else if (c->private_var_tmp == PRIVATE_TMP_DISCONNECTED && !exec_context_with_rootfs(c)) {
                /* Even if PrivateTmp=disconnected, we still require /var/tmp/ mountpoint to be present,
                 * i.e. /var/ needs to be mounted. See comments in unit_patch_contexts(). */
                r = unit_add_mounts_for(u, "/var/", UNIT_DEPENDENCY_FILE, UNIT_MOUNT_WANTS);
                if (r < 0)
                        return r;
        }
 
        if (c->private_tmp == PRIVATE_TMP_CONNECTED || c->private_var_tmp == PRIVATE_TMP_CONNECTED) {
                r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_TMPFILES_SETUP_SERVICE, true, UNIT_DEPENDENCY_FILE);
                if (r < 0)
                        return r;
        }
 
        if (c->root_image || c->root_mstack) {
                /* We need to wait for /dev/loopX to appear when doing RootImage=, hence let's add an
                 * implicit dependency on udev. (And for RootMStack= we might need it) */
 
                r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_UDEVD_SERVICE, true, UNIT_DEPENDENCY_FILE);
                if (r < 0)
                        return r;
        }
 
        /* If syslog or kernel logging is requested (or log namespacing is), make sure our own logging daemon
         * is run first. */
        if (c->log_namespace) {
                static const struct {
                        const char *template;
                        UnitType type;
                } deps[] = {
                        { "systemd-journald",         UNIT_SOCKET,  },
                        { "systemd-journald-varlink", UNIT_SOCKET,  },
                        { "systemd-journald-sync",    UNIT_SERVICE, },
                };
 
                FOREACH_ELEMENT(i, deps) {
                        _cleanup_free_ char *unit = NULL;
 
                        r = unit_name_build_from_type(i->template, c->log_namespace, i->type, &unit);
                        if (r < 0)
                                return r;
 
                        r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, unit, true, UNIT_DEPENDENCY_FILE);
                        if (r < 0)
                                return r;
                }
        } else if (IN_SET(c->std_output, EXEC_OUTPUT_JOURNAL, EXEC_OUTPUT_JOURNAL_AND_CONSOLE,
                                         EXEC_OUTPUT_KMSG, EXEC_OUTPUT_KMSG_AND_CONSOLE) ||
                   IN_SET(c->std_error,  EXEC_OUTPUT_JOURNAL, EXEC_OUTPUT_JOURNAL_AND_CONSOLE,
                                         EXEC_OUTPUT_KMSG, EXEC_OUTPUT_KMSG_AND_CONSOLE)) {
 
                r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, true, UNIT_DEPENDENCY_FILE);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
const char* unit_description(Unit *u) {
        assert(u);
 
        if (u->description)
                return u->description;
 
        return strna(u->id);
}
 
const char* unit_status_string(Unit *u, char **ret_combined_buffer) {
        assert(u);
        assert(u->id);
 
        /* Return u->id, u->description, or "{u->id} - {u->description}".
         * Versions with u->description are only used if it is set.
         * The last option is used if configured and the caller provided the 'ret_combined_buffer'
         * pointer.
         *
         * Note that *ret_combined_buffer may be set to NULL. */
 
        if (!u->description ||
            u->manager->status_unit_format == STATUS_UNIT_FORMAT_NAME ||
            (u->manager->status_unit_format == STATUS_UNIT_FORMAT_COMBINED && !ret_combined_buffer) ||
            streq(u->description, u->id)) {
 
                if (ret_combined_buffer)
                        *ret_combined_buffer = NULL;
                return u->id;
        }
 
        if (ret_combined_buffer) {
                if (u->manager->status_unit_format == STATUS_UNIT_FORMAT_COMBINED) {
                        *ret_combined_buffer = strjoin(u->id, " - ", u->description);
                        if (*ret_combined_buffer)
                                return *ret_combined_buffer;
                        log_oom(); /* Fall back to ->description */
                } else
                        *ret_combined_buffer = NULL;
        }
 
        return u->description;
}
 
/* Common implementation for multiple backends */
int unit_load_fragment_and_dropin(Unit *u, bool fragment_required) {
        int r;
 
        assert(u);
 
        /* Load a .{service,socket,...} file */
        r = unit_load_fragment(u);
        if (r < 0)
                return r;
 
        if (u->load_state == UNIT_MASKED)
                return 0;
 
        if (u->load_state == UNIT_STUB) {
                if (fragment_required)
                        return -ENOENT;
 
                u->load_state = UNIT_LOADED;
        }
 
        u = unit_follow_merge(u);
 
        /* Load drop-in directory data. If u is an alias, we might be reloading the
         * target unit needlessly. But we cannot be sure which drops-ins have already
         * been loaded and which not, at least without doing complicated book-keeping,
         * so let's always reread all drop-ins. */
        r = unit_load_dropin(u);
        if (r < 0)
                return r;
 
        if (u->source_path) {
                struct stat st;
 
                if (stat(u->source_path, &st) >= 0)
                        u->source_mtime = timespec_load(&st.st_mtim);
                else
                        u->source_mtime = 0;
        }
 
        return 0;
}
 
void unit_add_to_target_deps_queue(Unit *u) {
        Manager *m = ASSERT_PTR(ASSERT_PTR(u)->manager);
 
        if (u->in_target_deps_queue)
                return;
 
        LIST_PREPEND(target_deps_queue, m->target_deps_queue, u);
        u->in_target_deps_queue = true;
}
 
int unit_add_default_target_dependency(Unit *u, Unit *target) {
        assert(u);
        assert(target);
 
        if (target->type != UNIT_TARGET)
                return 0;
 
        /* Only add the dependency if both units are loaded, so that
         * that loop check below is reliable */
        if (u->load_state != UNIT_LOADED ||
            target->load_state != UNIT_LOADED)
                return 0;
 
        /* If either side wants no automatic dependencies, then let's
         * skip this */
        if (!u->default_dependencies ||
            !target->default_dependencies)
                return 0;
 
        /* Don't create loops */
        if (unit_has_dependency(target, UNIT_ATOM_BEFORE, u))
                return 0;
 
        return unit_add_dependency(target, UNIT_AFTER, u, true, UNIT_DEPENDENCY_DEFAULT);
}
 
static int unit_add_slice_dependencies(Unit *u) {
        Unit *slice;
 
        assert(u);
 
        if (!UNIT_HAS_CGROUP_CONTEXT(u))
                return 0;
 
        /* Slice units are implicitly ordered against their parent slices (as this relationship is encoded in the
           name), while all other units are ordered based on configuration (as in their case Slice= configures the
           relationship). */
        UnitDependencyMask mask = u->type == UNIT_SLICE ? UNIT_DEPENDENCY_IMPLICIT : UNIT_DEPENDENCY_FILE;
 
        slice = UNIT_GET_SLICE(u);
        if (slice) {
                if (!IN_SET(slice->freezer_state, FREEZER_RUNNING, FREEZER_THAWING))
                        u->freezer_state = FREEZER_FROZEN_BY_PARENT;
 
                return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, slice, true, mask);
        }
 
        if (unit_has_name(u, SPECIAL_ROOT_SLICE))
                return 0;
 
        return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, true, mask);
}
 
static int unit_add_mount_dependencies(Unit *u) {
        bool changed = false;
        int r;
 
        assert(u);
 
        for (UnitMountDependencyType t = 0; t < _UNIT_MOUNT_DEPENDENCY_TYPE_MAX; ++t) {
                UnitDependencyInfo di;
                const char *path;
 
                HASHMAP_FOREACH_KEY(di.data, path, u->mounts_for[t]) {
 
                        char prefix[strlen(ASSERT_PTR(path)) + 1];
 
                        PATH_FOREACH_PREFIX_MORE(prefix, path) {
                                _cleanup_free_ char *p = NULL;
                                Unit *m;
 
                                r = unit_name_from_path(prefix, ".mount", &p);
                                if (r == -EINVAL)
                                        continue; /* If the path cannot be converted to a mount unit name,
                                                   * then it's not manageable as a unit by systemd, and
                                                   * hence we don't need a dependency on it. Let's thus
                                                   * silently ignore the issue. */
                                if (r < 0)
                                        return r;
 
                                m = manager_get_unit(u->manager, p);
                                if (!m) {
                                        /* Make sure to load the mount unit if it exists. If so the
                                         * dependencies on this unit will be added later during the loading
                                         * of the mount unit. */
                                        (void) manager_load_unit_prepare(
                                                        u->manager,
                                                        p,
                                                        /* path= */ NULL,
                                                        /* e= */ NULL,
                                                        &m);
                                        continue;
                                }
                                if (m == u)
                                        continue;
 
                                if (m->load_state != UNIT_LOADED)
                                        continue;
 
                                r = unit_add_dependency(
                                                u,
                                                UNIT_AFTER,
                                                m,
                                                /* add_reference= */ true,
                                                di.origin_mask);
                                if (r < 0)
                                        return r;
                                changed = changed || r > 0;
 
                                if (m->fragment_path) {
                                        r = unit_add_dependency(
                                                        u,
                                                        unit_mount_dependency_type_to_dependency_type(t),
                                                        m,
                                                        /* add_reference= */ true,
                                                        di.origin_mask);
                                        if (r < 0)
                                                return r;
                                        changed = changed || r > 0;
                                }
                        }
                }
        }
 
        return changed;
}
 
static int unit_add_oomd_dependencies(Unit *u) {
        CGroupContext *c;
        CGroupMask mask;
        int r;
 
        assert(u);
 
        if (!u->default_dependencies)
                return 0;
 
        c = unit_get_cgroup_context(u);
        if (!c)
                return 0;
 
        bool wants_oomd = c->moom_swap == MANAGED_OOM_KILL || c->moom_mem_pressure == MANAGED_OOM_KILL || !strv_isempty(c->moom_rules);
        if (!wants_oomd)
                return 0;
 
        r = cg_mask_supported(&mask);
        if (r < 0)
                return log_debug_errno(r, "Failed to determine supported controllers: %m");
 
        if (!FLAGS_SET(mask, CGROUP_MASK_MEMORY))
                return 0;
 
        return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_WANTS, "systemd-oomd.service", true, UNIT_DEPENDENCY_FILE);
}
 
static int unit_add_startup_units(Unit *u) {
        if (!unit_has_startup_cgroup_constraints(u))
                return 0;
 
        return set_ensure_put(&u->manager->startup_units, NULL, u);
}
 
static const struct {
        UnitDependencyAtom atom;
        size_t job_mode_offset;
        const char *dependency_name;
        const char *job_mode_setting_name;
} on_termination_settings[] = {
        { UNIT_ATOM_ON_SUCCESS, offsetof(Unit, on_success_job_mode), "OnSuccess=", "OnSuccessJobMode=" },
        { UNIT_ATOM_ON_FAILURE, offsetof(Unit, on_failure_job_mode), "OnFailure=", "OnFailureJobMode=" },
};
 
static int unit_validate_on_termination_job_modes(Unit *u) {
        assert(u);
 
        /* Verify that if On{Success,Failure}JobMode=isolate, only one unit gets specified. */
 
        FOREACH_ELEMENT(setting, on_termination_settings) {
                JobMode job_mode = *(JobMode*) ((uint8_t*) u + setting->job_mode_offset);
 
                if (job_mode != JOB_ISOLATE)
                        continue;
 
                Unit *other, *found = NULL;
                UNIT_FOREACH_DEPENDENCY(other, u, setting->atom) {
                        if (!found)
                                found = other;
                        else if (found != other)
                                return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC),
                                                            "More than one %s dependencies specified but %sisolate set. Refusing.",
                                                            setting->dependency_name, setting->job_mode_setting_name);
                }
        }
 
        return 0;
}
 
int unit_load(Unit *u) {
        int r;
 
        assert(u);
 
        if (u->in_load_queue) {
                LIST_REMOVE(load_queue, u->manager->load_queue, u);
                u->in_load_queue = false;
        }
 
        if (u->type == _UNIT_TYPE_INVALID)
                return -EINVAL;
 
        if (u->load_state != UNIT_STUB)
                return 0;
 
        if (u->transient_file) {
                /* Finalize transient file: if this is a transient unit file, as soon as we reach unit_load() the setup
                 * is complete, hence let's synchronize the unit file we just wrote to disk. */
 
                r = fflush_and_check(u->transient_file);
                if (r < 0)
                        goto fail;
 
                u->transient_file = safe_fclose(u->transient_file);
                u->fragment_mtime = now(CLOCK_REALTIME);
        }
 
        r = UNIT_VTABLE(u)->load(u);
        if (r < 0)
                goto fail;
 
        assert(u->load_state != UNIT_STUB);
 
        if (u->load_state == UNIT_LOADED) {
                unit_add_to_target_deps_queue(u);
 
                r = unit_add_slice_dependencies(u);
                if (r < 0)
                        goto fail;
 
                r = unit_add_mount_dependencies(u);
                if (r < 0)
                        goto fail;
 
                r = unit_add_oomd_dependencies(u);
                if (r < 0)
                        goto fail;
 
                r = unit_add_startup_units(u);
                if (r < 0)
                        goto fail;
 
                r = unit_validate_on_termination_job_modes(u);
                if (r < 0)
                        goto fail;
 
                if (u->job_running_timeout != USEC_INFINITY && u->job_running_timeout > u->job_timeout)
                        log_unit_warning(u, "JobRunningTimeoutSec= is greater than JobTimeoutSec=, it has no effect.");
 
                /* We finished loading, let's ensure our parents recalculate the members mask */
                unit_invalidate_cgroup_members_masks(u);
        }
 
        assert((u->load_state != UNIT_MERGED) == !u->merged_into);
 
        unit_add_to_dbus_queue(unit_follow_merge(u));
        unit_add_to_gc_queue(u);
        (void) manager_varlink_send_managed_oom_update(u);
 
        return 0;
 
fail:
        /* We convert ENOEXEC errors to the UNIT_BAD_SETTING load state here. Configuration parsing code
         * should hence return ENOEXEC to ensure units are placed in this state after loading. */
 
        u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND :
                                     r == -ENOEXEC ? UNIT_BAD_SETTING :
                                                     UNIT_ERROR;
        u->load_error = r;
 
        /* Record the timestamp on the cache, so that if the cache gets updated between now and the next time
         * an attempt is made to load this unit, we know we need to check again. */
        if (u->load_state == UNIT_NOT_FOUND)
                u->fragment_not_found_timestamp_hash = u->manager->unit_cache_timestamp_hash;
 
        unit_add_to_dbus_queue(u);
        unit_add_to_gc_queue(u);
 
        return log_unit_debug_errno(u, r, "Failed to load configuration: %m");
}
 
_printf_(7, 8)
static int log_unit_internal(void *userdata, int level, int error, const char *file, int line, const char *func, const char *format, ...) {
        Unit *u = userdata;
        va_list ap;
        int r;
 
        if (u && !unit_log_level_test(u, level))
                return -ERRNO_VALUE(error);
 
        va_start(ap, format);
        if (u)
                r = log_object_internalv(level, error, file, line, func,
                                         unit_log_field(u),
                                         u->id,
                                         unit_invocation_log_field(u),
                                         u->invocation_id_string,
                                         format, ap);
        else
                r = log_internalv(level, error,  file, line, func, format, ap);
        va_end(ap);
 
        return r;
}
 
static bool unit_test_condition(Unit *u) {
        _cleanup_strv_free_ char **env = NULL;
        int r;
 
        assert(u);
 
        dual_timestamp_now(&u->condition_timestamp);
 
        r = manager_get_effective_environment(u->manager, &env);
        if (r < 0) {
                log_unit_error_errno(u, r, "Failed to determine effective environment: %m");
                u->condition_result = true;
        } else
                u->condition_result = condition_test_list(
                                u->conditions,
                                env,
                                condition_type_to_string,
                                log_unit_internal,
                                u) > 0;
 
        unit_add_to_dbus_queue(u);
        return u->condition_result;
}
 
static bool unit_test_assert(Unit *u) {
        _cleanup_strv_free_ char **env = NULL;
        int r;
 
        assert(u);
 
        dual_timestamp_now(&u->assert_timestamp);
 
        r = manager_get_effective_environment(u->manager, &env);
        if (r < 0) {
                log_unit_error_errno(u, r, "Failed to determine effective environment: %m");
                u->assert_result = CONDITION_ERROR;
        } else
                u->assert_result = condition_test_list(
                                u->asserts,
                                env,
                                assert_type_to_string,
                                log_unit_internal,
                                u) > 0;
 
        unit_add_to_dbus_queue(u);
        return u->assert_result;
}
 
void unit_status_printf(
                Unit *u,
                StatusType status_type,
                const char *status,
                const char *format,
                const char *ident) {
 
        assert(u);
 
        if (log_get_show_color()) {
                if (u->manager->status_unit_format == STATUS_UNIT_FORMAT_COMBINED && strchr(ident, ' '))
                        ident = strjoina(ANSI_HIGHLIGHT, u->id, ANSI_NORMAL, " - ", u->description);
                else
                        ident = strjoina(ANSI_HIGHLIGHT, ident, ANSI_NORMAL);
        }
 
        DISABLE_WARNING_FORMAT_NONLITERAL;
        manager_status_printf(u->manager, status_type, status, format, ident);
        REENABLE_WARNING;
}
 
int unit_test_start_limit(Unit *u) {
        const char *reason;
 
        assert(u);
 
        if (ratelimit_below(&u->start_ratelimit)) {
                u->start_limit_hit = false;
                return 0;
        }
 
        log_unit_warning(u, "Start request repeated too quickly.");
        u->start_limit_hit = true;
 
        reason = strjoina("unit ", u->id, " failed");
 
        emergency_action(
                        u->manager,
                        u->start_limit_action,
                        EMERGENCY_ACTION_IS_WATCHDOG|EMERGENCY_ACTION_WARN|EMERGENCY_ACTION_SLEEP_5S|EMERGENCY_ACTION_IS_FAILURE,
                        u->reboot_arg,
                        /* exit_status= */ -1,
                        reason);
 
        return -ECANCELED;
}
 
static bool unit_verify_deps(Unit *u) {
        Unit *other;
 
        assert(u);
 
        /* Checks whether all BindsTo= dependencies of this unit are fulfilled — if they are also combined
         * with After=. We do not check Requires= or Requisite= here as they only should have an effect on
         * the job processing, but do not have any effect afterwards. We don't check BindsTo= dependencies
         * that are not used in conjunction with After= as for them any such check would make things entirely
         * racy. */
 
        UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_CANNOT_BE_ACTIVE_WITHOUT) {
 
                if (!unit_has_dependency(u, UNIT_ATOM_AFTER, other))
                        continue;
 
                if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other))) {
                        log_unit_notice(u, "Bound to unit %s, but unit isn't active.", other->id);
                        return false;
                }
        }
 
        return true;
}
 
/* Errors that aren't really errors:
 *         -EALREADY:     Unit is already started.
 *         -ECOMM:        Condition failed
 *         -EAGAIN:       An operation is already in progress. Retry later.
 *
 * Errors that are real errors:
 *         -EBADR:        This unit type does not support starting.
 *         -ECANCELED:    Start limit hit, too many requests for now
 *         -EPROTO:       Assert failed
 *         -EINVAL:       Unit not loaded
 *         -EOPNOTSUPP:   Unit type not supported
 *         -ENOLINK:      The necessary dependencies are not fulfilled.
 *         -ESTALE:       This unit has been started before and can't be started a second time
 *         -EDEADLK:      This unit is frozen
 *         -ENOENT:       This is a triggering unit and unit to trigger is not loaded
 *         -ETOOMANYREFS: The hard concurrency limit of at least one of the slices the unit is contained in has been reached
 */
int unit_start(Unit *u, ActivationDetails *details) {
        UnitActiveState state;
        Unit *following;
        int r;
 
        assert(u);
 
        /* Let's hold off running start jobs for mount units when /proc/self/mountinfo monitor is ratelimited. */
        if (UNIT_VTABLE(u)->subsystem_ratelimited) {
                r = UNIT_VTABLE(u)->subsystem_ratelimited(u->manager);
                if (r < 0)
                        return r;
                if (r > 0)
                        return -EAGAIN;
        }
 
        /* If this is already started, then this will succeed. Note that this will even succeed if this unit
         * is not startable by the user. This is relied on to detect when we need to wait for units and when
         * waiting is finished. */
        state = unit_active_state(u);
        if (UNIT_IS_ACTIVE_OR_RELOADING(state))
                return -EALREADY;
        if (IN_SET(state, UNIT_DEACTIVATING, UNIT_MAINTENANCE))
                return -EAGAIN;
 
        /* Units that aren't loaded cannot be started */
        if (u->load_state != UNIT_LOADED)
                return -EINVAL;
 
        /* Refuse starting scope units more than once */
        if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_enter_timestamp))
                return -ESTALE;
 
        /* If the conditions were unmet, don't do anything at all. If we already are activating this call might
         * still be useful to speed up activation in case there is some hold-off time, but we don't want to
         * recheck the condition in that case. */
        if (state != UNIT_ACTIVATING &&
            !unit_test_condition(u))
                return log_unit_debug_errno(u, SYNTHETIC_ERRNO(ECOMM), "Starting requested but condition not met. Not starting unit.");
 
        /* If the asserts failed, fail the entire job */
        if (state != UNIT_ACTIVATING &&
            !unit_test_assert(u))
                return log_unit_notice_errno(u, SYNTHETIC_ERRNO(EPROTO), "Starting requested but asserts failed.");
 
        /* Units of types that aren't supported cannot be started. Note that we do this test only after the
         * condition checks, so that we rather return condition check errors (which are usually not
         * considered a true failure) than "not supported" errors (which are considered a failure).
         */
        if (!unit_type_supported(u->type))
                return -EOPNOTSUPP;
 
        /* Let's make sure that the deps really are in order before we start this. Normally the job engine
         * should have taken care of this already, but let's check this here again. After all, our
         * dependencies might not be in effect anymore, due to a reload or due to an unmet condition. */
        if (!unit_verify_deps(u))
                return -ENOLINK;
 
        /* Forward to the main object, if we aren't it. */
        following = unit_following(u);