HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/main.c

180,411 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 7887e0f02d9696e736ccfb06986d5d50dcb1cfc6

Lines 2001–3000 of 4,044

        if (skip_setup || !arg_early_core_pattern)
                return;
 
        if (getpid_cached() != 1)
                return;
 
        r = write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern, WRITE_STRING_FILE_DISABLE_BUFFER);
        if (r < 0)
                log_warning_errno(r, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
                                  arg_early_core_pattern);
}
 
static void apply_protect_system(bool skip_setup) {
        int r;
 
        if (skip_setup || getpid_cached() != 1 || arg_protect_system == 0)
                return;
 
        if (arg_protect_system < 0 && !in_initrd()) {
                log_debug("ProtectSystem=auto selected, but not running in an initrd, skipping.");
                return;
        }
 
        r = make_mount_point("/usr");
        if (r < 0) {
                log_warning_errno(r, "Failed to make /usr/ a mount point, ignoring: %m");
                return;
        }
 
        if (mount_nofollow_verbose(
                        LOG_WARNING,
                        /* what= */ NULL,
                        "/usr",
                        /* fstype= */ NULL,
                        MS_BIND|MS_REMOUNT|MS_RDONLY,
                        /* options= */ NULL) < 0)
                return;
 
        log_info("Successfully made /usr/ read-only.");
}
 
static void update_cpu_affinity(bool skip_setup) {
        _cleanup_free_ char *mask = NULL;
 
        if (skip_setup || !arg_cpu_affinity.set)
                return;
 
        assert(arg_cpu_affinity.allocated > 0);
 
        mask = cpu_set_to_range_string(&arg_cpu_affinity);
        log_debug("Setting CPU affinity to {%s}.", strnull(mask));
 
        if (sched_setaffinity(0, arg_cpu_affinity.allocated, arg_cpu_affinity.set) < 0)
                log_warning_errno(errno, "Failed to set CPU affinity, ignoring: %m");
}
 
static void update_numa_policy(bool skip_setup) {
        int r;
        _cleanup_free_ char *nodes = NULL;
        const char * policy = NULL;
 
        if (skip_setup || !mpol_is_valid(numa_policy_get_type(&arg_numa_policy)))
                return;
 
        if (DEBUG_LOGGING) {
                policy = mpol_to_string(numa_policy_get_type(&arg_numa_policy));
                nodes = cpu_set_to_range_string(&arg_numa_policy.nodes);
                log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy), strnull(nodes));
        }
 
        r = apply_numa_policy(&arg_numa_policy);
        if (r == -ENOSYS)
                log_debug_errno(r, "NUMA support not available, ignoring.");
        else if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
                log_warning_errno(r, "NUMA policy not supported by kernel, ignoring.");
        else if (r < 0)
                log_warning_errno(r, "Failed to set NUMA memory policy, ignoring: %m");
}
 
static void filter_args(
                const char* dst[],
                size_t *dst_index,
                char **src,
                int argc) {
 
        assert(dst);
        assert(dst_index);
 
        /* Copy some filtered arguments into the dst array from src. */
        for (int i = 1; i < argc; i++) {
                if (STR_IN_SET(src[i],
                               "--switched-root",
                               "--system",
                               "--user"))
                        continue;
 
                if (startswith(src[i], "--deserialize="))
                        continue;
                if (streq(src[i], "--deserialize")) {
                        i++;                            /* Skip the argument too */
                        continue;
                }
 
                /* Skip target unit designators. We already acted upon this information and have queued
                 * appropriate jobs. We don't want to redo all this after reexecution. */
                if (startswith(src[i], "--unit="))
                        continue;
                if (streq(src[i], "--unit")) {
                        i++;                            /* Skip the argument too */
                        continue;
                }
 
                /* Seems we have a good old option. Let's pass it over to the new instance. */
                dst[(*dst_index)++] = src[i];
        }
}
 
static void finish_remaining_processes(ManagerObjective objective) {
        assert(objective >= 0 && objective < _MANAGER_OBJECTIVE_MAX);
 
        /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
         * SIGCHLD for them after deserializing. */
        if (IN_SET(objective, MANAGER_SWITCH_ROOT, MANAGER_SOFT_REBOOT))
                broadcast_signal(SIGTERM, /* wait_for_exit= */ false, /* send_sighup= */ true, arg_defaults.timeout_stop_usec);
 
        /* On soft reboot really make sure nothing is left. Note that this will skip cgroups
         * of units that were configured with SurviveFinalKillSignal=yes. */
        if (objective == MANAGER_SOFT_REBOOT)
                broadcast_signal(SIGKILL, /* wait_for_exit= */ false, /* send_sighup= */ false, arg_defaults.timeout_stop_usec);
}
 
