1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include <sys/utsname.h>
14 #if HAVE_VALGRIND_VALGRIND_H
15 # include <valgrind/valgrind.h>
19 #include "sd-daemon.h"
20 #include "sd-messages.h"
22 #include "alloc-util.h"
23 #include "apparmor-setup.h"
24 #include "architecture.h"
25 #include "argv-util.h"
30 #include "bus-error.h"
32 #include "capability-util.h"
33 #include "cgroup-util.h"
35 #include "clock-util.h"
36 #include "conf-parser.h"
37 #include "confidential-virt.h"
39 #include "cpu-set-util.h"
40 #include "crash-handler.h"
41 #include "dbus-manager.h"
43 #include "constants.h"
44 #include "dev-setup.h"
45 #include "efi-random.h"
47 #include "emergency-action.h"
49 #include "exit-status.h"
53 #include "format-util.h"
55 #include "getopt-defs.h"
56 #include "hexdecoct.h"
57 #include "hostname-setup.h"
58 #include "ima-setup.h"
59 #include "import-creds.h"
60 #include "initrd-util.h"
62 #include "kmod-setup.h"
63 #include "limits-util.h"
64 #include "load-fragment.h"
66 #include "loopback-setup.h"
67 #include "machine-id-setup.h"
70 #include "manager-dump.h"
71 #include "manager-serialize.h"
72 #include "mkdir-label.h"
73 #include "mount-setup.h"
76 #include "parse-argument.h"
77 #include "parse-util.h"
78 #include "path-util.h"
79 #include "pretty-print.h"
80 #include "proc-cmdline.h"
81 #include "process-util.h"
83 #include "random-util.h"
84 #include "rlimit-util.h"
86 #include "seccomp-util.h"
88 #include "selinux-setup.h"
89 #include "selinux-util.h"
90 #include "signal-util.h"
91 #include "smack-setup.h"
93 #include "stat-util.h"
94 #include "stdio-util.h"
96 #include "switch-root.h"
97 #include "sysctl-util.h"
98 #include "terminal-util.h"
99 #include "time-util.h"
100 #include "umask-util.h"
101 #include "user-util.h"
103 #include "watchdog.h"
105 #if HAS_FEATURE_ADDRESS_SANITIZER
106 #include <sanitizer/lsan_interface.h>
109 #define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
116 ACTION_DUMP_CONFIGURATION_ITEMS
,
117 ACTION_DUMP_BUS_PROPERTIES
,
118 ACTION_BUS_INTROSPECT
,
119 } arg_action
= ACTION_RUN
;
121 static const char *arg_bus_introspect
= NULL
;
123 /* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
124 * defaults are assigned in reset_arguments() below. */
125 static char *arg_default_unit
;
126 static RuntimeScope arg_runtime_scope
;
129 bool arg_crash_shell
;
130 bool arg_crash_reboot
;
131 static char *arg_confirm_spawn
;
132 static ShowStatus arg_show_status
;
133 static StatusUnitFormat arg_status_unit_format
;
134 static bool arg_switched_root
;
135 static PagerFlags arg_pager_flags
;
136 static bool arg_service_watchdogs
;
137 static ExecOutput arg_default_std_output
;
138 static ExecOutput arg_default_std_error
;
139 static usec_t arg_default_restart_usec
;
140 static usec_t arg_default_timeout_start_usec
;
141 static usec_t arg_default_timeout_stop_usec
;
142 static usec_t arg_default_timeout_abort_usec
;
143 static usec_t arg_default_device_timeout_usec
;
144 static bool arg_default_timeout_abort_set
;
145 static usec_t arg_default_start_limit_interval
;
146 static unsigned arg_default_start_limit_burst
;
147 static usec_t arg_runtime_watchdog
;
148 static usec_t arg_reboot_watchdog
;
149 static usec_t arg_kexec_watchdog
;
150 static usec_t arg_pretimeout_watchdog
;
151 static char *arg_early_core_pattern
;
152 static char *arg_watchdog_pretimeout_governor
;
153 static char *arg_watchdog_device
;
154 static char **arg_default_environment
;
155 static char **arg_manager_environment
;
156 static struct rlimit
*arg_default_rlimit
[_RLIMIT_MAX
];
157 static uint64_t arg_capability_bounding_set
;
158 static bool arg_no_new_privs
;
159 static nsec_t arg_timer_slack_nsec
;
160 static usec_t arg_default_timer_accuracy_usec
;
161 static Set
* arg_syscall_archs
;
162 static FILE* arg_serialization
;
163 static int arg_default_cpu_accounting
;
164 static bool arg_default_io_accounting
;
165 static bool arg_default_ip_accounting
;
166 static bool arg_default_blockio_accounting
;
167 static bool arg_default_memory_accounting
;
168 static bool arg_default_tasks_accounting
;
169 static TasksMax arg_default_tasks_max
;
170 static usec_t arg_default_memory_pressure_threshold_usec
;
171 static CGroupPressureWatch arg_default_memory_pressure_watch
;
172 static sd_id128_t arg_machine_id
;
173 static EmergencyAction arg_cad_burst_action
;
174 static OOMPolicy arg_default_oom_policy
;
175 static CPUSet arg_cpu_affinity
;
176 static NUMAPolicy arg_numa_policy
;
177 static usec_t arg_clock_usec
;
178 static void *arg_random_seed
;
179 static size_t arg_random_seed_size
;
180 static int arg_default_oom_score_adjust
;
181 static bool arg_default_oom_score_adjust_set
;
182 static char *arg_default_smack_process_label
;
183 static usec_t arg_reload_limit_interval_sec
;
184 static unsigned arg_reload_limit_burst
;
186 /* A copy of the original environment block */
187 static char **saved_env
= NULL
;
189 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
190 const struct rlimit
*saved_rlimit_memlock
);
192 static int manager_find_user_config_paths(char ***ret_files
, char ***ret_dirs
) {
193 _cleanup_free_
char *base
= NULL
;
194 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
197 r
= xdg_user_config_dir(&base
, "/systemd");
201 r
= strv_extendf(&files
, "%s/user.conf", base
);
205 r
= strv_extend(&files
, PKGSYSCONFDIR
"/user.conf");
209 r
= strv_consume(&dirs
, TAKE_PTR(base
));
213 r
= strv_extend_strv(&dirs
, CONF_PATHS_STRV("systemd"), false);
217 *ret_files
= TAKE_PTR(files
);
218 *ret_dirs
= TAKE_PTR(dirs
);
222 static int console_setup(void) {
223 _cleanup_close_
int tty_fd
= -EBADF
;
227 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
229 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
231 /* We don't want to force text mode. plymouth may be showing
232 * pictures already from initrd. */
233 r
= reset_terminal_fd(tty_fd
, false);
235 return log_error_errno(r
, "Failed to reset /dev/console: %m");
237 r
= proc_cmdline_tty_size("/dev/console", &rows
, &cols
);
239 log_warning_errno(r
, "Failed to get terminal size, ignoring: %m");
241 r
= terminal_set_size_fd(tty_fd
, NULL
, rows
, cols
);
243 log_warning_errno(r
, "Failed to set terminal size, ignoring: %m");
249 static int set_machine_id(const char *m
) {
253 if (sd_id128_from_string(m
, &t
) < 0)
256 if (sd_id128_is_null(t
))
263 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
268 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
270 if (proc_cmdline_value_missing(key
, value
))
273 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
274 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
275 else if (in_initrd() == !!startswith(key
, "rd."))
276 return free_and_strdup_warn(&arg_default_unit
, value
);
278 } else if (proc_cmdline_key_streq(key
, "systemd.dump_core")) {
280 r
= value
? parse_boolean(value
) : true;
282 log_warning_errno(r
, "Failed to parse dump core switch %s, ignoring: %m", value
);
286 } else if (proc_cmdline_key_streq(key
, "systemd.early_core_pattern")) {
288 if (proc_cmdline_value_missing(key
, value
))
291 if (path_is_absolute(value
))
292 (void) parse_path_argument(value
, false, &arg_early_core_pattern
);
294 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value
);
296 } else if (proc_cmdline_key_streq(key
, "systemd.crash_chvt")) {
299 arg_crash_chvt
= 0; /* turn on */
301 r
= parse_crash_chvt(value
, &arg_crash_chvt
);
303 log_warning_errno(r
, "Failed to parse crash chvt switch %s, ignoring: %m", value
);
306 } else if (proc_cmdline_key_streq(key
, "systemd.crash_shell")) {
308 r
= value
? parse_boolean(value
) : true;
310 log_warning_errno(r
, "Failed to parse crash shell switch %s, ignoring: %m", value
);
314 } else if (proc_cmdline_key_streq(key
, "systemd.crash_reboot")) {
316 r
= value
? parse_boolean(value
) : true;
318 log_warning_errno(r
, "Failed to parse crash reboot switch %s, ignoring: %m", value
);
320 arg_crash_reboot
= r
;
322 } else if (proc_cmdline_key_streq(key
, "systemd.confirm_spawn")) {
325 r
= parse_confirm_spawn(value
, &s
);
327 log_warning_errno(r
, "Failed to parse confirm_spawn switch %s, ignoring: %m", value
);
329 free_and_replace(arg_confirm_spawn
, s
);
331 } else if (proc_cmdline_key_streq(key
, "systemd.service_watchdogs")) {
333 r
= value
? parse_boolean(value
) : true;
335 log_warning_errno(r
, "Failed to parse service watchdog switch %s, ignoring: %m", value
);
337 arg_service_watchdogs
= r
;
339 } else if (proc_cmdline_key_streq(key
, "systemd.show_status")) {
342 r
= parse_show_status(value
, &arg_show_status
);
344 log_warning_errno(r
, "Failed to parse show status switch %s, ignoring: %m", value
);
346 arg_show_status
= SHOW_STATUS_YES
;
348 } else if (proc_cmdline_key_streq(key
, "systemd.status_unit_format")) {
350 if (proc_cmdline_value_missing(key
, value
))
353 r
= status_unit_format_from_string(value
);
355 log_warning_errno(r
, "Failed to parse %s=%s, ignoring: %m", key
, value
);
357 arg_status_unit_format
= r
;
359 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_output")) {
361 if (proc_cmdline_value_missing(key
, value
))
364 r
= exec_output_from_string(value
);
366 log_warning_errno(r
, "Failed to parse default standard output switch %s, ignoring: %m", value
);
368 arg_default_std_output
= r
;
370 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_error")) {
372 if (proc_cmdline_value_missing(key
, value
))
375 r
= exec_output_from_string(value
);
377 log_warning_errno(r
, "Failed to parse default standard error switch %s, ignoring: %m", value
);
379 arg_default_std_error
= r
;
381 } else if (streq(key
, "systemd.setenv")) {
383 if (proc_cmdline_value_missing(key
, value
))
386 if (!env_assignment_is_valid(value
))
387 log_warning("Environment variable assignment '%s' is not valid. Ignoring.", value
);
389 r
= strv_env_replace_strdup(&arg_default_environment
, value
);
394 } else if (proc_cmdline_key_streq(key
, "systemd.machine_id")) {
396 if (proc_cmdline_value_missing(key
, value
))
399 r
= set_machine_id(value
);
401 log_warning_errno(r
, "MachineID '%s' is not valid, ignoring: %m", value
);
403 } else if (proc_cmdline_key_streq(key
, "systemd.default_timeout_start_sec")) {
405 if (proc_cmdline_value_missing(key
, value
))
408 r
= parse_sec(value
, &arg_default_timeout_start_usec
);
410 log_warning_errno(r
, "Failed to parse default start timeout '%s', ignoring: %m", value
);
412 if (arg_default_timeout_start_usec
<= 0)
413 arg_default_timeout_start_usec
= USEC_INFINITY
;
415 } else if (proc_cmdline_key_streq(key
, "systemd.default_device_timeout_sec")) {
417 if (proc_cmdline_value_missing(key
, value
))
420 r
= parse_sec(value
, &arg_default_device_timeout_usec
);
422 log_warning_errno(r
, "Failed to parse default device timeout '%s', ignoring: %m", value
);
424 if (arg_default_device_timeout_usec
<= 0)
425 arg_default_device_timeout_usec
= USEC_INFINITY
;
427 } else if (proc_cmdline_key_streq(key
, "systemd.cpu_affinity")) {
429 if (proc_cmdline_value_missing(key
, value
))
432 r
= parse_cpu_set(value
, &arg_cpu_affinity
);
434 log_warning_errno(r
, "Failed to parse CPU affinity mask '%s', ignoring: %m", value
);
436 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_device")) {
438 if (proc_cmdline_value_missing(key
, value
))
441 (void) parse_path_argument(value
, false, &arg_watchdog_device
);
443 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_sec")) {
445 if (proc_cmdline_value_missing(key
, value
))
448 if (streq(value
, "default"))
449 arg_runtime_watchdog
= USEC_INFINITY
;
450 else if (streq(value
, "off"))
451 arg_runtime_watchdog
= 0;
453 r
= parse_sec(value
, &arg_runtime_watchdog
);
455 log_warning_errno(r
, "Failed to parse systemd.watchdog_sec= argument '%s', ignoring: %m", value
);
460 arg_kexec_watchdog
= arg_reboot_watchdog
= arg_runtime_watchdog
;
462 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pre_sec")) {
464 if (proc_cmdline_value_missing(key
, value
))
467 if (streq(value
, "default"))
468 arg_pretimeout_watchdog
= USEC_INFINITY
;
469 else if (streq(value
, "off"))
470 arg_pretimeout_watchdog
= 0;
472 r
= parse_sec(value
, &arg_pretimeout_watchdog
);
474 log_warning_errno(r
, "Failed to parse systemd.watchdog_pre_sec= argument '%s', ignoring: %m", value
);
479 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pretimeout_governor")) {
481 if (proc_cmdline_value_missing(key
, value
) || isempty(value
)) {
482 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
486 if (!string_is_safe(value
)) {
487 log_warning("Watchdog pretimeout governor '%s' is not valid, ignoring.", value
);
491 return free_and_strdup_warn(&arg_watchdog_pretimeout_governor
, value
);
493 } else if (proc_cmdline_key_streq(key
, "systemd.clock_usec")) {
495 if (proc_cmdline_value_missing(key
, value
))
498 r
= safe_atou64(value
, &arg_clock_usec
);
500 log_warning_errno(r
, "Failed to parse systemd.clock_usec= argument, ignoring: %s", value
);
502 } else if (proc_cmdline_key_streq(key
, "systemd.random_seed")) {
506 if (proc_cmdline_value_missing(key
, value
))
509 r
= unbase64mem(value
, SIZE_MAX
, &p
, &sz
);
511 log_warning_errno(r
, "Failed to parse systemd.random_seed= argument, ignoring: %s", value
);
513 free(arg_random_seed
);
514 arg_random_seed
= sz
> 0 ? p
: mfree(p
);
515 arg_random_seed_size
= sz
;
517 } else if (proc_cmdline_key_streq(key
, "systemd.reload_limit_interval_sec")) {
519 if (proc_cmdline_value_missing(key
, value
))
522 r
= parse_sec(value
, &arg_reload_limit_interval_sec
);
524 log_warning_errno(r
, "Failed to parse systemd.reload_limit_interval_sec= argument '%s', ignoring: %m", value
);
528 } else if (proc_cmdline_key_streq(key
, "systemd.reload_limit_burst")) {
530 if (proc_cmdline_value_missing(key
, value
))
533 r
= safe_atou(value
, &arg_reload_limit_burst
);
535 log_warning_errno(r
, "Failed to parse systemd.reload_limit_burst= argument '%s', ignoring: %m", value
);
539 } else if (streq(key
, "quiet") && !value
) {
541 if (arg_show_status
== _SHOW_STATUS_INVALID
)
542 arg_show_status
= SHOW_STATUS_ERROR
;
544 } else if (streq(key
, "debug") && !value
) {
546 /* Note that log_parse_environment() handles 'debug'
547 * too, and sets the log level to LOG_DEBUG. */
549 if (detect_container() > 0)
550 log_set_target(LOG_TARGET_CONSOLE
);
555 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
556 target
= runlevel_to_target(key
);
558 return free_and_strdup_warn(&arg_default_unit
, target
);
564 #define DEFINE_SETTER(name, func, descr) \
565 static int name(const char *unit, \
566 const char *filename, \
568 const char *section, \
569 unsigned section_line, \
570 const char *lvalue, \
572 const char *rvalue, \
584 log_syntax(unit, LOG_ERR, filename, line, r, \
585 "Invalid " descr "'%s': %m", \
591 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level");
592 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target");
593 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color");
594 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location");
595 DEFINE_SETTER(config_parse_time
, log_show_time_from_string
, "time");
597 static int config_parse_default_timeout_abort(
599 const char *filename
,
602 unsigned section_line
,
610 r
= config_parse_timeout_abort(unit
, filename
, line
, section
, section_line
, lvalue
, ltype
, rvalue
,
611 &arg_default_timeout_abort_usec
, userdata
);
613 arg_default_timeout_abort_set
= r
;
617 static int config_parse_oom_score_adjust(
619 const char *filename
,
622 unsigned section_line
,
631 if (isempty(rvalue
)) {
632 arg_default_oom_score_adjust_set
= false;
636 r
= parse_oom_score_adjust(rvalue
, &oa
);
638 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse the OOM score adjust value '%s', ignoring: %m", rvalue
);
642 arg_default_oom_score_adjust
= oa
;
643 arg_default_oom_score_adjust_set
= true;
648 static int parse_config_file(void) {
649 const ConfigTableItem items
[] = {
650 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
651 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
652 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
653 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
654 { "Manager", "LogTime", config_parse_time
, 0, NULL
},
655 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
656 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, &arg_crash_chvt
},
657 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, &arg_crash_chvt
},
658 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
659 { "Manager", "CrashReboot", config_parse_bool
, 0, &arg_crash_reboot
},
660 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
661 { "Manager", "StatusUnitFormat", config_parse_status_unit_format
, 0, &arg_status_unit_format
},
662 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, &arg_cpu_affinity
},
663 { "Manager", "NUMAPolicy", config_parse_numa_policy
, 0, &arg_numa_policy
.type
},
664 { "Manager", "NUMAMask", config_parse_numa_mask
, 0, &arg_numa_policy
},
665 { "Manager", "JoinControllers", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
666 { "Manager", "RuntimeWatchdogSec", config_parse_watchdog_sec
, 0, &arg_runtime_watchdog
},
667 { "Manager", "RuntimeWatchdogPreSec", config_parse_watchdog_sec
, 0, &arg_pretimeout_watchdog
},
668 { "Manager", "RebootWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
},
669 { "Manager", "ShutdownWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
}, /* obsolete alias */
670 { "Manager", "KExecWatchdogSec", config_parse_watchdog_sec
, 0, &arg_kexec_watchdog
},
671 { "Manager", "WatchdogDevice", config_parse_path
, 0, &arg_watchdog_device
},
672 { "Manager", "RuntimeWatchdogPreGovernor", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &arg_watchdog_pretimeout_governor
},
673 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
674 { "Manager", "NoNewPrivileges", config_parse_bool
, 0, &arg_no_new_privs
},
676 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
678 { "Manager", "SystemCallArchitectures", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
681 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
682 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_default_timer_accuracy_usec
},
683 { "Manager", "DefaultStandardOutput", config_parse_output_restricted
, 0, &arg_default_std_output
},
684 { "Manager", "DefaultStandardError", config_parse_output_restricted
, 0, &arg_default_std_error
},
685 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_default_timeout_start_usec
},
686 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_default_timeout_stop_usec
},
687 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort
, 0, NULL
},
688 { "Manager", "DefaultDeviceTimeoutSec", config_parse_sec
, 0, &arg_default_device_timeout_usec
},
689 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_default_restart_usec
},
690 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_default_start_limit_interval
}, /* obsolete alias */
691 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec
, 0, &arg_default_start_limit_interval
},
692 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_default_start_limit_burst
},
693 { "Manager", "DefaultEnvironment", config_parse_environ
, arg_runtime_scope
, &arg_default_environment
},
694 { "Manager", "ManagerEnvironment", config_parse_environ
, arg_runtime_scope
, &arg_manager_environment
},
695 { "Manager", "DefaultLimitCPU", config_parse_rlimit
, RLIMIT_CPU
, arg_default_rlimit
},
696 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit
, RLIMIT_FSIZE
, arg_default_rlimit
},
697 { "Manager", "DefaultLimitDATA", config_parse_rlimit
, RLIMIT_DATA
, arg_default_rlimit
},
698 { "Manager", "DefaultLimitSTACK", config_parse_rlimit
, RLIMIT_STACK
, arg_default_rlimit
},
699 { "Manager", "DefaultLimitCORE", config_parse_rlimit
, RLIMIT_CORE
, arg_default_rlimit
},
700 { "Manager", "DefaultLimitRSS", config_parse_rlimit
, RLIMIT_RSS
, arg_default_rlimit
},
701 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit
, RLIMIT_NOFILE
, arg_default_rlimit
},
702 { "Manager", "DefaultLimitAS", config_parse_rlimit
, RLIMIT_AS
, arg_default_rlimit
},
703 { "Manager", "DefaultLimitNPROC", config_parse_rlimit
, RLIMIT_NPROC
, arg_default_rlimit
},
704 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit
, RLIMIT_MEMLOCK
, arg_default_rlimit
},
705 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit
, RLIMIT_LOCKS
, arg_default_rlimit
},
706 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit
, RLIMIT_SIGPENDING
, arg_default_rlimit
},
707 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit
, RLIMIT_MSGQUEUE
, arg_default_rlimit
},
708 { "Manager", "DefaultLimitNICE", config_parse_rlimit
, RLIMIT_NICE
, arg_default_rlimit
},
709 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit
, RLIMIT_RTPRIO
, arg_default_rlimit
},
710 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit
, RLIMIT_RTTIME
, arg_default_rlimit
},
711 { "Manager", "DefaultCPUAccounting", config_parse_tristate
, 0, &arg_default_cpu_accounting
},
712 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_default_io_accounting
},
713 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_default_ip_accounting
},
714 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_default_blockio_accounting
},
715 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_default_memory_accounting
},
716 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_default_tasks_accounting
},
717 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_default_tasks_max
},
718 { "Manager", "DefaultMemoryPressureThresholdSec", config_parse_sec
, 0, &arg_default_memory_pressure_threshold_usec
},
719 { "Manager", "DefaultMemoryPressureWatch", config_parse_memory_pressure_watch
, 0, &arg_default_memory_pressure_watch
},
720 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, arg_runtime_scope
, &arg_cad_burst_action
},
721 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy
, 0, &arg_default_oom_policy
},
722 { "Manager", "DefaultOOMScoreAdjust", config_parse_oom_score_adjust
, 0, NULL
},
723 { "Manager", "ReloadLimitIntervalSec", config_parse_sec
, 0, &arg_reload_limit_interval_sec
},
724 { "Manager", "ReloadLimitBurst", config_parse_unsigned
, 0, &arg_reload_limit_burst
},
726 { "Manager", "DefaultSmackProcessLabel", config_parse_string
, 0, &arg_default_smack_process_label
},
728 { "Manager", "DefaultSmackProcessLabel", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
733 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
)
734 (void) config_parse_config_file("system.conf",
736 config_item_table_lookup
, items
,
740 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
743 assert(arg_runtime_scope
== RUNTIME_SCOPE_USER
);
745 r
= manager_find_user_config_paths(&files
, &dirs
);
747 return log_error_errno(r
, "Failed to determine config file paths: %m");
749 (void) config_parse_many(
750 (const char* const*) files
,
751 (const char* const*) dirs
,
755 config_item_table_lookup
, items
,
760 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we use
761 * USEC_INFINITY like everywhere else. */
762 if (arg_default_timeout_start_usec
<= 0)
763 arg_default_timeout_start_usec
= USEC_INFINITY
;
764 if (arg_default_timeout_stop_usec
<= 0)
765 arg_default_timeout_stop_usec
= USEC_INFINITY
;
770 static void set_manager_defaults(Manager
*m
) {
774 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
775 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
776 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
778 m
->default_timer_accuracy_usec
= arg_default_timer_accuracy_usec
;
779 m
->default_std_output
= arg_default_std_output
;
780 m
->default_std_error
= arg_default_std_error
;
781 m
->default_timeout_start_usec
= arg_default_timeout_start_usec
;
782 m
->default_timeout_stop_usec
= arg_default_timeout_stop_usec
;
783 m
->default_timeout_abort_usec
= arg_default_timeout_abort_usec
;
784 m
->default_timeout_abort_set
= arg_default_timeout_abort_set
;
785 m
->default_device_timeout_usec
= arg_default_device_timeout_usec
;
786 m
->default_restart_usec
= arg_default_restart_usec
;
787 m
->default_start_limit_interval
= arg_default_start_limit_interval
;
788 m
->default_start_limit_burst
= arg_default_start_limit_burst
;
790 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
791 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
792 if (arg_default_cpu_accounting
>= 0)
793 m
->default_cpu_accounting
= arg_default_cpu_accounting
;
795 m
->default_cpu_accounting
= cpu_accounting_is_cheap();
797 m
->default_io_accounting
= arg_default_io_accounting
;
798 m
->default_ip_accounting
= arg_default_ip_accounting
;
799 m
->default_blockio_accounting
= arg_default_blockio_accounting
;
800 m
->default_memory_accounting
= arg_default_memory_accounting
;
801 m
->default_tasks_accounting
= arg_default_tasks_accounting
;
802 m
->default_tasks_max
= arg_default_tasks_max
;
803 m
->default_memory_pressure_watch
= arg_default_memory_pressure_watch
;
804 m
->default_memory_pressure_threshold_usec
= arg_default_memory_pressure_threshold_usec
;
805 m
->default_oom_policy
= arg_default_oom_policy
;
806 m
->default_oom_score_adjust_set
= arg_default_oom_score_adjust_set
;
807 m
->default_oom_score_adjust
= arg_default_oom_score_adjust
;
809 (void) manager_set_default_smack_process_label(m
, arg_default_smack_process_label
);
811 (void) manager_set_default_rlimits(m
, arg_default_rlimit
);
813 (void) manager_default_environment(m
);
814 (void) manager_transient_environment_add(m
, arg_default_environment
);
817 static void set_manager_settings(Manager
*m
) {
822 /* Propagates the various manager settings into the manager object, i.e. properties that
823 * effect the manager itself (as opposed to just being inherited into newly allocated
824 * units, see set_manager_defaults() above). */
826 m
->confirm_spawn
= arg_confirm_spawn
;
827 m
->service_watchdogs
= arg_service_watchdogs
;
828 m
->cad_burst_action
= arg_cad_burst_action
;
829 /* Note that we don't do structured initialization here, otherwise it will reset the rate limit
830 * counter on every daemon-reload. */
831 m
->reload_ratelimit
.interval
= arg_reload_limit_interval_sec
;
832 m
->reload_ratelimit
.burst
= arg_reload_limit_burst
;
834 manager_set_watchdog(m
, WATCHDOG_RUNTIME
, arg_runtime_watchdog
);
835 manager_set_watchdog(m
, WATCHDOG_REBOOT
, arg_reboot_watchdog
);
836 manager_set_watchdog(m
, WATCHDOG_KEXEC
, arg_kexec_watchdog
);
837 manager_set_watchdog(m
, WATCHDOG_PRETIMEOUT
, arg_pretimeout_watchdog
);
838 r
= manager_set_watchdog_pretimeout_governor(m
, arg_watchdog_pretimeout_governor
);
840 log_warning_errno(r
, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor
);
842 manager_set_show_status(m
, arg_show_status
, "commandline");
843 m
->status_unit_format
= arg_status_unit_format
;
846 static int parse_argv(int argc
, char *argv
[]) {
852 static const struct option options
[] = {
853 COMMON_GETOPT_OPTIONS
,
854 SYSTEMD_GETOPT_OPTIONS
,
859 bool user_arg_seen
= false;
864 if (getpid_cached() == 1)
867 while ((c
= getopt_long(argc
, argv
, SYSTEMD_GETOPT_SHORT_OPTIONS
, options
, NULL
)) >= 0)
872 r
= log_set_max_level_from_string(optarg
);
874 return log_error_errno(r
, "Failed to parse log level \"%s\": %m", optarg
);
879 r
= log_set_target_from_string(optarg
);
881 return log_error_errno(r
, "Failed to parse log target \"%s\": %m", optarg
);
888 r
= log_show_color_from_string(optarg
);
890 return log_error_errno(r
, "Failed to parse log color setting \"%s\": %m",
893 log_show_color(true);
897 case ARG_LOG_LOCATION
:
899 r
= log_show_location_from_string(optarg
);
901 return log_error_errno(r
, "Failed to parse log location setting \"%s\": %m",
904 log_show_location(true);
911 r
= log_show_time_from_string(optarg
);
913 return log_error_errno(r
, "Failed to parse log time setting \"%s\": %m",
920 case ARG_DEFAULT_STD_OUTPUT
:
921 r
= exec_output_from_string(optarg
);
923 return log_error_errno(r
, "Failed to parse default standard output setting \"%s\": %m",
925 arg_default_std_output
= r
;
928 case ARG_DEFAULT_STD_ERROR
:
929 r
= exec_output_from_string(optarg
);
931 return log_error_errno(r
, "Failed to parse default standard error output setting \"%s\": %m",
933 arg_default_std_error
= r
;
937 r
= free_and_strdup(&arg_default_unit
, optarg
);
939 return log_error_errno(r
, "Failed to set default unit \"%s\": %m", optarg
);
944 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
948 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
949 user_arg_seen
= true;
953 arg_action
= ACTION_TEST
;
957 arg_pager_flags
|= PAGER_DISABLE
;
961 arg_action
= ACTION_VERSION
;
964 case ARG_DUMP_CONFIGURATION_ITEMS
:
965 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
968 case ARG_DUMP_BUS_PROPERTIES
:
969 arg_action
= ACTION_DUMP_BUS_PROPERTIES
;
972 case ARG_BUS_INTROSPECT
:
973 arg_bus_introspect
= optarg
;
974 arg_action
= ACTION_BUS_INTROSPECT
;
978 r
= parse_boolean_argument("--dump-core", optarg
, &arg_dump_core
);
984 r
= parse_crash_chvt(optarg
, &arg_crash_chvt
);
986 return log_error_errno(r
, "Failed to parse crash virtual terminal index: \"%s\": %m",
990 case ARG_CRASH_SHELL
:
991 r
= parse_boolean_argument("--crash-shell", optarg
, &arg_crash_shell
);
996 case ARG_CRASH_REBOOT
:
997 r
= parse_boolean_argument("--crash-reboot", optarg
, &arg_crash_reboot
);
1002 case ARG_CONFIRM_SPAWN
:
1003 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
1005 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
1007 return log_error_errno(r
, "Failed to parse confirm spawn option: \"%s\": %m",
1011 case ARG_SERVICE_WATCHDOGS
:
1012 r
= parse_boolean_argument("--service-watchdogs=", optarg
, &arg_service_watchdogs
);
1017 case ARG_SHOW_STATUS
:
1019 r
= parse_show_status(optarg
, &arg_show_status
);
1021 return log_error_errno(r
, "Failed to parse show status boolean: \"%s\": %m",
1024 arg_show_status
= SHOW_STATUS_YES
;
1027 case ARG_DESERIALIZE
: {
1031 fd
= parse_fd(optarg
);
1033 return log_error_errno(fd
, "Failed to parse serialization fd \"%s\": %m", optarg
);
1035 (void) fd_cloexec(fd
, true);
1037 f
= fdopen(fd
, "r");
1039 return log_error_errno(errno
, "Failed to open serialization fd %d: %m", fd
);
1041 safe_fclose(arg_serialization
);
1042 arg_serialization
= f
;
1047 case ARG_SWITCHED_ROOT
:
1048 arg_switched_root
= true;
1051 case ARG_MACHINE_ID
:
1052 r
= set_machine_id(optarg
);
1054 return log_error_errno(r
, "MachineID '%s' is not valid: %m", optarg
);
1058 arg_action
= ACTION_HELP
;
1062 log_set_max_level(LOG_DEBUG
);
1068 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1069 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1072 if (getpid_cached() != 1)
1078 assert_not_reached();
1081 if (optind
< argc
&& getpid_cached() != 1)
1082 /* Hmm, when we aren't run as init system let's complain about excess arguments */
1083 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Excess arguments.");
1085 if (arg_action
== ACTION_RUN
&& arg_runtime_scope
== RUNTIME_SCOPE_USER
&& !user_arg_seen
)
1086 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1087 "Explicit --user argument required to run as user manager.");
1092 static int help(void) {
1093 _cleanup_free_
char *link
= NULL
;
1096 r
= terminal_urlify_man("systemd", "1", &link
);
1100 printf("%s [OPTIONS...]\n\n"
1101 "%sStarts and monitors system and user services.%s\n\n"
1102 "This program takes no positional arguments.\n\n"
1104 " -h --help Show this help\n"
1105 " --version Show version\n"
1106 " --test Determine initial transaction, dump it and exit\n"
1107 " --system Combined with --test: operate in system mode\n"
1108 " --user Combined with --test: operate in user mode\n"
1109 " --dump-configuration-items Dump understood unit configuration items\n"
1110 " --dump-bus-properties Dump exposed bus properties\n"
1111 " --bus-introspect=PATH Write XML introspection data\n"
1112 " --unit=UNIT Set default unit\n"
1113 " --dump-core[=BOOL] Dump core on crash\n"
1114 " --crash-vt=NR Change to specified VT on crash\n"
1115 " --crash-reboot[=BOOL] Reboot on crash\n"
1116 " --crash-shell[=BOOL] Run shell on crash\n"
1117 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1118 " --show-status[=BOOL] Show status updates on the console during boot\n"
1119 " --log-target=TARGET Set log target (console, journal, kmsg,\n"
1120 " journal-or-kmsg, null)\n"
1121 " --log-level=LEVEL Set log level (debug, info, notice, warning,\n"
1122 " err, crit, alert, emerg)\n"
1123 " --log-color[=BOOL] Highlight important log messages\n"
1124 " --log-location[=BOOL] Include code location in log messages\n"
1125 " --log-time[=BOOL] Prefix log messages with current time\n"
1126 " --default-standard-output= Set default standard output for services\n"
1127 " --default-standard-error= Set default standard error output for services\n"
1128 " --no-pager Do not pipe output into a pager\n"
1129 "\nSee the %s for details.\n",
1130 program_invocation_short_name
,
1140 static int prepare_reexecute(
1144 bool switching_root
) {
1146 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1147 _cleanup_fclose_
FILE *f
= NULL
;
1154 r
= manager_open_serialization(m
, &f
);
1156 return log_error_errno(r
, "Failed to create serialization file: %m");
1158 /* Make sure nothing is really destructed when we shut down */
1160 bus_manager_send_reloading(m
, true);
1166 r
= manager_serialize(m
, f
, fds
, switching_root
);
1170 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1171 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1173 r
= fd_cloexec(fileno(f
), false);
1175 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1177 r
= fdset_cloexec(fds
, false);
1179 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1181 *ret_f
= TAKE_PTR(f
);
1182 *ret_fds
= TAKE_PTR(fds
);
1187 static void bump_file_max_and_nr_open(void) {
1189 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
1190 * numbers of file descriptors are no longer a performance problem and their memory is properly
1191 * tracked by memcg, thus counting them and limiting them in another two layers of limits is
1192 * unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
1193 * on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
1195 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1199 #if BUMP_PROC_SYS_FS_FILE_MAX
1200 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
1201 * different, but the operation would fail silently.) */
1202 r
= sysctl_write("fs/file-max", LONG_MAX_STR
);
1204 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
,
1205 r
, "Failed to bump fs.file-max, ignoring: %m");
1208 #if BUMP_PROC_SYS_FS_NR_OPEN
1211 /* Argh! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know
1212 * what they are. The expression by which the maximum is determined is dependent on the architecture,
1213 * and is something we don't really want to copy to userspace, as it is dependent on implementation
1214 * details of the kernel. Since the kernel doesn't expose the maximum value to us, we can only try
1215 * and hope. Hence, let's start with INT_MAX, and then keep halving the value until we find one that
1216 * works. Ugly? Yes, absolutely, but kernel APIs are kernel APIs, so what do can we do... 🤯 */
1221 v
&= ~(__SIZEOF_POINTER__
- 1); /* Round down to next multiple of the pointer size */
1223 log_warning("Can't bump fs.nr_open, value too small.");
1229 log_error_errno(k
, "Failed to read fs.nr_open: %m");
1232 if (k
>= v
) { /* Already larger */
1233 log_debug("Skipping bump, value is already larger.");
1237 r
= sysctl_writef("fs/nr_open", "%i", v
);
1239 log_debug("Couldn't write fs.nr_open as %i, halving it.", v
);
1244 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.nr_open, ignoring: %m");
1248 log_debug("Successfully bumped fs.nr_open to %i", v
);
1254 static int bump_rlimit_nofile(const struct rlimit
*saved_rlimit
) {
1255 struct rlimit new_rlimit
;
1258 /* Get the underlying absolute limit the kernel enforces */
1259 nr
= read_nr_open();
1261 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1262 new_rlimit
= (struct rlimit
) {
1263 .rlim_cur
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_cur
),
1264 .rlim_max
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_max
),
1267 /* Shortcut if nothing changes. */
1268 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_max
&&
1269 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_cur
) {
1270 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1274 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1275 * both hard and soft. */
1276 r
= setrlimit_closest(RLIMIT_NOFILE
, &new_rlimit
);
1278 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1283 static int bump_rlimit_memlock(const struct rlimit
*saved_rlimit
) {
1284 struct rlimit new_rlimit
;
1288 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
1289 * which should normally disable such checks. We need them to implement IPAddressAllow= and
1290 * IPAddressDeny=, hence let's bump the value high enough for our user. */
1292 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1293 * must be unsigned, hence this is a given, but let's make this clear here. */
1294 assert_cc(RLIM_INFINITY
> 0);
1296 mm
= physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
1297 * physical RAM. We allow an eighth to be locked by us, just to
1300 new_rlimit
= (struct rlimit
) {
1301 .rlim_cur
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_cur
, mm
),
1302 .rlim_max
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_max
, mm
),
1305 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_cur
&&
1306 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_max
) {
1307 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1311 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &new_rlimit
);
1313 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1318 static void test_usr(void) {
1320 /* Check that /usr is either on the same file system as / or mounted already. */
1322 if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) <= 0)
1325 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1326 "Some things will probably break (sometimes even silently) in mysterious ways. "
1327 "Consult https://www.freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1330 static int enforce_syscall_archs(Set
*archs
) {
1334 if (!is_seccomp_available())
1337 r
= seccomp_restrict_archs(arg_syscall_archs
);
1339 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1344 static int os_release_status(void) {
1345 _cleanup_free_
char *pretty_name
= NULL
, *name
= NULL
, *version
= NULL
,
1346 *ansi_color
= NULL
, *support_end
= NULL
;
1349 r
= parse_os_release(NULL
,
1350 "PRETTY_NAME", &pretty_name
,
1352 "VERSION", &version
,
1353 "ANSI_COLOR", &ansi_color
,
1354 "SUPPORT_END", &support_end
);
1356 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1357 "Failed to read os-release file, ignoring: %m");
1359 const char *label
= os_release_pretty_name(pretty_name
, name
);
1361 if (show_status_on(arg_show_status
)) {
1362 if (log_get_show_color())
1363 status_printf(NULL
, 0,
1364 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1365 empty_to_null(ansi_color
) ?: "1",
1368 status_printf(NULL
, 0,
1369 "\nWelcome to %s!\n",
1373 if (support_end
&& os_release_support_ended(support_end
, /* quiet */ false, NULL
) > 0)
1374 /* pretty_name may include the version already, so we'll print the version only if we
1375 * have it and we're not using pretty_name. */
1376 status_printf(ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
, 0,
1377 "This OS version (%s%s%s) is past its end-of-support date (%s)",
1379 (pretty_name
|| !version
) ? "" : " version ",
1380 (pretty_name
|| !version
) ? "" : version
,
1386 static int setup_os_release(RuntimeScope scope
) {
1387 _cleanup_free_
char *os_release_dst
= NULL
;
1388 const char *os_release_src
= "/etc/os-release";
1391 if (access("/etc/os-release", F_OK
) < 0) {
1392 if (errno
!= ENOENT
)
1393 log_debug_errno(errno
, "Failed to check if /etc/os-release exists, ignoring: %m");
1395 os_release_src
= "/usr/lib/os-release";
1398 if (scope
== RUNTIME_SCOPE_SYSTEM
) {
1399 os_release_dst
= strdup("/run/systemd/propagate/os-release");
1400 if (!os_release_dst
)
1401 return log_oom_debug();
1403 if (asprintf(&os_release_dst
, "/run/user/" UID_FMT
"/systemd/propagate/os-release", geteuid()) < 0)
1404 return log_oom_debug();
1407 r
= mkdir_parents_label(os_release_dst
, 0755);
1408 if (r
< 0 && r
!= -EEXIST
)
1409 return log_debug_errno(r
, "Failed to create parent directory of %s, ignoring: %m", os_release_dst
);
1411 r
= copy_file(os_release_src
, os_release_dst
, /* open_flags= */ 0, 0644, COPY_MAC_CREATE
);
1413 return log_debug_errno(r
, "Failed to create %s, ignoring: %m", os_release_dst
);
1418 static int write_container_id(void) {
1420 int r
= 0; /* avoid false maybe-uninitialized warning */
1422 c
= getenv("container");
1427 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1429 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1434 static int bump_unix_max_dgram_qlen(void) {
1435 _cleanup_free_
char *qlen
= NULL
;
1439 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
1440 * the value really really early during boot, so that it is actually applied to all our sockets,
1441 * including the $NOTIFY_SOCKET one. */
1443 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1445 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1446 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1448 r
= safe_atolu(qlen
, &v
);
1450 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen
);
1452 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1455 r
= sysctl_write("net/unix/max_dgram_qlen", STRINGIFY(DEFAULT_UNIX_MAX_DGRAM_QLEN
));
1457 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1458 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1463 static int fixup_environment(void) {
1464 _cleanup_free_
char *term
= NULL
;
1468 /* Only fix up the environment when we are started as PID 1 */
1469 if (getpid_cached() != 1)
1472 /* We expect the environment to be set correctly if run inside a container. */
1473 if (detect_container() > 0)
1476 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
1477 * backend device used by the console. We try to make a better guess here since some consoles might
1478 * not have support for color mode for example.
1480 * However if TERM was configured through the kernel command line then leave it alone. */
1481 r
= proc_cmdline_get_key("TERM", 0, &term
);
1486 r
= proc_cmdline_get_key("systemd.tty.term.console", 0, &term
);
1491 t
= term
?: default_term_for_tty("/dev/console");
1493 if (setenv("TERM", t
, 1) < 0)
1496 /* The kernels sets HOME=/ for init. Let's undo this. */
1497 if (path_equal_ptr(getenv("HOME"), "/"))
1498 assert_se(unsetenv("HOME") == 0);
1503 static void redirect_telinit(int argc
, char *argv
[]) {
1505 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1507 #if HAVE_SYSV_COMPAT
1508 if (getpid_cached() == 1)
1511 if (!invoked_as(argv
, "init"))
1514 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1515 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1520 static int become_shutdown(int objective
, int retval
) {
1521 static const char* const table
[_MANAGER_OBJECTIVE_MAX
] = {
1522 [MANAGER_EXIT
] = "exit",
1523 [MANAGER_REBOOT
] = "reboot",
1524 [MANAGER_POWEROFF
] = "poweroff",
1525 [MANAGER_HALT
] = "halt",
1526 [MANAGER_KEXEC
] = "kexec",
1529 char log_level
[STRLEN("--log-level=") + DECIMAL_STR_MAX(int)],
1530 timeout
[STRLEN("--timeout=") + DECIMAL_STR_MAX(usec_t
) + STRLEN("us")],
1531 exit_code
[STRLEN("--exit-code=") + DECIMAL_STR_MAX(uint8_t)];
1533 _cleanup_strv_free_
char **env_block
= NULL
;
1534 usec_t watchdog_timer
= 0;
1537 assert(objective
>= 0 && objective
< _MANAGER_OBJECTIVE_MAX
);
1538 assert(table
[objective
]);
1540 xsprintf(log_level
, "--log-level=%d", log_get_max_level());
1541 xsprintf(timeout
, "--timeout=%" PRI_USEC
"us", arg_default_timeout_stop_usec
);
1543 const char* command_line
[10] = {
1544 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1548 /* Note that the last position is a terminator and must contain NULL. */
1552 assert(command_line
[pos
-1]);
1553 assert(!command_line
[pos
]);
1555 switch (log_get_target()) {
1557 case LOG_TARGET_KMSG
:
1558 case LOG_TARGET_JOURNAL_OR_KMSG
:
1559 case LOG_TARGET_SYSLOG_OR_KMSG
:
1560 command_line
[pos
++] = "--log-target=kmsg";
1563 case LOG_TARGET_NULL
:
1564 command_line
[pos
++] = "--log-target=null";
1567 case LOG_TARGET_CONSOLE
:
1569 command_line
[pos
++] = "--log-target=console";
1573 if (log_get_show_color())
1574 command_line
[pos
++] = "--log-color";
1576 if (log_get_show_location())
1577 command_line
[pos
++] = "--log-location";
1579 if (log_get_show_time())
1580 command_line
[pos
++] = "--log-time";
1582 xsprintf(exit_code
, "--exit-code=%d", retval
);
1583 command_line
[pos
++] = exit_code
;
1585 assert(pos
< ELEMENTSOF(command_line
));
1589 if (objective
== MANAGER_REBOOT
)
1590 watchdog_timer
= arg_reboot_watchdog
;
1591 else if (objective
== MANAGER_KEXEC
)
1592 watchdog_timer
= arg_kexec_watchdog
;
1594 /* If we reboot or kexec let's set the shutdown watchdog and tell the
1595 * shutdown binary to repeatedly ping it.
1596 * Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
1597 (void) watchdog_setup_pretimeout(0);
1598 (void) watchdog_setup_pretimeout_governor(NULL
);
1599 r
= watchdog_setup(watchdog_timer
);
1600 watchdog_close(r
< 0);
1602 /* The environment block: */
1604 env_block
= strv_copy(environ
);
1606 /* Tell the binary how often to ping, ignore failure */
1607 (void) strv_extendf(&env_block
, "WATCHDOG_USEC="USEC_FMT
, watchdog_timer
);
1609 if (arg_watchdog_device
)
1610 (void) strv_extendf(&env_block
, "WATCHDOG_DEVICE=%s", arg_watchdog_device
);
1612 /* Avoid the creation of new processes forked by the kernel; at this
1613 * point, we will not listen to the signals anyway */
1614 if (detect_container() <= 0)
1615 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1617 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1621 static void initialize_clock(void) {
1624 /* This is called very early on, before we parse the kernel command line or otherwise figure out why
1625 * we are running, but only once. */
1627 if (clock_is_localtime(NULL
) > 0) {
1630 /* The very first call of settimeofday() also does a time warp in the kernel.
1632 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
1633 * take care of maintaining the RTC and do all adjustments. This matches the behavior of
1634 * Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
1636 r
= clock_set_timezone(&min
);
1638 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1640 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1642 } else if (!in_initrd())
1644 * Do a dummy very first call to seal the kernel's time warp magic.
1646 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
1647 * LOCAL, but the real system could be set up that way. In such case, we need to delay the
1648 * time-warp or the sealing until we reach the real system.
1650 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
1651 * the time will jump or be incorrect at every daylight saving time change. All kernel local
1652 * time concepts will be treated as UTC that way.
1654 (void) clock_reset_timewarp();
1656 ClockChangeDirection change_dir
;
1657 r
= clock_apply_epoch(&change_dir
);
1658 if (r
> 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1659 log_info("System time before build time, advancing clock.");
1660 else if (r
> 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1661 log_info("System time is further ahead than %s after build time, resetting clock to build time.",
1662 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1663 else if (r
< 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1664 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1665 else if (r
< 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1666 log_error_errno(r
, "Current system time is further ahead %s after build time, but cannot correct: %m",
1667 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1670 static void apply_clock_update(void) {
1671 /* This is called later than initialize_clock(), i.e. after we parsed configuration files/kernel
1672 * command line and such. */
1674 if (arg_clock_usec
== 0)
1677 if (getpid_cached() != 1)
1680 if (clock_settime(CLOCK_REALTIME
, TIMESPEC_STORE(arg_clock_usec
)) < 0)
1681 log_error_errno(errno
, "Failed to set system clock to time specified on kernel command line: %m");
1683 log_info("Set system clock to %s, as specified on the kernel command line.",
1684 FORMAT_TIMESTAMP(arg_clock_usec
));
1687 static void cmdline_take_random_seed(void) {
1691 if (arg_random_seed_size
== 0)
1694 if (getpid_cached() != 1)
1697 assert(arg_random_seed
);
1698 suggested
= random_pool_size();
1700 if (arg_random_seed_size
< suggested
)
1701 log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
1702 arg_random_seed_size
, suggested
);
1704 r
= random_write_entropy(-1, arg_random_seed
, arg_random_seed_size
, true);
1706 log_warning_errno(r
, "Failed to credit entropy specified on kernel command line, ignoring: %m");
1710 log_notice("Successfully credited entropy passed on kernel command line.\n"
1711 "Note that the seed provided this way is accessible to unprivileged programs. "
1712 "This functionality should not be used outside of testing environments.");
1715 static void initialize_coredump(bool skip_setup
) {
1716 if (getpid_cached() != 1)
1719 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
1720 * the limit) will process core dumps for system services by default. */
1721 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1722 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1724 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1725 * until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
1726 * command line later so core dumps can still be generated during early startup and in initrd. */
1728 disable_coredumps();
1731 static void initialize_core_pattern(bool skip_setup
) {
1734 if (skip_setup
|| !arg_early_core_pattern
)
1737 if (getpid_cached() != 1)
1740 r
= write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1742 log_warning_errno(r
, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1743 arg_early_core_pattern
);
1746 static void update_cpu_affinity(bool skip_setup
) {
1747 _cleanup_free_
char *mask
= NULL
;
1749 if (skip_setup
|| !arg_cpu_affinity
.set
)
1752 assert(arg_cpu_affinity
.allocated
> 0);
1754 mask
= cpu_set_to_range_string(&arg_cpu_affinity
);
1755 log_debug("Setting CPU affinity to {%s}.", strnull(mask
));
1757 if (sched_setaffinity(0, arg_cpu_affinity
.allocated
, arg_cpu_affinity
.set
) < 0)
1758 log_warning_errno(errno
, "Failed to set CPU affinity, ignoring: %m");
1761 static void update_numa_policy(bool skip_setup
) {
1763 _cleanup_free_
char *nodes
= NULL
;
1764 const char * policy
= NULL
;
1766 if (skip_setup
|| !mpol_is_valid(numa_policy_get_type(&arg_numa_policy
)))
1769 if (DEBUG_LOGGING
) {
1770 policy
= mpol_to_string(numa_policy_get_type(&arg_numa_policy
));
1771 nodes
= cpu_set_to_range_string(&arg_numa_policy
.nodes
);
1772 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy
), strnull(nodes
));
1775 r
= apply_numa_policy(&arg_numa_policy
);
1776 if (r
== -EOPNOTSUPP
)
1777 log_debug_errno(r
, "NUMA support not available, ignoring.");
1779 log_warning_errno(r
, "Failed to set NUMA memory policy, ignoring: %m");
1782 static void filter_args(
1791 /* Copy some filtered arguments into the dst array from src. */
1792 for (int i
= 1; i
< argc
; i
++) {
1793 if (STR_IN_SET(src
[i
],
1799 if (startswith(src
[i
], "--deserialize="))
1801 if (streq(src
[i
], "--deserialize")) {
1802 i
++; /* Skip the argument too */
1806 /* Skip target unit designators. We already acted upon this information and have queued
1807 * appropriate jobs. We don't want to redo all this after reexecution. */
1808 if (startswith(src
[i
], "--unit="))
1810 if (streq(src
[i
], "--unit")) {
1811 i
++; /* Skip the argument too */
1815 /* Seems we have a good old option. Let's pass it over to the new instance. */
1816 dst
[(*dst_index
)++] = src
[i
];
1820 static int do_reexecute(
1821 ManagerObjective objective
,
1824 const struct rlimit
*saved_rlimit_nofile
,
1825 const struct rlimit
*saved_rlimit_memlock
,
1827 const char *switch_root_dir
,
1828 const char *switch_root_init
,
1829 const char **ret_error_message
) {
1831 size_t i
, args_size
;
1835 assert(IN_SET(objective
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
));
1837 assert(saved_rlimit_nofile
);
1838 assert(saved_rlimit_memlock
);
1839 assert(ret_error_message
);
1841 if (switch_root_init
) {
1842 r
= chase(switch_root_init
, switch_root_dir
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1844 log_warning_errno(r
, "Failed to chase configured init %s/%s: %m",
1845 strempty(switch_root_dir
), switch_root_init
);
1847 r
= chase(SYSTEMD_BINARY_PATH
, switch_root_dir
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1849 log_debug_errno(r
, "Failed to chase our own binary %s/%s: %m",
1850 strempty(switch_root_dir
), SYSTEMD_BINARY_PATH
);
1854 r
= chase("/sbin/init", switch_root_dir
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1856 return log_error_errno(r
, "Failed to chase %s/sbin/init", strempty(switch_root_dir
));
1859 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1860 * rebooted while we do that */
1861 watchdog_close(true);
1863 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1864 * the kernel default to its child processes */
1865 if (saved_rlimit_nofile
->rlim_cur
!= 0)
1866 (void) setrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
);
1867 if (saved_rlimit_memlock
->rlim_cur
!= RLIM_INFINITY
)
1868 (void) setrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
);
1870 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
1871 * SIGCHLD for them after deserializing. */
1872 if (IN_SET(objective
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
))
1873 broadcast_signal(SIGTERM
, /* wait_for_exit= */ false, /* send_sighup= */ true, arg_default_timeout_stop_usec
);
1874 /* On soft reboot really make sure nothing is left */
1875 if (objective
== MANAGER_SOFT_REBOOT
)
1876 broadcast_signal(SIGKILL
, /* wait_for_exit= */ false, /* send_sighup= */ false, arg_default_timeout_stop_usec
);
1878 if (!switch_root_dir
&& objective
== MANAGER_SOFT_REBOOT
) {
1879 /* If no switch root dir is specified, then check if /run/nextroot/ qualifies and use that */
1880 r
= path_is_os_tree("/run/nextroot");
1881 if (r
< 0 && r
!= -ENOENT
)
1882 log_debug_errno(r
, "Failed to determine if /run/nextroot/ is a valid OS tree, ignoring: %m");
1884 switch_root_dir
= "/run/nextroot";
1887 if (switch_root_dir
) {
1888 r
= switch_root(/* new_root= */ switch_root_dir
,
1889 /* old_root_after= */ NULL
,
1890 /* flags= */ (objective
== MANAGER_SWITCH_ROOT
? SWITCH_ROOT_DESTROY_OLD_ROOT
: 0) |
1891 (objective
== MANAGER_SOFT_REBOOT
? SWITCH_ROOT_SKIP_RECURSIVE_RUN
: 0));
1893 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
1896 args_size
= argc
+ 5;
1897 args
= newa(const char*, args_size
);
1899 if (!switch_root_init
) {
1900 char sfd
[STRLEN("--deserialize=") + DECIMAL_STR_MAX(int)];
1902 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1903 * only if the user didn't specify an explicit init to spawn. */
1905 assert(arg_serialization
);
1908 xsprintf(sfd
, "--deserialize=%i", fileno(arg_serialization
));
1910 i
= 1; /* Leave args[0] empty for now. */
1912 /* Put our stuff first to make sure it always gets parsed in case
1913 * we get weird stuff from the kernel cmdline (like --) */
1914 if (IN_SET(objective
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
))
1915 args
[i
++] = "--switched-root";
1916 args
[i
++] = runtime_scope_cmdline_option_to_string(arg_runtime_scope
);
1919 filter_args(args
, &i
, argv
, argc
);
1923 assert(i
<= args_size
);
1926 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
1927 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
1928 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
1929 * and wait() for it in the parent, before proceeding into the exec().
1931 valgrind_summary_hack();
1933 args
[0] = SYSTEMD_BINARY_PATH
;
1934 (void) execv(args
[0], (char* const*) args
);
1936 if (objective
== MANAGER_REEXECUTE
) {
1937 *ret_error_message
= "Failed to execute our own binary";
1938 return log_error_errno(errno
, "Failed to execute our own binary %s: %m", args
[0]);
1941 log_debug_errno(errno
, "Failed to execute our own binary %s, trying fallback: %m", args
[0]);
1944 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
1945 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
1946 * but let's hope that doesn't matter.) */
1948 arg_serialization
= safe_fclose(arg_serialization
);
1949 fds
= fdset_free(fds
);
1951 /* Reopen the console */
1952 (void) make_console_stdio();
1954 i
= 1; /* Leave args[0] empty for now. */
1955 for (int j
= 1; j
<= argc
; j
++)
1956 args
[i
++] = argv
[j
];
1957 assert(i
<= args_size
);
1959 /* Re-enable any blocked signals, especially important if we switch from initrd to init=... */
1960 (void) reset_all_signal_handlers();
1961 (void) reset_signal_mask();
1962 (void) rlimit_nofile_safe();
1964 if (switch_root_init
) {
1965 args
[0] = switch_root_init
;
1966 (void) execve(args
[0], (char* const*) args
, saved_env
);
1967 log_warning_errno(errno
, "Failed to execute configured init %s, trying fallback: %m", args
[0]);
1970 args
[0] = "/sbin/init";
1971 (void) execv(args
[0], (char* const*) args
);
1974 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
1975 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
1976 "Failed to execute /sbin/init");
1978 *ret_error_message
= "Failed to execute fallback shell";
1980 log_warning("No /sbin/init, trying fallback");
1982 args
[0] = "/bin/sh";
1984 (void) execve(args
[0], (char* const*) args
, saved_env
);
1985 return log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
1987 return log_error_errno(r
, "Failed to execute /sbin/init, giving up: %m");
1990 static int invoke_main_loop(
1992 const struct rlimit
*saved_rlimit_nofile
,
1993 const struct rlimit
*saved_rlimit_memlock
,
1994 int *ret_retval
, /* Return parameters relevant for shutting down */
1995 FDSet
**ret_fds
, /* Return parameters for reexecuting */
1996 char **ret_switch_root_dir
, /* … */
1997 char **ret_switch_root_init
, /* … */
1998 const char **ret_error_message
) {
2003 assert(saved_rlimit_nofile
);
2004 assert(saved_rlimit_memlock
);
2007 assert(ret_switch_root_dir
);
2008 assert(ret_switch_root_init
);
2009 assert(ret_error_message
);
2012 int objective
= manager_loop(m
);
2013 if (objective
< 0) {
2014 *ret_error_message
= "Failed to run main loop";
2015 return log_emergency_errno(objective
, "Failed to run main loop: %m");
2018 switch (objective
) {
2020 case MANAGER_RELOAD
: {
2021 LogTarget saved_log_target
;
2022 int saved_log_level
;
2024 manager_send_reloading(m
);
2026 log_info("Reloading...");
2028 /* First, save any overridden log level/target, then parse the configuration file,
2029 * which might change the log level to new settings. */
2031 saved_log_level
= m
->log_level_overridden
? log_get_max_level() : -1;
2032 saved_log_target
= m
->log_target_overridden
? log_get_target() : _LOG_TARGET_INVALID
;
2034 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
2036 set_manager_defaults(m
);
2037 set_manager_settings(m
);
2039 update_cpu_affinity(false);
2040 update_numa_policy(false);
2042 if (saved_log_level
>= 0)
2043 manager_override_log_level(m
, saved_log_level
);
2044 if (saved_log_target
>= 0)
2045 manager_override_log_target(m
, saved_log_target
);
2047 if (manager_reload(m
) < 0)
2048 /* Reloading failed before the point of no return.
2049 * Let's continue running as if nothing happened. */
2050 m
->objective
= MANAGER_OK
;
2052 log_info("Reloading finished in " USEC_FMT
" ms.",
2053 usec_sub_unsigned(now(CLOCK_MONOTONIC
), m
->timestamps
[MANAGER_TIMESTAMP_UNITS_LOAD
].monotonic
) / USEC_PER_MSEC
);
2058 case MANAGER_REEXECUTE
:
2060 manager_send_reloading(m
); /* From the perspective of the manager calling us this is
2061 * pretty much the same as a reload */
2063 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, false);
2065 *ret_error_message
= "Failed to prepare for reexecution";
2069 log_notice("Reexecuting.");
2071 *ret_retval
= EXIT_SUCCESS
;
2072 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2076 case MANAGER_SWITCH_ROOT
:
2078 manager_send_reloading(m
); /* From the perspective of the manager calling us this is
2079 * pretty much the same as a reload */
2081 manager_set_switching_root(m
, true);
2083 if (!m
->switch_root_init
) {
2084 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, true);
2086 *ret_error_message
= "Failed to prepare for reexecution";
2092 log_notice("Switching root.");
2094 *ret_retval
= EXIT_SUCCESS
;
2096 /* Steal the switch root parameters */
2097 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
2098 *ret_switch_root_init
= TAKE_PTR(m
->switch_root_init
);
2102 case MANAGER_SOFT_REBOOT
:
2103 manager_send_reloading(m
);
2104 manager_set_switching_root(m
, true);
2106 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, /* switching_root= */ true);
2108 *ret_error_message
= "Failed to prepare for reexecution";
2112 log_notice("Soft-rebooting.");
2114 *ret_retval
= EXIT_SUCCESS
;
2115 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
2116 *ret_switch_root_init
= NULL
;
2121 if (MANAGER_IS_USER(m
)) {
2124 *ret_retval
= m
->return_value
;
2126 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2132 case MANAGER_REBOOT
:
2133 case MANAGER_POWEROFF
:
2135 case MANAGER_KEXEC
: {
2136 log_notice("Shutting down.");
2138 *ret_retval
= m
->return_value
;
2140 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2146 assert_not_reached();
2151 static void log_execution_mode(bool *ret_first_boot
) {
2152 bool first_boot
= false;
2155 assert(ret_first_boot
);
2157 switch (arg_runtime_scope
) {
2159 case RUNTIME_SCOPE_SYSTEM
: {
2163 log_info("systemd " GIT_VERSION
" running in %ssystem mode (%s)",
2164 arg_action
== ACTION_TEST
? "test " : "",
2167 v
= detect_virtualization();
2169 log_info("Detected virtualization %s.", virtualization_to_string(v
));
2171 v
= detect_confidential_virtualization();
2173 log_info("Detected confidential virtualization %s.", confidential_virtualization_to_string(v
));
2175 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2178 log_info("Running in initrd.");
2180 _cleanup_free_
char *id_text
= NULL
;
2182 /* Let's check whether we are in first boot. First, check if an override was
2183 * specified on the kernel commandline. If yes, we honour that. */
2185 r
= proc_cmdline_get_bool("systemd.condition-first-boot", &first_boot
);
2187 log_debug_errno(r
, "Failed to parse systemd.condition-first-boot= kernel commandline argument, ignoring: %m");
2190 log_full(first_boot
? LOG_INFO
: LOG_DEBUG
,
2191 "Kernel commandline argument says we are %s first boot.",
2192 first_boot
? "in" : "not in");
2194 /* Second, perform autodetection. We use /etc/machine-id as flag file for
2195 * this: If it is missing or contains the value "uninitialized", this is the
2196 * first boot. In other cases, it is not. This allows container managers and
2197 * installers to provision a couple of files in /etc but still permit the
2198 * first-boot initialization to occur. If the container manager wants to
2199 * provision the machine ID it should pass $container_uuid to PID 1. */
2201 r
= read_one_line_file("/etc/machine-id", &id_text
);
2202 if (r
< 0 || streq(id_text
, "uninitialized")) {
2203 if (r
< 0 && r
!= -ENOENT
)
2204 log_warning_errno(r
, "Unexpected error while reading /etc/machine-id, ignoring: %m");
2207 log_info("Detected first boot.");
2209 log_debug("Detected initialized system, this is not the first boot.");
2213 assert_se(uname(&uts
) >= 0);
2215 if (strverscmp_improved(uts
.release
, KERNEL_BASELINE_VERSION
) < 0)
2216 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2217 "Your mileage may vary.", uts
.release
, KERNEL_BASELINE_VERSION
);
2219 log_debug("Kernel version %s, our baseline is %s", uts
.release
, KERNEL_BASELINE_VERSION
);
2224 case RUNTIME_SCOPE_USER
:
2225 if (DEBUG_LOGGING
) {
2226 _cleanup_free_
char *t
= NULL
;
2228 t
= uid_to_name(getuid());
2229 log_debug("systemd " GIT_VERSION
" running in %suser mode for user " UID_FMT
"/%s. (%s)",
2230 arg_action
== ACTION_TEST
? " test" : "",
2231 getuid(), strna(t
), systemd_features
);
2237 assert_not_reached();
2240 *ret_first_boot
= first_boot
;
2243 static int initialize_runtime(
2246 struct rlimit
*saved_rlimit_nofile
,
2247 struct rlimit
*saved_rlimit_memlock
,
2248 const char **ret_error_message
) {
2251 assert(ret_error_message
);
2253 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2255 * - Some only apply to --system instances
2256 * - Some only apply to --user instances
2257 * - Some only apply when we first start up, but not when we reexecute
2260 if (arg_action
!= ACTION_RUN
)
2263 update_cpu_affinity(skip_setup
);
2264 update_numa_policy(skip_setup
);
2266 switch (arg_runtime_scope
) {
2268 case RUNTIME_SCOPE_SYSTEM
:
2269 /* Make sure we leave a core dump without panicking the kernel. */
2270 install_crash_handler();
2273 r
= mount_cgroup_controllers();
2275 *ret_error_message
= "Failed to mount cgroup hierarchies";
2279 /* Pull credentials from various sources into a common credential directory (we do
2280 * this here, before setting up the machine ID, so that we can use credential info
2281 * for setting up the machine ID) */
2282 (void) import_credentials();
2284 (void) os_release_status();
2285 (void) hostname_setup(true);
2286 /* Force transient machine-id on first boot. */
2287 machine_id_setup(/* root= */ NULL
, /* force_transient= */ first_boot
, arg_machine_id
, /* ret_machine_id */ NULL
);
2288 (void) loopback_setup();
2289 bump_unix_max_dgram_qlen();
2290 bump_file_max_and_nr_open();
2292 write_container_id();
2294 /* Copy os-release to the propagate directory, so that we update it for services running
2295 * under RootDirectory=/RootImage= when we do a soft reboot. */
2296 r
= setup_os_release(RUNTIME_SCOPE_SYSTEM
);
2298 log_warning_errno(r
, "Failed to copy os-release for propagation, ignoring: %m");
2301 r
= watchdog_set_device(arg_watchdog_device
);
2303 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device
);
2307 case RUNTIME_SCOPE_USER
: {
2308 _cleanup_free_
char *p
= NULL
;
2310 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2311 * user mode. In system mode mount_setup() already did that. */
2313 r
= xdg_user_runtime_dir(&p
, "/systemd");
2315 *ret_error_message
= "$XDG_RUNTIME_DIR is not set";
2316 return log_emergency_errno(r
, "Failed to determine $XDG_RUNTIME_DIR path: %m");
2319 (void) mkdir_p_label(p
, 0755);
2320 (void) make_inaccessible_nodes(p
, UID_INVALID
, GID_INVALID
);
2321 r
= setup_os_release(RUNTIME_SCOPE_USER
);
2323 log_warning_errno(r
, "Failed to copy os-release for propagation, ignoring: %m");
2328 assert_not_reached();
2331 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
2332 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
2333 log_warning_errno(errno
, "Failed to adjust timer slack, ignoring: %m");
2335 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2337 if (!cap_test_all(arg_capability_bounding_set
)) {
2338 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
2340 *ret_error_message
= "Failed to drop capability bounding set of usermode helpers";
2341 return log_emergency_errno(r
, "Failed to drop capability bounding set of usermode helpers: %m");
2344 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
2346 *ret_error_message
= "Failed to drop capability bounding set";
2347 return log_emergency_errno(r
, "Failed to drop capability bounding set: %m");
2351 if (arg_no_new_privs
) {
2352 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2353 *ret_error_message
= "Failed to disable new privileges";
2354 return log_emergency_errno(errno
, "Failed to disable new privileges: %m");
2359 if (arg_syscall_archs
) {
2360 r
= enforce_syscall_archs(arg_syscall_archs
);
2362 *ret_error_message
= "Failed to set syscall architectures";
2367 r
= make_reaper_process(true);
2369 log_warning_errno(r
, "Failed to make us a subreaper, ignoring: %m");
2371 /* Bump up RLIMIT_NOFILE for systemd itself */
2372 (void) bump_rlimit_nofile(saved_rlimit_nofile
);
2373 (void) bump_rlimit_memlock(saved_rlimit_memlock
);
2378 static int do_queue_default_job(
2380 const char **ret_error_message
) {
2382 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2388 if (arg_default_unit
)
2389 unit
= arg_default_unit
;
2390 else if (in_initrd())
2391 unit
= SPECIAL_INITRD_TARGET
;
2393 unit
= SPECIAL_DEFAULT_TARGET
;
2395 log_debug("Activating default unit: %s", unit
);
2397 r
= manager_load_startable_unit_or_warn(m
, unit
, NULL
, &target
);
2398 if (r
< 0 && in_initrd() && !arg_default_unit
) {
2399 /* Fall back to default.target, which we used to always use by default. Only do this if no
2400 * explicit configuration was given. */
2402 log_info("Falling back to " SPECIAL_DEFAULT_TARGET
".");
2404 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_DEFAULT_TARGET
, NULL
, &target
);
2407 log_info("Falling back to " SPECIAL_RESCUE_TARGET
".");
2409 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_RESCUE_TARGET
, NULL
, &target
);
2411 *ret_error_message
= r
== -ERFKILL
? SPECIAL_RESCUE_TARGET
" masked"
2412 : "Failed to load " SPECIAL_RESCUE_TARGET
;
2417 assert(target
->load_state
== UNIT_LOADED
);
2419 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, NULL
, &error
, &job
);
2421 log_debug_errno(r
, "Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
2423 sd_bus_error_free(&error
);
2425 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, NULL
, &error
, &job
);
2427 *ret_error_message
= "Failed to start default target";
2428 return log_emergency_errno(r
, "Failed to start default target: %s", bus_error_message(&error
, r
));
2432 *ret_error_message
= "Failed to isolate default target";
2433 return log_emergency_errno(r
, "Failed to isolate default target: %s", bus_error_message(&error
, r
));
2435 log_info("Queued %s job for default target %s.",
2436 job_type_to_string(job
->type
),
2437 unit_status_string(job
->unit
, NULL
));
2439 m
->default_unit_job_id
= job
->id
;
2444 static void save_rlimits(struct rlimit
*saved_rlimit_nofile
,
2445 struct rlimit
*saved_rlimit_memlock
) {
2447 assert(saved_rlimit_nofile
);
2448 assert(saved_rlimit_memlock
);
2450 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
) < 0)
2451 log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2453 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
) < 0)
2454 log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2457 static void fallback_rlimit_nofile(const struct rlimit
*saved_rlimit_nofile
) {
2460 if (arg_default_rlimit
[RLIMIT_NOFILE
])
2463 /* Make sure forked processes get limits based on the original kernel setting */
2465 rl
= newdup(struct rlimit
, saved_rlimit_nofile
, 1);
2471 /* Bump the hard limit for system services to a substantially higher value. The default
2472 * hard limit current kernels set is pretty low (4K), mostly for historical
2473 * reasons. According to kernel developers, the fd handling in recent kernels has been
2474 * optimized substantially enough, so that we can bump the limit now, without paying too
2475 * high a price in memory or performance. Note however that we only bump the hard limit,
2476 * not the soft limit. That's because select() works the way it works, and chokes on fds
2477 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2478 * unexpecting programs that they get fds higher than what they can process using
2479 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2480 * this pitfall: programs that are written by folks aware of the select() problem in mind
2481 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2482 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2484 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2487 /* Get the underlying absolute limit the kernel enforces */
2488 nr
= read_nr_open();
2490 rl
->rlim_max
= MIN((rlim_t
) nr
, MAX(rl
->rlim_max
, (rlim_t
) HIGH_RLIMIT_NOFILE
));
2493 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2494 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2495 * instance), then lower what we pass on to not confuse our children */
2496 rl
->rlim_cur
= MIN(rl
->rlim_cur
, (rlim_t
) FD_SETSIZE
);
2498 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
2501 static void fallback_rlimit_memlock(const struct rlimit
*saved_rlimit_memlock
) {
2504 /* Pass the original value down to invoked processes */
2506 if (arg_default_rlimit
[RLIMIT_MEMLOCK
])
2509 rl
= newdup(struct rlimit
, saved_rlimit_memlock
, 1);
2515 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2516 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2517 * default for this since kernel 5.16) */
2518 rl
->rlim_max
= MAX(rl
->rlim_max
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2519 rl
->rlim_cur
= MAX(rl
->rlim_cur
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2522 arg_default_rlimit
[RLIMIT_MEMLOCK
] = rl
;
2525 static void setenv_manager_environment(void) {
2528 STRV_FOREACH(p
, arg_manager_environment
) {
2529 log_debug("Setting '%s' in our own environment.", *p
);
2531 r
= putenv_dup(*p
, true);
2533 log_warning_errno(errno
, "Failed to setenv \"%s\", ignoring: %m", *p
);
2537 static void reset_arguments(void) {
2538 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2540 arg_default_unit
= mfree(arg_default_unit
);
2542 /* arg_runtime_scope — ignore */
2544 arg_dump_core
= true;
2545 arg_crash_chvt
= -1;
2546 arg_crash_shell
= false;
2547 arg_crash_reboot
= false;
2548 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2549 arg_show_status
= _SHOW_STATUS_INVALID
;
2550 arg_status_unit_format
= STATUS_UNIT_FORMAT_DEFAULT
;
2551 arg_switched_root
= false;
2552 arg_pager_flags
= 0;
2553 arg_service_watchdogs
= true;
2554 arg_default_std_output
= EXEC_OUTPUT_JOURNAL
;
2555 arg_default_std_error
= EXEC_OUTPUT_INHERIT
;
2556 arg_default_restart_usec
= DEFAULT_RESTART_USEC
;
2557 arg_default_timeout_start_usec
= manager_default_timeout(arg_runtime_scope
);
2558 arg_default_timeout_stop_usec
= manager_default_timeout(arg_runtime_scope
);
2559 arg_default_timeout_abort_usec
= manager_default_timeout(arg_runtime_scope
);
2560 arg_default_timeout_abort_set
= false;
2561 arg_default_device_timeout_usec
= manager_default_timeout(arg_runtime_scope
);
2562 arg_default_start_limit_interval
= DEFAULT_START_LIMIT_INTERVAL
;
2563 arg_default_start_limit_burst
= DEFAULT_START_LIMIT_BURST
;
2564 arg_runtime_watchdog
= 0;
2565 arg_reboot_watchdog
= 10 * USEC_PER_MINUTE
;
2566 arg_kexec_watchdog
= 0;
2567 arg_pretimeout_watchdog
= 0;
2568 arg_early_core_pattern
= mfree(arg_early_core_pattern
);
2569 arg_watchdog_device
= mfree(arg_watchdog_device
);
2570 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
2572 arg_default_environment
= strv_free(arg_default_environment
);
2573 arg_manager_environment
= strv_free(arg_manager_environment
);
2574 rlimit_free_all(arg_default_rlimit
);
2576 arg_capability_bounding_set
= CAP_MASK_UNSET
;
2577 arg_no_new_privs
= false;
2578 arg_timer_slack_nsec
= NSEC_INFINITY
;
2579 arg_default_timer_accuracy_usec
= 1 * USEC_PER_MINUTE
;
2581 arg_syscall_archs
= set_free(arg_syscall_archs
);
2583 /* arg_serialization — ignore */
2585 arg_default_cpu_accounting
= -1;
2586 arg_default_io_accounting
= false;
2587 arg_default_ip_accounting
= false;
2588 arg_default_blockio_accounting
= false;
2589 arg_default_memory_accounting
= MEMORY_ACCOUNTING_DEFAULT
;
2590 arg_default_tasks_accounting
= true;
2591 arg_default_tasks_max
= DEFAULT_TASKS_MAX
;
2592 arg_default_memory_pressure_threshold_usec
= MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC
;
2593 arg_default_memory_pressure_watch
= CGROUP_PRESSURE_WATCH_AUTO
;
2594 arg_machine_id
= (sd_id128_t
) {};
2595 arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
2596 arg_default_oom_policy
= OOM_STOP
;
2598 cpu_set_reset(&arg_cpu_affinity
);
2599 numa_policy_reset(&arg_numa_policy
);
2601 arg_random_seed
= mfree(arg_random_seed
);
2602 arg_random_seed_size
= 0;
2605 arg_default_oom_score_adjust_set
= false;
2606 arg_default_smack_process_label
= mfree(arg_default_smack_process_label
);
2608 arg_reload_limit_interval_sec
= 0;
2609 arg_reload_limit_burst
= 0;
2612 static void determine_default_oom_score_adjust(void) {
2615 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2616 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2619 if (arg_default_oom_score_adjust_set
)
2625 r
= get_oom_score_adjust(&a
);
2627 return (void) log_warning_errno(r
, "Failed to determine current OOM score adjustment value, ignoring: %m");
2629 assert_cc(100 <= OOM_SCORE_ADJ_MAX
);
2630 b
= a
>= OOM_SCORE_ADJ_MAX
- 100 ? OOM_SCORE_ADJ_MAX
: a
+ 100;
2635 arg_default_oom_score_adjust
= b
;
2636 arg_default_oom_score_adjust_set
= true;
2639 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
2640 const struct rlimit
*saved_rlimit_memlock
) {
2643 assert(saved_rlimit_nofile
);
2644 assert(saved_rlimit_memlock
);
2646 /* Assign configuration defaults */
2649 r
= parse_config_file();
2651 log_warning_errno(r
, "Failed to parse config file, ignoring: %m");
2653 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2654 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
2656 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2659 /* Initialize some default rlimits for services if they haven't been configured */
2660 fallback_rlimit_nofile(saved_rlimit_nofile
);
2661 fallback_rlimit_memlock(saved_rlimit_memlock
);
2663 /* Note that this also parses bits from the kernel command line, including "debug". */
2664 log_parse_environment();
2666 /* Initialize the show status setting if it hasn't been set explicitly yet */
2667 if (arg_show_status
== _SHOW_STATUS_INVALID
)
2668 arg_show_status
= SHOW_STATUS_YES
;
2670 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2671 determine_default_oom_score_adjust();
2673 /* Push variables into the manager environment block */
2674 setenv_manager_environment();
2676 /* Parse log environment variables again to take into account any new environment variables. */
2677 log_parse_environment();
2682 static int safety_checks(void) {
2684 if (getpid_cached() == 1 &&
2685 arg_action
!= ACTION_RUN
)
2686 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2687 "Unsupported execution mode while PID 1.");
2689 if (getpid_cached() == 1 &&
2690 arg_runtime_scope
== RUNTIME_SCOPE_USER
)
2691 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2692 "Can't run --user mode as PID 1.");
2694 if (arg_action
== ACTION_RUN
&&
2695 arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
&&
2696 getpid_cached() != 1)
2697 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2698 "Can't run system mode unless PID 1.");
2700 if (arg_action
== ACTION_TEST
&&
2702 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2703 "Don't run test mode as root.");
2705 switch (arg_runtime_scope
) {
2707 case RUNTIME_SCOPE_USER
:
2709 if (arg_action
== ACTION_RUN
&&
2711 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2712 "Trying to run as user instance, but the system has not been booted with systemd.");
2714 if (arg_action
== ACTION_RUN
&&
2715 !getenv("XDG_RUNTIME_DIR"))
2716 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH
),
2717 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2721 case RUNTIME_SCOPE_SYSTEM
:
2722 if (arg_action
== ACTION_RUN
&&
2723 running_in_chroot() > 0)
2724 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2725 "Cannot be run in a chroot() environment.");
2729 assert_not_reached();
2735 static int initialize_security(
2736 bool *loaded_policy
,
2737 dual_timestamp
*security_start_timestamp
,
2738 dual_timestamp
*security_finish_timestamp
,
2739 const char **ret_error_message
) {
2743 assert(loaded_policy
);
2744 assert(security_start_timestamp
);
2745 assert(security_finish_timestamp
);
2746 assert(ret_error_message
);
2748 dual_timestamp_get(security_start_timestamp
);
2750 r
= mac_selinux_setup(loaded_policy
);
2752 *ret_error_message
= "Failed to load SELinux policy";
2756 r
= mac_smack_setup(loaded_policy
);
2758 *ret_error_message
= "Failed to load SMACK policy";
2762 r
= mac_apparmor_setup();
2764 *ret_error_message
= "Failed to load AppArmor policy";
2770 *ret_error_message
= "Failed to load IMA policy";
2774 dual_timestamp_get(security_finish_timestamp
);
2778 static int collect_fds(FDSet
**ret_fds
, const char **ret_error_message
) {
2782 assert(ret_error_message
);
2784 /* Pick up all fds passed to us. We apply a filter here: we only take the fds that have O_CLOEXEC
2785 * off. All fds passed via execve() to us must have O_CLOEXEC off, and our own code and dependencies
2786 * should be clean enough to set O_CLOEXEC universally. Thus checking the bit should be a safe
2787 * mechanism to distinguish passed in fds from our own.
2789 * Why bother? Some subsystems we initialize early, specifically selinux might keep fds open in our
2790 * process behind our back. We should not take possession of that (and then accidentally close
2791 * it). SELinux thankfully sets O_CLOEXEC on its fds, so this test should work. */
2792 r
= fdset_new_fill(/* filter_cloexec= */ 0, ret_fds
);
2794 *ret_error_message
= "Failed to allocate fd set";
2795 return log_emergency_errno(r
, "Failed to allocate fd set: %m");
2798 (void) fdset_cloexec(*ret_fds
, true);
2800 /* The serialization fd should have O_CLOEXEC turned on already, let's verify that we didn't pick it up here */
2801 assert_se(!arg_serialization
|| !fdset_contains(*ret_fds
, fileno(arg_serialization
)));
2806 static void setup_console_terminal(bool skip_setup
) {
2808 if (arg_runtime_scope
!= RUNTIME_SCOPE_SYSTEM
)
2811 /* Become a session leader if we aren't one yet. */
2814 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2815 * controlling tty. */
2816 (void) release_terminal();
2818 /* Reset the console, but only if this is really init and we are freshly booted */
2819 if (getpid_cached() == 1 && !skip_setup
)
2820 (void) console_setup();
2823 static bool early_skip_setup_check(int argc
, char *argv
[]) {
2824 bool found_deserialize
= false;
2826 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2827 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2828 * special setup things anyway, even if in that case we also do deserialization. */
2830 for (int i
= 1; i
< argc
; i
++)
2831 if (streq(argv
[i
], "--switched-root"))
2832 return false; /* If we switched root, don't skip the setup. */
2833 else if (startswith(argv
[i
], "--deserialize=") || streq(argv
[i
], "--deserialize"))
2834 found_deserialize
= true;
2836 return found_deserialize
; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2839 static int save_env(void) {
2842 l
= strv_copy(environ
);
2846 strv_free_and_replace(saved_env
, l
);
2850 int main(int argc
, char *argv
[]) {
2852 initrd_timestamp
= DUAL_TIMESTAMP_NULL
,
2853 userspace_timestamp
= DUAL_TIMESTAMP_NULL
,
2854 kernel_timestamp
= DUAL_TIMESTAMP_NULL
,
2855 security_start_timestamp
= DUAL_TIMESTAMP_NULL
,
2856 security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
2857 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0),
2858 saved_rlimit_memlock
= RLIMIT_MAKE_CONST(RLIM_INFINITY
); /* The original rlimits we passed
2859 * in. Note we use different values
2860 * for the two that indicate whether
2861 * these fields are initialized! */
2862 bool skip_setup
, loaded_policy
= false, queue_default_job
= false, first_boot
= false;
2863 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
2864 usec_t before_startup
, after_startup
;
2865 static char systemd
[] = "systemd";
2866 const char *error_message
= NULL
;
2867 int r
, retval
= EXIT_FAILURE
;
2871 assert_se(argc
> 0 && !isempty(argv
[0]));
2873 /* SysV compatibility: redirect init → telinit */
2874 redirect_telinit(argc
, argv
);
2876 /* Take timestamps early on */
2877 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
2878 dual_timestamp_get(&userspace_timestamp
);
2880 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2882 skip_setup
= early_skip_setup_check(argc
, argv
);
2884 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2885 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2887 program_invocation_short_name
= systemd
;
2888 (void) prctl(PR_SET_NAME
, systemd
);
2890 /* Save the original command line */
2891 save_argc_argv(argc
, argv
);
2893 /* Save the original environment as we might need to restore it if we're requested to execute another
2894 * system manager later. */
2897 error_message
= "Failed to copy environment block";
2901 /* Make sure that if the user says "syslog" we actually log to the journal. */
2902 log_set_upgrade_syslog_to_journal(true);
2904 if (getpid_cached() == 1) {
2905 /* When we run as PID 1 force system mode */
2906 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
2908 /* Disable the umask logic */
2911 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2912 * not be activated yet (even though the log socket for it exists). */
2913 log_set_prohibit_ipc(true);
2915 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
2916 * is important so that we never end up logging to any foreign stderr, for example if we have
2917 * to log in a child process right before execve()'ing the actual binary, at a point in time
2918 * where socket activation stderr/stdout area already set up. */
2919 log_set_always_reopen_console(true);
2921 if (detect_container() <= 0) {
2923 /* Running outside of a container as PID 1 */
2924 log_set_target_and_open(LOG_TARGET_KMSG
);
2927 initrd_timestamp
= userspace_timestamp
;
2930 r
= mount_setup_early();
2932 error_message
= "Failed to mount early API filesystems";
2937 /* We might have just mounted /proc, so let's try to parse the kernel
2938 * command line log arguments immediately. */
2939 log_parse_environment();
2941 /* Let's open the log backend a second time, in case the first time didn't
2942 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2943 * available, and it previously wasn't. */
2947 disable_printk_ratelimit();
2949 r
= initialize_security(
2951 &security_start_timestamp
,
2952 &security_finish_timestamp
,
2958 if (mac_init() < 0) {
2959 error_message
= "Failed to initialize MAC support";
2966 /* Set the default for later on, but don't actually open the logs like this for
2967 * now. Note that if we are transitioning from the initrd there might still be
2968 * journal fd open, and we shouldn't attempt opening that before we parsed
2969 * /proc/cmdline which might redirect output elsewhere. */
2970 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
2973 /* Running inside a container, as PID 1 */
2974 log_set_target_and_open(LOG_TARGET_CONSOLE
);
2976 /* For later on, see above... */
2977 log_set_target(LOG_TARGET_JOURNAL
);
2979 /* clear the kernel timestamp, because we are in a container */
2980 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2983 initialize_coredump(skip_setup
);
2985 r
= fixup_environment();
2987 log_emergency_errno(r
, "Failed to fix up PID 1 environment: %m");
2988 error_message
= "Failed to fix up PID1 environment";
2992 /* Try to figure out if we can use colors with the console. No need to do that for user
2993 * instances since they never log into the console. */
2994 log_show_color(colors_enabled());
2996 r
= make_null_stdio();
2998 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null, ignoring: %m");
3000 /* Load the kernel modules early. */
3002 (void) kmod_setup();
3004 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
3005 r
= mount_setup(loaded_policy
, skip_setup
);
3007 error_message
= "Failed to mount API filesystems";
3011 /* The efivarfs is now mounted, let's lock down the system token. */
3012 lock_down_efi_variables();
3014 /* Cache command-line options passed from EFI variables */
3016 (void) cache_efi_options_variable();
3018 /* Running as user instance */
3019 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
3020 log_set_always_reopen_console(true);
3021 log_set_target_and_open(LOG_TARGET_AUTO
);
3023 /* clear the kernel timestamp, because we are not PID 1 */
3024 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
3026 /* Clear ambient capabilities, so services do not inherit them implicitly. Dropping them does
3027 * not affect the permitted and effective sets which are important for the manager itself to
3029 capability_ambient_set_apply(0, /* also_inherit= */ false);
3031 if (mac_init() < 0) {
3032 error_message
= "Failed to initialize MAC support";
3037 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
3038 * transitioning from the initrd to the main systemd or suchlike. */
3039 save_rlimits(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
3041 /* Reset all signal handlers. */
3042 (void) reset_all_signal_handlers();
3043 (void) ignore_signals(SIGNALS_IGNORE
);
3045 (void) parse_configuration(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
3047 r
= parse_argv(argc
, argv
);
3049 error_message
= "Failed to parse commandline arguments";
3053 r
= safety_checks();
3057 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
, ACTION_DUMP_CONFIGURATION_ITEMS
, ACTION_DUMP_BUS_PROPERTIES
, ACTION_BUS_INTROSPECT
))
3058 pager_open(arg_pager_flags
);
3060 if (arg_action
!= ACTION_RUN
)
3063 if (arg_action
== ACTION_HELP
) {
3064 retval
= help() < 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
3066 } else if (arg_action
== ACTION_VERSION
) {
3069 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
3070 unit_dump_config_items(stdout
);
3071 retval
= EXIT_SUCCESS
;
3073 } else if (arg_action
== ACTION_DUMP_BUS_PROPERTIES
) {
3074 dump_bus_properties(stdout
);
3075 retval
= EXIT_SUCCESS
;
3077 } else if (arg_action
== ACTION_BUS_INTROSPECT
) {
3078 r
= bus_manager_introspect_implementations(stdout
, arg_bus_introspect
);
3079 retval
= r
>= 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
3083 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
3085 /* Move out of the way, so that we won't block unmounts */
3086 assert_se(chdir("/") == 0);
3088 if (arg_action
== ACTION_RUN
) {
3090 /* Apply the systemd.clock_usec= kernel command line switch */
3091 apply_clock_update();
3093 /* Apply random seed from kernel command line */
3094 cmdline_take_random_seed();
3097 /* A core pattern might have been specified via the cmdline. */
3098 initialize_core_pattern(skip_setup
);
3100 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
3103 /* Remember open file descriptors for later deserialization */
3104 r
= collect_fds(&fds
, &error_message
);
3108 /* Give up any control of the console, but make sure its initialized. */
3109 setup_console_terminal(skip_setup
);
3111 /* Open the logging devices, if possible and necessary */
3115 log_execution_mode(&first_boot
);
3117 r
= initialize_runtime(skip_setup
,
3119 &saved_rlimit_nofile
,
3120 &saved_rlimit_memlock
,
3125 r
= manager_new(arg_runtime_scope
,
3126 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
3129 log_emergency_errno(r
, "Failed to allocate manager object: %m");
3130 error_message
= "Failed to allocate manager object";
3134 m
->timestamps
[MANAGER_TIMESTAMP_KERNEL
] = kernel_timestamp
;
3135 m
->timestamps
[MANAGER_TIMESTAMP_INITRD
] = initrd_timestamp
;
3136 m
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
] = userspace_timestamp
;
3137 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START
)] = security_start_timestamp
;
3138 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH
)] = security_finish_timestamp
;
3140 set_manager_defaults(m
);
3141 set_manager_settings(m
);
3142 manager_set_first_boot(m
, first_boot
);
3143 manager_set_switching_root(m
, arg_switched_root
);
3145 /* Remember whether we should queue the default job */
3146 queue_default_job
= !arg_serialization
|| arg_switched_root
;
3148 before_startup
= now(CLOCK_MONOTONIC
);
3150 r
= manager_startup(m
, arg_serialization
, fds
, /* root= */ NULL
);
3152 error_message
= "Failed to start up manager";
3156 /* This will close all file descriptors that were opened, but not claimed by any unit. */
3157 fds
= fdset_free(fds
);
3158 arg_serialization
= safe_fclose(arg_serialization
);
3160 if (queue_default_job
) {
3161 r
= do_queue_default_job(m
, &error_message
);
3166 after_startup
= now(CLOCK_MONOTONIC
);
3168 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
3169 "Loaded units and determined initial transaction in %s.",
3170 FORMAT_TIMESPAN(after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
3172 if (arg_action
== ACTION_TEST
) {
3173 manager_test_summary(m
);
3174 retval
= EXIT_SUCCESS
;
3178 r
= invoke_main_loop(m
,
3179 &saved_rlimit_nofile
,
3180 &saved_rlimit_memlock
,
3186 assert(r
< 0 || IN_SET(r
, MANAGER_EXIT
, /* MANAGER_OK is not expected here. */
3190 MANAGER_SOFT_REBOOT
,
3194 MANAGER_SWITCH_ROOT
));
3200 arg_reboot_watchdog
= manager_get_watchdog(m
, WATCHDOG_REBOOT
);
3201 arg_kexec_watchdog
= manager_get_watchdog(m
, WATCHDOG_KEXEC
);
3202 m
= manager_free(m
);
3205 mac_selinux_finish();
3207 if (IN_SET(r
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
))
3210 &saved_rlimit_nofile
,
3211 &saved_rlimit_memlock
,
3215 &error_message
); /* This only returns if reexecution failed */
3217 arg_serialization
= safe_fclose(arg_serialization
);
3218 fds
= fdset_free(fds
);
3220 saved_env
= strv_free(saved_env
);
3222 #if HAVE_VALGRIND_VALGRIND_H
3223 /* If we are PID 1 and running under valgrind, then let's exit
3224 * here explicitly. valgrind will only generate nice output on
3225 * exit(), not on exec(), hence let's do the former not the
3227 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
3228 /* Cleanup watchdog_device strings for valgrind. We need them
3229 * in become_shutdown() so normally we cannot free them yet. */
3230 watchdog_free_device();
3236 #if HAS_FEATURE_ADDRESS_SANITIZER
3237 __lsan_do_leak_check();
3241 (void) sd_notifyf(0, "ERRNO=%i", -r
);
3243 /* Try to invoke the shutdown binary unless we already failed.
3244 * If we failed above, we want to freeze after finishing cleanup. */
3245 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
&&
3246 IN_SET(r
, MANAGER_EXIT
, MANAGER_REBOOT
, MANAGER_POWEROFF
, MANAGER_HALT
, MANAGER_KEXEC
)) {
3247 r
= become_shutdown(r
, retval
);
3248 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3249 error_message
= "Failed to execute shutdown binary";
3252 /* This is primarily useful when running systemd in a VM, as it provides the user running the VM with
3253 * a mechanism to pick up systemd's exit status in the VM. */
3254 (void) sd_notifyf(0, "EXIT_STATUS=%i", retval
);
3256 watchdog_free_device();
3257 arg_watchdog_device
= mfree(arg_watchdog_device
);
3259 if (getpid_cached() == 1) {
3261 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
3262 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
3263 "%s.", error_message
);
3264 freeze_or_exit_or_reboot();