static void reduce_vt(ManagerObjective objective) {
        int r;
 
        if (objective != MANAGER_SOFT_REBOOT)
                return;
 
        /* Switches back to VT 1, and releases all other VTs, in an attempt to return to a situation similar
         * to how it was during the original kernel initialization. This is important because if some random
         * TTY is in foreground, /dev/console will end up pointing to it, where the future init system will
         * then write its status output to, but where it probably shouldn't be writing to. */
 
        r = chvt(1);
        if (r < 0)
                log_debug_errno(r, "Failed to switch to VT TTY 1, ignoring: %m");
 
        _cleanup_close_ int tty0_fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
        if (tty0_fd < 0)
                return (void) log_debug_errno(tty0_fd, "Failed to open '/dev/tty0', ignoring: %m");
 
        for (int ttynr = 2; ttynr <= VTNR_MAX; ttynr++)
                if (ioctl(tty0_fd, VT_DISALLOCATE, ttynr) < 0)
                        log_debug_errno(errno, "Failed to disallocate VT TTY %i, ignoring: %m", ttynr);
                else
                        log_debug("Successfully disallocated VT TTY %i.", ttynr);
}
 
static int do_reexecute(
                ManagerObjective objective,
                int argc,
                char* argv[],
                const struct rlimit *saved_rlimit_nofile,
                const struct rlimit *saved_rlimit_memlock,
                FDSet *_fds, /* donated */
                const char *switch_root_dir,
                const char *switch_root_init,
                uint64_t saved_capability_ambient_set,
                const char **ret_error_message) {
 
        size_t i, args_size;
        _cleanup_free_ char *our_exe = NULL;
        const char **args;
        int r;
 
        assert(IN_SET(objective, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT, MANAGER_SOFT_REBOOT));
        assert(argc >= 0);
        assert(saved_rlimit_nofile);
        assert(saved_rlimit_memlock);
        assert(ret_error_message);
 
        /* The fdset is donated to us, take ownership so it is freed on all exit paths. */
        _cleanup_fdset_free_ FDSet *fds = TAKE_PTR(_fds);
 
        /* Close and disarm the watchdog, so that the new instance can reinitialize it, but the machine
         * doesn't get rebooted while we do that. */
        watchdog_close(/* disarm= */ true);
 
        if (!switch_root_dir && objective == MANAGER_SOFT_REBOOT) {
                /* If no switch root dir is specified, then check if /run/nextroot/ qualifies and use that */
                r = path_is_os_tree("/run/nextroot");
                if (r < 0 && r != -ENOENT)
                        log_debug_errno(r, "Failed to determine if /run/nextroot/ is a valid OS tree, ignoring: %m");
                else if (r > 0)
                        switch_root_dir = "/run/nextroot";
        }
 
        if (switch_root_dir) {
                /* If we're supposed to switch root, preemptively check the existence of a usable init.
                 * Otherwise the system might end up in a completely undebuggable state afterwards. */
                if (switch_root_init) {
                        r = chase_and_access(switch_root_init, switch_root_dir, CHASE_PREFIX_ROOT, X_OK, /* ret_path= */ NULL);
                        if (r < 0)
                                log_warning_errno(r, "Failed to chase configured init %s/%s: %m",
                                                  switch_root_dir, switch_root_init);
                } else {
                        r = chase_and_access(SYSTEMD_BINARY_PATH, switch_root_dir, CHASE_PREFIX_ROOT, X_OK, /* ret_path= */ NULL);
                        if (r < 0)
                                log_debug_errno(r, "Failed to chase our own binary %s/%s: %m",
                                                switch_root_dir, SYSTEMD_BINARY_PATH);
                }
 
                if (r < 0) {
                        r = chase_and_access("/sbin/init", switch_root_dir, CHASE_PREFIX_ROOT, X_OK, /* ret_path= */ NULL);
                        if (r < 0) {
                                *ret_error_message = "Switch root target contains no usable init";
                                return log_error_errno(r, "Failed to chase %s/sbin/init", switch_root_dir);
                        }
                }
        }
 
        /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
         * the kernel default to its child processes */
        if (saved_rlimit_nofile->rlim_cur != 0)
                (void) setrlimit(RLIMIT_NOFILE, saved_rlimit_nofile);
        if (saved_rlimit_memlock->rlim_cur != RLIM_INFINITY)
                (void) setrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock);
 
        finish_remaining_processes(objective);
        reduce_vt(objective);
 
        if (switch_root_dir) {
                r = switch_root(/* new_root= */ switch_root_dir,
                                /* old_root_after= */ NULL,
                                /* flags= */ (objective == MANAGER_SWITCH_ROOT ? SWITCH_ROOT_DESTROY_OLD_ROOT : 0) |
                                             (objective == MANAGER_SOFT_REBOOT ? 0 : SWITCH_ROOT_RECURSIVE_RUN));
                if (r < 0)
                        log_error_errno(r, "Failed to switch root, trying to continue: %m");
        }
 
        r = capability_ambient_set_apply(saved_capability_ambient_set, /* also_inherit= */ false);
        if (r < 0)
                log_warning_errno(r, "Failed to apply the starting ambient set, ignoring: %m");
 
        args_size = argc + 5;
        args = newa(const char*, args_size);
 
        if (!switch_root_init) {
                char sfd[STRLEN("--deserialize=") + DECIMAL_STR_MAX(int)];
 
                /* First try to spawn ourselves with the right path, and with full serialization. We do this
                 * only if the user didn't specify an explicit init to spawn. */
 
                assert(arg_serialization);
                assert(fds);
 
                xsprintf(sfd, "--deserialize=%i", fileno(arg_serialization));
 
                i = 1;         /* Leave args[0] empty for now. */
 
                /* Put our stuff first to make sure it always gets parsed in case
                 * we get weird stuff from the kernel cmdline (like --) */
                if (IN_SET(objective, MANAGER_SWITCH_ROOT, MANAGER_SOFT_REBOOT))
                        args[i++] = "--switched-root";
                args[i++] = runtime_scope_cmdline_option_to_string(arg_runtime_scope);
                args[i++] = sfd;
 
                filter_args(args, &i, argv, argc);
 
                args[i++] = NULL;
 
                assert(i <= args_size);
 
                /*
                 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
                 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
                 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
                 * and wait() for it in the parent, before proceeding into the exec().
                 */
                valgrind_summary_hack();
 
                args[0] = SYSTEMD_BINARY_PATH;
                r = RET_NERRNO(execv(args[0], (char* const*) args));
 
                if (objective == MANAGER_REEXECUTE) {
                        /* If the binary is missing, try with our current executable too. This way things
                         * continue to work if the binary is installed into a non-default location. Note that
                         * we don't use chase here, the symlink the kernel gives is good enough. */
                        if (r == -ENOENT) {
                                int k;
 
                                k = readlink_malloc("/proc/self/exe", &our_exe);
                                if (k < 0)
                                        log_warning_errno(k, "Failed to read /proc/self/exe: %m");
                                else if (endswith(our_exe, " (deleted)"))
                                        log_info("The current binary (/proc/self/exe) has been deleted.");
                                else {
                                        log_info_errno(r, "Failed to execute our own binary %s, trying /proc/self/exe: %m", args[0]);
                                        args[0] = "/proc/self/exe";
                                        r = RET_NERRNO(execv(args[0], (char* const*) args));
                                }
                        }
 
                        *ret_error_message = "Failed to execute our own binary";
                        return log_error_errno(r, "Failed to execute our own binary %s: %m", args[0]);
                }
 
                log_debug_errno(r, "Failed to execute our own binary %s, trying fallback: %m", args[0]);
        }
 
        /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
         * envp[]. (Well, modulo the ordering changes due to option parsing in argv[], and some cleanups in
         * envp[], but let's hope that doesn't matter.) */
 
        arg_serialization = safe_fclose(arg_serialization);
        fds = fdset_free(fds);
 
        /* Drop /run/systemd directory. Some of its content can be used as a flag indicating that systemd is
         * the init system but we might be replacing it with something different. If systemd is used again it
         * will recreate the directory and its content anyway. */
        r = rm_rf("/run/systemd.pre-switch-root", REMOVE_ROOT|REMOVE_MISSING_OK);
        if (r < 0)
                log_warning_errno(r, "Failed to prepare /run/systemd.pre-switch-root/, ignoring: %m");
 
        r = RET_NERRNO(rename("/run/systemd", "/run/systemd.pre-switch-root"));
        if (r < 0)
                log_warning_errno(r, "Failed to move /run/systemd/ to /run/systemd.pre-switch-root/, ignoring: %m");
 
        /* Reopen the console */
        (void) make_console_stdio(/* switch_to_text= */ true);
 
        i = 1;         /* Leave args[0] empty for now. */
        for (int j = 1; j <= argc; j++)
                args[i++] = argv[j];
        assert(i <= args_size);
 
        /* Re-enable any blocked signals, especially important if we switch from initrd to init=... */
        (void) reset_all_signal_handlers();
        (void) reset_signal_mask();
        (void) rlimit_nofile_safe();
 
        if (switch_root_init) {
                args[0] = switch_root_init;
                r = RET_NERRNO(execve(args[0], (char* const*) args, saved_env));
                log_warning_errno(r, "Failed to execute configured init %s, trying fallback: %m", args[0]);
        }
 
        args[0] = "/sbin/init";
        r = RET_NERRNO(execv(args[0], (char* const*) args));
        *ret_error_message = "Failed to execute /sbin/init";
 
        if (r == -ENOENT) {
                manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
                                      ANSI_HIGHLIGHT_RED "  !!  " ANSI_NORMAL,
                                      "%s", *ret_error_message);
 
                log_warning_errno(r, "No /sbin/init, trying fallback shell");
 
                args[0] = "/bin/sh";
                args[1] = NULL;
                r = RET_NERRNO(execve(args[0], (char* const*) args, saved_env));
                *ret_error_message = "Failed to execute fallback shell";
        }
 
        return log_error_errno(r, "%s, giving up: %m", *ret_error_message);
}
 
static int invoke_main_loop(
                Manager *m,
                const struct rlimit *saved_rlimit_nofile,
                const struct rlimit *saved_rlimit_memlock,
                int *ret_retval,                   /* Return parameters relevant for shutting down */
                FDSet **ret_fds,                   /* Return parameters for reexecuting */
                char **ret_switch_root_dir,        /* … */
                char **ret_switch_root_init,       /* … */
                const char **ret_error_message) {
 
        int r;
 
        assert(m);
        assert(saved_rlimit_nofile);
        assert(saved_rlimit_memlock);
        assert(ret_retval);
        assert(ret_fds);
        assert(ret_switch_root_dir);
        assert(ret_switch_root_init);
        assert(ret_error_message);
 
        for (;;) {
                int objective = manager_loop(m);
                if (objective < 0) {
                        *ret_error_message = "Failed to run main loop";
                        return log_struct_errno(LOG_EMERG, objective,
                                                LOG_MESSAGE("Failed to run main loop: %m"),
                                                LOG_MESSAGE_ID(SD_MESSAGE_CORE_MAINLOOP_FAILED_STR));
                }
 
                /* Ensure shutdown timestamp is taken even when bypassing the job engine */
                if (IN_SET(objective,
                           MANAGER_SOFT_REBOOT,
                           MANAGER_REBOOT,
                           MANAGER_KEXEC,
                           MANAGER_HALT,
                           MANAGER_POWEROFF)) {
                        dual_timestamp ts;
 
                        dual_timestamp_now(&ts);
                        if (!dual_timestamp_is_set(m->timestamps + MANAGER_TIMESTAMP_SHUTDOWN_START))
                                m->timestamps[MANAGER_TIMESTAMP_SHUTDOWN_START] = ts;
                        m->timestamps[MANAGER_TIMESTAMP_SHUTDOWN_FINISH] = ts;
                }
 
                switch (objective) {
 
                case MANAGER_RELOAD: {
                        LogTarget saved_log_target;
                        int saved_log_level;
 
                        manager_send_reloading(m);
 
                        log_info("Reloading...");
 
                        /* First, save any overridden log level/target, then parse the configuration file,
                         * which might change the log level to new settings. */
 
                        saved_log_level = m->log_level_overridden ? log_get_max_level() : -1;
                        saved_log_target = m->log_target_overridden ? log_get_target() : _LOG_TARGET_INVALID;
 
                        (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
 
                        set_manager_defaults(m);
                        set_manager_settings(m);
 
                        update_cpu_affinity(false);
                        update_numa_policy(false);
 
                        if (saved_log_level >= 0)
                                manager_override_log_level(m, saved_log_level);
                        if (saved_log_target >= 0)
                                manager_override_log_target(m, saved_log_target);
 
                        if (manager_reload(m) < 0)
                                /* Reloading failed before the point of no return.
                                 * Let's continue running as if nothing happened. */
                                m->objective = MANAGER_OK;
                        else
                                log_info("Reloading finished in " USEC_FMT " ms.",
                                         usec_sub_unsigned(now(CLOCK_MONOTONIC), m->timestamps[MANAGER_TIMESTAMP_UNITS_LOAD].monotonic) / USEC_PER_MSEC);
 
                        continue;
                }
 
                case MANAGER_REEXECUTE:
 
                        manager_send_reloading(m); /* From the perspective of the manager calling us this is
                                                    * pretty much the same as a reload */
 
                        r = prepare_reexecute(m, &arg_serialization, ret_fds, false);
                        if (r < 0) {
                                *ret_error_message = "Failed to prepare for reexecution";
                                return r;
                        }
 
                        log_notice("Reexecuting.");
 
                        *ret_retval = EXIT_FAILURE;
                        *ret_switch_root_dir = *ret_switch_root_init = NULL;
 
                        return objective;
 
                case MANAGER_SWITCH_ROOT:
 
                        manager_send_reloading(m); /* From the perspective of the manager calling us this is
                                                    * pretty much the same as a reload */
 
                        manager_set_switching_root(m, true);
 
                        if (!m->switch_root_init) {
                                r = prepare_reexecute(m, &arg_serialization, ret_fds, true);
                                if (r < 0) {
                                        *ret_error_message = "Failed to prepare for reexecution";
                                        return r;
                                }
                        } else
                                *ret_fds = NULL;
 
                        log_notice("Switching root.");
 
                        *ret_retval = EXIT_FAILURE;
 
                        /* Steal the switch root parameters */
                        *ret_switch_root_dir = TAKE_PTR(m->switch_root);
                        *ret_switch_root_init = TAKE_PTR(m->switch_root_init);
 
                        return objective;
 
                case MANAGER_SOFT_REBOOT:
                        manager_send_reloading(m);
                        manager_set_switching_root(m, true);
 
                        r = prepare_reexecute(m, &arg_serialization, ret_fds, /* switching_root= */ true);
                        if (r < 0) {
                                *ret_error_message = "Failed to prepare for reexecution";
                                return r;
                        }
 
                        log_notice("Soft-rebooting.");
 
                        *ret_retval = EXIT_FAILURE;
                        *ret_switch_root_dir = TAKE_PTR(m->switch_root);
                        *ret_switch_root_init = NULL;
 
                        return objective;
 
                case MANAGER_EXIT:
                        if (MANAGER_IS_USER(m)) {
                                log_debug("Exit.");
 
                                *ret_retval = m->return_value;
                                *ret_fds = NULL;
                                *ret_switch_root_dir = *ret_switch_root_init = NULL;
 
                                return objective;
                        }
 
                        _fallthrough_;
                case MANAGER_REBOOT:
                case MANAGER_POWEROFF:
                case MANAGER_HALT:
                case MANAGER_KEXEC: {
                        log_notice("Shutting down.");
 
                        *ret_retval = m->return_value;
                        *ret_fds = NULL;
                        *ret_switch_root_dir = *ret_switch_root_init = NULL;
 
                        return objective;
                }
 
                default:
                        assert_not_reached();
                }
        }
}
 
static void log_execution_mode(bool *ret_first_boot) {
        bool first_boot = false;
        int r;
 
        assert(ret_first_boot);
 
        switch (arg_runtime_scope) {
 
        case RUNTIME_SCOPE_SYSTEM: {
                struct utsname uts;
                int v;
 
                log_info("systemd " GIT_VERSION " running in %ssystem mode (%s)",
                         arg_action == ACTION_TEST ? "test " : "",
                         systemd_features);
 
                v = detect_virtualization();
                if (v > 0)
                        log_info("Detected virtualization %s.", virtualization_to_string(v));
 
                v = detect_confidential_virtualization();
                if (v > 0)
                        log_info("Detected confidential virtualization %s.", confidential_virtualization_to_string(v));
 
                log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
 
                if (in_initrd())
                        log_info("Running in initrd.");
                else {
                        _cleanup_free_ char *id_text = NULL;
 
                        /* Let's check whether we are in first boot. First, check if an override was
                         * specified on the kernel command line. If yes, we honour that. */
 
                        r = proc_cmdline_get_bool("systemd.condition_first_boot", /* flags= */ 0, &first_boot);
                        if (r < 0)
                                log_debug_errno(r, "Failed to parse systemd.condition_first_boot= kernel command line argument, ignoring: %m");
 
                        if (r > 0)
                                log_full(first_boot ? LOG_INFO : LOG_DEBUG,
                                         "Kernel command line argument says we are %s first boot.",
                                         first_boot ? "in" : "not in");
                        else {
                                /* Second, perform autodetection. We use /etc/machine-id as flag file for
                                 * this: If it is missing or contains the value "uninitialized", this is the
                                 * first boot. In other cases, it is not. This allows container managers and
                                 * installers to provision a couple of files in /etc but still permit the
                                 * first-boot initialization to occur. If the container manager wants to
                                 * provision the machine ID it should pass $container_uuid to PID 1. */
 
                                r = read_one_line_file("/etc/machine-id", &id_text);
                                if (r < 0 || streq(id_text, "uninitialized")) {
                                        if (r < 0 && r != -ENOENT)
                                                log_warning_errno(r, "Unexpected error while reading /etc/machine-id, assuming first boot: %m");
 
                                        first_boot = true;
                                        log_info("Detected first boot.");
                                } else
                                        log_debug("Detected initialized system, this is not the first boot.");
                        }
                }
 
                /* Make the first-boot file visible now: the credential import
                 * consults in_first_boot() for systemd.credentials_boot_policy= which runs
                 * before the manager object is created. */
                (void) update_first_boot_file(first_boot);
 
                assert_se(uname(&uts) >= 0);
 
                if (strverscmp_improved(uts.release, KERNEL_BASELINE_VERSION) < 0)
                        log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
                                    "Your mileage may vary.", uts.release, KERNEL_BASELINE_VERSION);
                else
                        log_debug("Kernel version %s, our baseline is %s", uts.release, KERNEL_BASELINE_VERSION);
 
                break;
        }
 
        case RUNTIME_SCOPE_USER:
                if (DEBUG_LOGGING) {
                        _cleanup_free_ char *t = NULL;
 
                        t = uid_to_name(getuid());
                        log_debug("systemd " GIT_VERSION " running in %suser mode for user " UID_FMT "/%s. (%s)",
                                  arg_action == ACTION_TEST ? " test" : "",
                                  getuid(), strna(t), systemd_features);
                }
 
                break;
 
        default:
                assert_not_reached();
        }
 
        *ret_first_boot = first_boot;
}
 
static int initialize_runtime(
                bool skip_setup,
                bool first_boot,
                struct rlimit *saved_rlimit_nofile,
                struct rlimit *saved_rlimit_memlock,
                uint64_t *saved_ambient_set,
                const char **ret_error_message) {
 
        int r;
 
        assert(saved_ambient_set);
        assert(ret_error_message);
 
        /* Sets up various runtime parameters. Many of these initializations are conditionalized:
         *
         * - Some only apply to --system instances
         * - Some only apply to --user instances
         * - Some only apply when we first start up, but not when we reexecute
         */
 
        if (arg_action != ACTION_RUN)
                return 0;
 
        update_cpu_affinity(skip_setup);
        update_numa_policy(skip_setup);
 
        switch (arg_runtime_scope) {
 
        case RUNTIME_SCOPE_SYSTEM:
                /* Make sure we leave a core dump without panicking the kernel. */
                install_crash_handler();
 
                if (!skip_setup) {
                        /* Check that /usr/ is either on the same file system as / or mounted already. */
                        if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ true) > 0) {
                                *ret_error_message = "Refusing to run in unsupported environment where /usr/ is not populated";
                                return -ENOEXEC;
                        }
 
                        /* Pull credentials from various sources into a common credential directory (we do
                         * this here, before setting up the machine ID, so that we can use credential info
                         * for setting up the machine ID) */
                        (void) import_credentials();
 
                        (void) os_release_status();
                        (void) machine_id_setup(/* root= */ NULL, arg_machine_id,
                                                (first_boot ? MACHINE_ID_SETUP_FORCE_TRANSIENT : 0) |
                                                (arg_machine_id_from_firmware ? MACHINE_ID_SETUP_FORCE_FIRMWARE : 0),
                                                /* ret= */ NULL);
                        (void) hostname_setup(/* really= */ true);
                        (void) loopback_setup();
 
                        bump_unix_max_dgram_qlen();
                        bump_file_max_and_nr_open();
 
                        write_container_id();
 
                        (void) write_boot_or_shutdown_osc("boot");
 
                        /* Copy os-release to the propagate directory, so that we update it for services running
                         * under RootDirectory=/RootImage= when we do a soft reboot. */
                        r = setup_os_release(RUNTIME_SCOPE_SYSTEM);
                        if (r < 0)
                                log_warning_errno(r, "Failed to copy os-release for propagation, ignoring: %m");
                }
 
                r = watchdog_set_device(arg_watchdog_device);
                if (r < 0)
                        log_warning_errno(r, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device);
 
                if (!cap_test_all(arg_capability_bounding_set)) {
                        r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
                        if (r < 0) {
                                *ret_error_message = "Failed to drop capability bounding set of usermode helpers";
                                return log_struct_errno(LOG_EMERG, r,
                                                        LOG_MESSAGE("Failed to drop capability bounding set of usermode helpers: %m"),
                                                        LOG_MESSAGE_ID(SD_MESSAGE_CORE_CAPABILITY_BOUNDING_USER_STR));
                        }
 
                        r = capability_bounding_set_drop(arg_capability_bounding_set, true);
                        if (r < 0) {
                                *ret_error_message = "Failed to drop capability bounding set";
                                return log_struct_errno(LOG_EMERG, r,
                                                        LOG_MESSAGE("Failed to drop capability bounding set: %m"),
                                                        LOG_MESSAGE_ID(SD_MESSAGE_CORE_CAPABILITY_BOUNDING_STR));
                        }
                }
 
                if (arg_no_new_privs) {
                        r = proc_set_nnp();
                        if (r < 0) {
                                *ret_error_message = "Failed to disable new privileges";
                                return log_struct_errno(LOG_EMERG, r,
                                                        LOG_MESSAGE("Failed to disable new privileges: %m"),
                                                        LOG_MESSAGE_ID(SD_MESSAGE_CORE_DISABLE_PRIVILEGES_STR));
                        }
                }
 
                break;
 
        case RUNTIME_SCOPE_USER: {
                _cleanup_free_ char *p = NULL;
 
                /* Create the runtime directory and place the inaccessible device nodes there, if we run in
                 * user mode. In system mode mount_setup() already did that. */
 
                r = xdg_user_runtime_dir("/systemd", &p);
                if (r < 0) {
                        *ret_error_message = "$XDG_RUNTIME_DIR is not set";
                        return log_struct_errno(LOG_EMERG, r,
                                                LOG_MESSAGE("Failed to determine $XDG_RUNTIME_DIR path: %m"),
                                                LOG_MESSAGE_ID(SD_MESSAGE_CORE_NO_XDGDIR_PATH_STR));
                }
 
                if (!skip_setup) {
                        (void) mkdir_p_label(p, 0755);
                        (void) make_inaccessible_nodes(p, UID_INVALID, GID_INVALID);
 
                        r = setup_os_release(RUNTIME_SCOPE_USER);
                        if (r < 0)
                                log_warning_errno(r, "Failed to copy os-release for propagation, ignoring: %m");
                }
 
                break;
        }
 
        default:
                assert_not_reached();
        }
 
        /* The two operations on the ambient set are meant for a user serssion manager. They do not affect
         * system manager operation, because by default it starts with an empty ambient set.
         *
         * Preserve the ambient set for later use with sd-executor processes. */
        r = capability_get_ambient(saved_ambient_set);
        if (r < 0)
                log_warning_errno(r, "Failed to save ambient capabilities, ignoring: %m");
 
        /* Clear ambient capabilities, so services do not inherit them implicitly. Dropping them does
         * not affect the permitted and effective sets which are important for the manager itself to
         * operate. */
        r = capability_ambient_set_apply(0, /* also_inherit= */ false);
        if (r < 0)
                log_warning_errno(r, "Failed to reset ambient capability set, ignoring: %m");
 
        if (arg_timer_slack_nsec != NSEC_INFINITY) {
                r = prctl_safe(PR_SET_TIMERSLACK, arg_timer_slack_nsec, 0, 0, 0);
                if (r < 0)
                        log_warning_errno(r, "Failed to adjust timer slack, ignoring: %m");
        }
 
        if (arg_syscall_archs) {
                r = enforce_syscall_archs(arg_syscall_archs);
                if (r < 0) {
                        *ret_error_message = "Failed to set syscall architectures";
                        return r;
                }
        }
 
        r = make_reaper_process(true);
        if (r < 0)
                log_warning_errno(r, "Failed to make us a subreaper, ignoring: %m");
 
        /* Bump up RLIMIT_NOFILE for systemd itself */
        (void) bump_rlimit_nofile(saved_rlimit_nofile);
        (void) bump_rlimit_memlock(saved_rlimit_memlock);
 
        return 0;
}
 
static int do_queue_default_job(
                Manager *m,
                const char **ret_error_message) {
 
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        const char *unit;
        Job *job;
        Unit *target;
        int r;
 
        assert(ret_error_message);
 
        if (arg_default_unit)
                unit = arg_default_unit;
        else if (in_initrd())
                unit = SPECIAL_INITRD_TARGET;
        else
                unit = SPECIAL_DEFAULT_TARGET;
 
        /* When no unit was explicitly requested, failures to load the default unit are not fatal,
         * since we fall back to other targets below. Log them at a lower level in that case. */
        int log_level = arg_default_unit ? LOG_ERR : LOG_INFO;
 
        log_debug("Activating default unit: %s", unit);
        r = manager_load_startable_unit_or_warn(m, unit, /* path= */ NULL, log_level, &target);
        if (r == -ENOENT && !arg_default_unit) {
                if (in_initrd())
                        /* Fall back to default.target, which we used to always use by default.
                         * Only do this if no explicit configuration was given. */
                        unit = SPECIAL_DEFAULT_TARGET;
                else
                        /* The default.target symlink was not found on disk and the target was not
                         * explicitly specified. Fall back to the target configured at build time
                         * via -Ddefault-target=. */
                        unit = FALLBACK_DEFAULT_TARGET;
 
                log_info("Falling back to %s.", unit);
                r = manager_load_startable_unit_or_warn(m, unit, /* path= */ NULL, log_level, &target);
        }
        if (r < 0) {
                /* We failed. Activate rescue mode. */
                log_info("Falling back to %s.", SPECIAL_RESCUE_TARGET);
 
                r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, /* path= */ NULL, log_level, &target);
                if (r < 0) {
                        *ret_error_message = r == -ERFKILL ? SPECIAL_RESCUE_TARGET " masked"
                                                           : "Failed to load " SPECIAL_RESCUE_TARGET;
                        return r;
                }
        }
 
        assert(target->load_state == UNIT_LOADED);
 
        r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, &error, &job);
        if (r == -EPERM) {
                log_debug_errno(r, "Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
 
                sd_bus_error_free(&error);
 
                r = manager_add_job(m, JOB_START, target, JOB_REPLACE, &error, &job);
                if (r < 0) {
                        *ret_error_message = "Failed to start default target";
                        return log_struct_errno(LOG_EMERG, r,
                                                LOG_MESSAGE("Failed to start default target: %s", bus_error_message(&error, r)),
                                                LOG_MESSAGE_ID(SD_MESSAGE_CORE_START_TARGET_FAILED_STR));
                }
 
        } else if (r < 0) {
                *ret_error_message = "Failed to isolate default target";
                return log_struct_errno(LOG_EMERG, r,
                                        LOG_MESSAGE("Failed to isolate default target: %s", bus_error_message(&error, r)),
                                        LOG_MESSAGE_ID(SD_MESSAGE_CORE_ISOLATE_TARGET_FAILED_STR));
        }
 
        log_info("Queued %s job for default target %s.",
                 job_type_to_string(job->type), unit_status_string(job->unit, NULL));
 
        return 0;
}
 
static void save_rlimits(struct rlimit *saved_rlimit_nofile,
                         struct rlimit *saved_rlimit_memlock) {
 
        assert(saved_rlimit_nofile);
        assert(saved_rlimit_memlock);
 
        if (getrlimit(RLIMIT_NOFILE, saved_rlimit_nofile) < 0)
                log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
 
        if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock) < 0)
                log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
}
 
static void fallback_rlimit_nofile(const struct rlimit *saved_rlimit_nofile) {
        struct rlimit *rl;
 
        if (arg_defaults.rlimit[RLIMIT_NOFILE])
                return;
 
        /* Make sure forked processes get limits based on the original kernel setting */
 
        rl = newdup(struct rlimit, saved_rlimit_nofile, 1);
        if (!rl) {
                log_oom();
                return;
        }
 
        /* Bump the hard limit for system services to a substantially higher value. The default
         * hard limit current kernels set is pretty low (4K), mostly for historical
         * reasons. According to kernel developers, the fd handling in recent kernels has been
         * optimized substantially enough, so that we can bump the limit now, without paying too
         * high a price in memory or performance. Note however that we only bump the hard limit,
         * not the soft limit. That's because select() works the way it works, and chokes on fds
         * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
         * unexpecting programs that they get fds higher than what they can process using
         * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
         * this pitfall:  programs that are written by folks aware of the select() problem in mind
         * (and thus use poll()/epoll instead of select(), the way everybody should) can
         * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
         * we pass. */
        if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM)
                rl->rlim_max = MIN((rlim_t) read_nr_open(), MAX(rl->rlim_max, (rlim_t) HIGH_RLIMIT_NOFILE));
 
        /* If for some reason we were invoked with a soft limit above 1024 (which should never
         * happen!, but who knows what we get passed in from pam_limit when invoked as --user
         * instance), then lower what we pass on to not confuse our children */
        rl->rlim_cur = MIN(rl->rlim_cur, (rlim_t) FD_SETSIZE);
 
        arg_defaults.rlimit[RLIMIT_NOFILE] = rl;
}
 
static void fallback_rlimit_memlock(const struct rlimit *saved_rlimit_memlock) {
        struct rlimit *rl;
 
        /* Pass the original value down to invoked processes */
 
        if (arg_defaults.rlimit[RLIMIT_MEMLOCK])
                return;
 
        rl = newdup(struct rlimit, saved_rlimit_memlock, 1);
        if (!rl) {
                log_oom();
                return;
        }
 
        if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM)  {
                /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
                 * default for this since kernel 5.16) */
                rl->rlim_max = MAX(rl->rlim_max, (rlim_t) DEFAULT_RLIMIT_MEMLOCK);
                rl->rlim_cur = MAX(rl->rlim_cur, (rlim_t) DEFAULT_RLIMIT_MEMLOCK);
        }
 
        arg_defaults.rlimit[RLIMIT_MEMLOCK] = rl;
}
 
static void setenv_manager_environment(void) {
        int r;
 
        STRV_FOREACH(p, arg_manager_environment) {
                log_debug("Setting '%s' in our own environment.", *p);
 
                r = putenv_dup(*p, true);
                if (r < 0)
                        log_warning_errno(r, "Failed to setenv \"%s\", ignoring: %m", *p);
        }
}
 
static void reset_arguments(void) {
        /* Frees/resets arg_* variables, with a few exceptions commented below. */
 
        arg_default_unit = mfree(arg_default_unit);
 
        /* arg_runtime_scope — ignore */
 
        arg_dump_core = true;
        arg_crash_chvt = -1;
        arg_crash_shell = false;
        arg_crash_action = CRASH_FREEZE;
        arg_confirm_spawn = mfree(arg_confirm_spawn);
        arg_show_status = _SHOW_STATUS_INVALID;
        arg_status_unit_format = STATUS_UNIT_FORMAT_DEFAULT;
        arg_switched_root = false;
        arg_pager_flags = 0;
        arg_service_watchdogs = true;
 
        unit_defaults_done(&arg_defaults);
        unit_defaults_init(&arg_defaults, arg_runtime_scope);
 
        arg_runtime_watchdog = 0;