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"
29 #include "bus-error.h"
31 #include "capability-util.h"
32 #include "cgroup-util.h"
33 #include "clock-util.h"
34 #include "conf-parser.h"
35 #include "cpu-set-util.h"
36 #include "crash-handler.h"
37 #include "dbus-manager.h"
40 #include "dev-setup.h"
41 #include "efi-random.h"
43 #include "emergency-action.h"
45 #include "exit-status.h"
49 #include "format-util.h"
51 #include "hexdecoct.h"
52 #include "hostname-setup.h"
53 #include "ima-setup.h"
54 #include "import-creds.h"
56 #include "kmod-setup.h"
57 #include "limits-util.h"
58 #include "load-fragment.h"
60 #include "loopback-setup.h"
61 #include "machine-id-setup.h"
64 #include "manager-dump.h"
65 #include "manager-serialize.h"
66 #include "mkdir-label.h"
67 #include "mount-setup.h"
70 #include "parse-argument.h"
71 #include "parse-util.h"
72 #include "path-util.h"
73 #include "pretty-print.h"
74 #include "proc-cmdline.h"
75 #include "process-util.h"
76 #include "random-util.h"
77 #include "rlimit-util.h"
79 #include "seccomp-util.h"
81 #include "selinux-setup.h"
82 #include "selinux-util.h"
83 #include "signal-util.h"
84 #include "smack-setup.h"
86 #include "stat-util.h"
87 #include "stdio-util.h"
89 #include "switch-root.h"
90 #include "sysctl-util.h"
91 #include "terminal-util.h"
92 #include "time-util.h"
93 #include "umask-util.h"
94 #include "user-util.h"
99 #if HAS_FEATURE_ADDRESS_SANITIZER
100 #include <sanitizer/lsan_interface.h>
103 #define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
110 ACTION_DUMP_CONFIGURATION_ITEMS
,
111 ACTION_DUMP_BUS_PROPERTIES
,
112 ACTION_BUS_INTROSPECT
,
113 } arg_action
= ACTION_RUN
;
115 static const char *arg_bus_introspect
= NULL
;
117 /* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
118 * defaults are assigned in reset_arguments() below. */
119 static char *arg_default_unit
;
120 static bool arg_system
;
123 bool arg_crash_shell
;
124 bool arg_crash_reboot
;
125 static char *arg_confirm_spawn
;
126 static ShowStatus arg_show_status
;
127 static StatusUnitFormat arg_status_unit_format
;
128 static bool arg_switched_root
;
129 static PagerFlags arg_pager_flags
;
130 static bool arg_service_watchdogs
;
131 static ExecOutput arg_default_std_output
;
132 static ExecOutput arg_default_std_error
;
133 static usec_t arg_default_restart_usec
;
134 static usec_t arg_default_timeout_start_usec
;
135 static usec_t arg_default_timeout_stop_usec
;
136 static usec_t arg_default_timeout_abort_usec
;
137 static bool arg_default_timeout_abort_set
;
138 static usec_t arg_default_start_limit_interval
;
139 static unsigned arg_default_start_limit_burst
;
140 static usec_t arg_runtime_watchdog
;
141 static usec_t arg_reboot_watchdog
;
142 static usec_t arg_kexec_watchdog
;
143 static usec_t arg_pretimeout_watchdog
;
144 static char *arg_early_core_pattern
;
145 static char *arg_watchdog_pretimeout_governor
;
146 static char *arg_watchdog_device
;
147 static char **arg_default_environment
;
148 static char **arg_manager_environment
;
149 static struct rlimit
*arg_default_rlimit
[_RLIMIT_MAX
];
150 static uint64_t arg_capability_bounding_set
;
151 static bool arg_no_new_privs
;
152 static nsec_t arg_timer_slack_nsec
;
153 static usec_t arg_default_timer_accuracy_usec
;
154 static Set
* arg_syscall_archs
;
155 static FILE* arg_serialization
;
156 static int arg_default_cpu_accounting
;
157 static bool arg_default_io_accounting
;
158 static bool arg_default_ip_accounting
;
159 static bool arg_default_blockio_accounting
;
160 static bool arg_default_memory_accounting
;
161 static bool arg_default_tasks_accounting
;
162 static TasksMax arg_default_tasks_max
;
163 static sd_id128_t arg_machine_id
;
164 static EmergencyAction arg_cad_burst_action
;
165 static OOMPolicy arg_default_oom_policy
;
166 static CPUSet arg_cpu_affinity
;
167 static NUMAPolicy arg_numa_policy
;
168 static usec_t arg_clock_usec
;
169 static void *arg_random_seed
;
170 static size_t arg_random_seed_size
;
171 static int arg_default_oom_score_adjust
;
172 static bool arg_default_oom_score_adjust_set
;
174 /* A copy of the original environment block */
175 static char **saved_env
= NULL
;
177 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
178 const struct rlimit
*saved_rlimit_memlock
);
180 static int manager_find_user_config_paths(char ***ret_files
, char ***ret_dirs
) {
181 _cleanup_free_
char *base
= NULL
;
182 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
185 r
= xdg_user_config_dir(&base
, "/systemd");
189 r
= strv_extendf(&files
, "%s/user.conf", base
);
193 r
= strv_extend(&files
, PKGSYSCONFDIR
"/user.conf");
197 r
= strv_consume(&dirs
, TAKE_PTR(base
));
201 r
= strv_extend_strv(&dirs
, CONF_PATHS_STRV("systemd"), false);
205 *ret_files
= TAKE_PTR(files
);
206 *ret_dirs
= TAKE_PTR(dirs
);
210 static int console_setup(void) {
211 _cleanup_close_
int tty_fd
= -1;
214 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
216 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
218 /* We don't want to force text mode. plymouth may be showing
219 * pictures already from initrd. */
220 r
= reset_terminal_fd(tty_fd
, false);
222 return log_error_errno(r
, "Failed to reset /dev/console: %m");
227 static int set_machine_id(const char *m
) {
231 if (sd_id128_from_string(m
, &t
) < 0)
234 if (sd_id128_is_null(t
))
241 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
246 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
248 if (proc_cmdline_value_missing(key
, value
))
251 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
252 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
253 else if (in_initrd() == !!startswith(key
, "rd."))
254 return free_and_strdup_warn(&arg_default_unit
, value
);
256 } else if (proc_cmdline_key_streq(key
, "systemd.dump_core")) {
258 r
= value
? parse_boolean(value
) : true;
260 log_warning_errno(r
, "Failed to parse dump core switch %s, ignoring: %m", value
);
264 } else if (proc_cmdline_key_streq(key
, "systemd.early_core_pattern")) {
266 if (proc_cmdline_value_missing(key
, value
))
269 if (path_is_absolute(value
))
270 (void) parse_path_argument(value
, false, &arg_early_core_pattern
);
272 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value
);
274 } else if (proc_cmdline_key_streq(key
, "systemd.crash_chvt")) {
277 arg_crash_chvt
= 0; /* turn on */
279 r
= parse_crash_chvt(value
, &arg_crash_chvt
);
281 log_warning_errno(r
, "Failed to parse crash chvt switch %s, ignoring: %m", value
);
284 } else if (proc_cmdline_key_streq(key
, "systemd.crash_shell")) {
286 r
= value
? parse_boolean(value
) : true;
288 log_warning_errno(r
, "Failed to parse crash shell switch %s, ignoring: %m", value
);
292 } else if (proc_cmdline_key_streq(key
, "systemd.crash_reboot")) {
294 r
= value
? parse_boolean(value
) : true;
296 log_warning_errno(r
, "Failed to parse crash reboot switch %s, ignoring: %m", value
);
298 arg_crash_reboot
= r
;
300 } else if (proc_cmdline_key_streq(key
, "systemd.confirm_spawn")) {
303 r
= parse_confirm_spawn(value
, &s
);
305 log_warning_errno(r
, "Failed to parse confirm_spawn switch %s, ignoring: %m", value
);
307 free_and_replace(arg_confirm_spawn
, s
);
309 } else if (proc_cmdline_key_streq(key
, "systemd.service_watchdogs")) {
311 r
= value
? parse_boolean(value
) : true;
313 log_warning_errno(r
, "Failed to parse service watchdog switch %s, ignoring: %m", value
);
315 arg_service_watchdogs
= r
;
317 } else if (proc_cmdline_key_streq(key
, "systemd.show_status")) {
320 r
= parse_show_status(value
, &arg_show_status
);
322 log_warning_errno(r
, "Failed to parse show status switch %s, ignoring: %m", value
);
324 arg_show_status
= SHOW_STATUS_YES
;
326 } else if (proc_cmdline_key_streq(key
, "systemd.status_unit_format")) {
328 if (proc_cmdline_value_missing(key
, value
))
331 r
= status_unit_format_from_string(value
);
333 log_warning_errno(r
, "Failed to parse %s=%s, ignoring: %m", key
, value
);
335 arg_status_unit_format
= r
;
337 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_output")) {
339 if (proc_cmdline_value_missing(key
, value
))
342 r
= exec_output_from_string(value
);
344 log_warning_errno(r
, "Failed to parse default standard output switch %s, ignoring: %m", value
);
346 arg_default_std_output
= r
;
348 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_error")) {
350 if (proc_cmdline_value_missing(key
, value
))
353 r
= exec_output_from_string(value
);
355 log_warning_errno(r
, "Failed to parse default standard error switch %s, ignoring: %m", value
);
357 arg_default_std_error
= r
;
359 } else if (streq(key
, "systemd.setenv")) {
361 if (proc_cmdline_value_missing(key
, value
))
364 if (!env_assignment_is_valid(value
))
365 log_warning("Environment variable assignment '%s' is not valid. Ignoring.", value
);
367 r
= strv_env_replace_strdup(&arg_default_environment
, value
);
372 } else if (proc_cmdline_key_streq(key
, "systemd.machine_id")) {
374 if (proc_cmdline_value_missing(key
, value
))
377 r
= set_machine_id(value
);
379 log_warning_errno(r
, "MachineID '%s' is not valid, ignoring: %m", value
);
381 } else if (proc_cmdline_key_streq(key
, "systemd.default_timeout_start_sec")) {
383 if (proc_cmdline_value_missing(key
, value
))
386 r
= parse_sec(value
, &arg_default_timeout_start_usec
);
388 log_warning_errno(r
, "Failed to parse default start timeout '%s', ignoring: %m", value
);
390 if (arg_default_timeout_start_usec
<= 0)
391 arg_default_timeout_start_usec
= USEC_INFINITY
;
393 } else if (proc_cmdline_key_streq(key
, "systemd.cpu_affinity")) {
395 if (proc_cmdline_value_missing(key
, value
))
398 r
= parse_cpu_set(value
, &arg_cpu_affinity
);
400 log_warning_errno(r
, "Failed to parse CPU affinity mask '%s', ignoring: %m", value
);
402 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_device")) {
404 if (proc_cmdline_value_missing(key
, value
))
407 (void) parse_path_argument(value
, false, &arg_watchdog_device
);
409 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_sec")) {
411 if (proc_cmdline_value_missing(key
, value
))
414 if (streq(value
, "default"))
415 arg_runtime_watchdog
= USEC_INFINITY
;
416 else if (streq(value
, "off"))
417 arg_runtime_watchdog
= 0;
419 r
= parse_sec(value
, &arg_runtime_watchdog
);
421 log_warning_errno(r
, "Failed to parse systemd.watchdog_sec= argument '%s', ignoring: %m", value
);
426 arg_kexec_watchdog
= arg_reboot_watchdog
= arg_runtime_watchdog
;
428 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pre_sec")) {
430 if (proc_cmdline_value_missing(key
, value
))
433 if (streq(value
, "default"))
434 arg_pretimeout_watchdog
= USEC_INFINITY
;
435 else if (streq(value
, "off"))
436 arg_pretimeout_watchdog
= 0;
438 r
= parse_sec(value
, &arg_pretimeout_watchdog
);
440 log_warning_errno(r
, "Failed to parse systemd.watchdog_pre_sec= argument '%s', ignoring: %m", value
);
445 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pretimeout_governor")) {
447 if (proc_cmdline_value_missing(key
, value
) || isempty(value
)) {
448 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
452 if (!string_is_safe(value
)) {
453 log_warning("Watchdog pretimeout governor '%s' is not valid, ignoring.", value
);
457 return free_and_strdup_warn(&arg_watchdog_pretimeout_governor
, value
);
459 } else if (proc_cmdline_key_streq(key
, "systemd.clock_usec")) {
461 if (proc_cmdline_value_missing(key
, value
))
464 r
= safe_atou64(value
, &arg_clock_usec
);
466 log_warning_errno(r
, "Failed to parse systemd.clock_usec= argument, ignoring: %s", value
);
468 } else if (proc_cmdline_key_streq(key
, "systemd.random_seed")) {
472 if (proc_cmdline_value_missing(key
, value
))
475 r
= unbase64mem(value
, SIZE_MAX
, &p
, &sz
);
477 log_warning_errno(r
, "Failed to parse systemd.random_seed= argument, ignoring: %s", value
);
479 free(arg_random_seed
);
480 arg_random_seed
= sz
> 0 ? p
: mfree(p
);
481 arg_random_seed_size
= sz
;
483 } else if (streq(key
, "quiet") && !value
) {
485 if (arg_show_status
== _SHOW_STATUS_INVALID
)
486 arg_show_status
= SHOW_STATUS_ERROR
;
488 } else if (streq(key
, "debug") && !value
) {
490 /* Note that log_parse_environment() handles 'debug'
491 * too, and sets the log level to LOG_DEBUG. */
493 if (detect_container() > 0)
494 log_set_target(LOG_TARGET_CONSOLE
);
499 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
500 target
= runlevel_to_target(key
);
502 return free_and_strdup_warn(&arg_default_unit
, target
);
508 #define DEFINE_SETTER(name, func, descr) \
509 static int name(const char *unit, \
510 const char *filename, \
512 const char *section, \
513 unsigned section_line, \
514 const char *lvalue, \
516 const char *rvalue, \
528 log_syntax(unit, LOG_ERR, filename, line, r, \
529 "Invalid " descr "'%s': %m", \
535 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level");
536 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target");
537 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color");
538 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location");
539 DEFINE_SETTER(config_parse_time
, log_show_time_from_string
, "time");
541 static int config_parse_default_timeout_abort(
543 const char *filename
,
546 unsigned section_line
,
554 r
= config_parse_timeout_abort(unit
, filename
, line
, section
, section_line
, lvalue
, ltype
, rvalue
,
555 &arg_default_timeout_abort_usec
, userdata
);
557 arg_default_timeout_abort_set
= r
;
561 static int config_parse_oom_score_adjust(
563 const char *filename
,
566 unsigned section_line
,
575 if (isempty(rvalue
)) {
576 arg_default_oom_score_adjust_set
= false;
580 r
= parse_oom_score_adjust(rvalue
, &oa
);
582 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse the OOM score adjust value '%s', ignoring: %m", rvalue
);
586 arg_default_oom_score_adjust
= oa
;
587 arg_default_oom_score_adjust_set
= true;
592 static int parse_config_file(void) {
593 const ConfigTableItem items
[] = {
594 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
595 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
596 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
597 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
598 { "Manager", "LogTime", config_parse_time
, 0, NULL
},
599 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
600 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, &arg_crash_chvt
},
601 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, &arg_crash_chvt
},
602 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
603 { "Manager", "CrashReboot", config_parse_bool
, 0, &arg_crash_reboot
},
604 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
605 { "Manager", "StatusUnitFormat", config_parse_status_unit_format
, 0, &arg_status_unit_format
},
606 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, &arg_cpu_affinity
},
607 { "Manager", "NUMAPolicy", config_parse_numa_policy
, 0, &arg_numa_policy
.type
},
608 { "Manager", "NUMAMask", config_parse_numa_mask
, 0, &arg_numa_policy
},
609 { "Manager", "JoinControllers", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
610 { "Manager", "RuntimeWatchdogSec", config_parse_watchdog_sec
, 0, &arg_runtime_watchdog
},
611 { "Manager", "RuntimeWatchdogPreSec", config_parse_watchdog_sec
, 0, &arg_pretimeout_watchdog
},
612 { "Manager", "RebootWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
},
613 { "Manager", "ShutdownWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
}, /* obsolete alias */
614 { "Manager", "KExecWatchdogSec", config_parse_watchdog_sec
, 0, &arg_kexec_watchdog
},
615 { "Manager", "WatchdogDevice", config_parse_path
, 0, &arg_watchdog_device
},
616 { "Manager", "RuntimeWatchdogPreGovernor", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &arg_watchdog_pretimeout_governor
},
617 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
618 { "Manager", "NoNewPrivileges", config_parse_bool
, 0, &arg_no_new_privs
},
620 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
622 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
623 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_default_timer_accuracy_usec
},
624 { "Manager", "DefaultStandardOutput", config_parse_output_restricted
, 0, &arg_default_std_output
},
625 { "Manager", "DefaultStandardError", config_parse_output_restricted
, 0, &arg_default_std_error
},
626 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_default_timeout_start_usec
},
627 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_default_timeout_stop_usec
},
628 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort
, 0, NULL
},
629 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_default_restart_usec
},
630 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_default_start_limit_interval
}, /* obsolete alias */
631 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec
, 0, &arg_default_start_limit_interval
},
632 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_default_start_limit_burst
},
633 { "Manager", "DefaultEnvironment", config_parse_environ
, 0, &arg_default_environment
},
634 { "Manager", "ManagerEnvironment", config_parse_environ
, 0, &arg_manager_environment
},
635 { "Manager", "DefaultLimitCPU", config_parse_rlimit
, RLIMIT_CPU
, arg_default_rlimit
},
636 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit
, RLIMIT_FSIZE
, arg_default_rlimit
},
637 { "Manager", "DefaultLimitDATA", config_parse_rlimit
, RLIMIT_DATA
, arg_default_rlimit
},
638 { "Manager", "DefaultLimitSTACK", config_parse_rlimit
, RLIMIT_STACK
, arg_default_rlimit
},
639 { "Manager", "DefaultLimitCORE", config_parse_rlimit
, RLIMIT_CORE
, arg_default_rlimit
},
640 { "Manager", "DefaultLimitRSS", config_parse_rlimit
, RLIMIT_RSS
, arg_default_rlimit
},
641 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit
, RLIMIT_NOFILE
, arg_default_rlimit
},
642 { "Manager", "DefaultLimitAS", config_parse_rlimit
, RLIMIT_AS
, arg_default_rlimit
},
643 { "Manager", "DefaultLimitNPROC", config_parse_rlimit
, RLIMIT_NPROC
, arg_default_rlimit
},
644 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit
, RLIMIT_MEMLOCK
, arg_default_rlimit
},
645 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit
, RLIMIT_LOCKS
, arg_default_rlimit
},
646 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit
, RLIMIT_SIGPENDING
, arg_default_rlimit
},
647 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit
, RLIMIT_MSGQUEUE
, arg_default_rlimit
},
648 { "Manager", "DefaultLimitNICE", config_parse_rlimit
, RLIMIT_NICE
, arg_default_rlimit
},
649 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit
, RLIMIT_RTPRIO
, arg_default_rlimit
},
650 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit
, RLIMIT_RTTIME
, arg_default_rlimit
},
651 { "Manager", "DefaultCPUAccounting", config_parse_tristate
, 0, &arg_default_cpu_accounting
},
652 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_default_io_accounting
},
653 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_default_ip_accounting
},
654 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_default_blockio_accounting
},
655 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_default_memory_accounting
},
656 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_default_tasks_accounting
},
657 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_default_tasks_max
},
658 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, 0, &arg_cad_burst_action
},
659 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy
, 0, &arg_default_oom_policy
},
660 { "Manager", "DefaultOOMScoreAdjust", config_parse_oom_score_adjust
, 0, NULL
},
664 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
669 suffix
= "system.conf.d";
671 r
= manager_find_user_config_paths(&files
, &dirs
);
673 return log_error_errno(r
, "Failed to determine config file paths: %m");
675 suffix
= "user.conf.d";
678 (void) config_parse_many(
679 (const char* const*) (files
?: STRV_MAKE(PKGSYSCONFDIR
"/system.conf")),
680 (const char* const*) (dirs
?: CONF_PATHS_STRV("systemd")),
683 config_item_table_lookup
, items
,
688 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we use
689 * USEC_INFINITY like everywhere else. */
690 if (arg_default_timeout_start_usec
<= 0)
691 arg_default_timeout_start_usec
= USEC_INFINITY
;
692 if (arg_default_timeout_stop_usec
<= 0)
693 arg_default_timeout_stop_usec
= USEC_INFINITY
;
698 static void set_manager_defaults(Manager
*m
) {
702 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
703 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
704 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
706 m
->default_timer_accuracy_usec
= arg_default_timer_accuracy_usec
;
707 m
->default_std_output
= arg_default_std_output
;
708 m
->default_std_error
= arg_default_std_error
;
709 m
->default_timeout_start_usec
= arg_default_timeout_start_usec
;
710 m
->default_timeout_stop_usec
= arg_default_timeout_stop_usec
;
711 m
->default_timeout_abort_usec
= arg_default_timeout_abort_usec
;
712 m
->default_timeout_abort_set
= arg_default_timeout_abort_set
;
713 m
->default_restart_usec
= arg_default_restart_usec
;
714 m
->default_start_limit_interval
= arg_default_start_limit_interval
;
715 m
->default_start_limit_burst
= arg_default_start_limit_burst
;
717 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
718 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
719 if (arg_default_cpu_accounting
>= 0)
720 m
->default_cpu_accounting
= arg_default_cpu_accounting
;
722 m
->default_cpu_accounting
= cpu_accounting_is_cheap();
724 m
->default_io_accounting
= arg_default_io_accounting
;
725 m
->default_ip_accounting
= arg_default_ip_accounting
;
726 m
->default_blockio_accounting
= arg_default_blockio_accounting
;
727 m
->default_memory_accounting
= arg_default_memory_accounting
;
728 m
->default_tasks_accounting
= arg_default_tasks_accounting
;
729 m
->default_tasks_max
= arg_default_tasks_max
;
730 m
->default_oom_policy
= arg_default_oom_policy
;
731 m
->default_oom_score_adjust_set
= arg_default_oom_score_adjust_set
;
732 m
->default_oom_score_adjust
= arg_default_oom_score_adjust
;
734 (void) manager_set_default_rlimits(m
, arg_default_rlimit
);
736 (void) manager_default_environment(m
);
737 (void) manager_transient_environment_add(m
, arg_default_environment
);
740 static void set_manager_settings(Manager
*m
) {
745 /* Propagates the various manager settings into the manager object, i.e. properties that
746 * effect the manager itself (as opposed to just being inherited into newly allocated
747 * units, see set_manager_defaults() above). */
749 m
->confirm_spawn
= arg_confirm_spawn
;
750 m
->service_watchdogs
= arg_service_watchdogs
;
751 m
->cad_burst_action
= arg_cad_burst_action
;
753 manager_set_watchdog(m
, WATCHDOG_RUNTIME
, arg_runtime_watchdog
);
754 manager_set_watchdog(m
, WATCHDOG_REBOOT
, arg_reboot_watchdog
);
755 manager_set_watchdog(m
, WATCHDOG_KEXEC
, arg_kexec_watchdog
);
756 manager_set_watchdog(m
, WATCHDOG_PRETIMEOUT
, arg_pretimeout_watchdog
);
757 r
= manager_set_watchdog_pretimeout_governor(m
, arg_watchdog_pretimeout_governor
);
759 log_warning_errno(r
, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor
);
761 manager_set_show_status(m
, arg_show_status
, "commandline");
762 m
->status_unit_format
= arg_status_unit_format
;
765 static int parse_argv(int argc
, char *argv
[]) {
767 ARG_LOG_LEVEL
= 0x100,
778 ARG_DUMP_CONFIGURATION_ITEMS
,
779 ARG_DUMP_BUS_PROPERTIES
,
789 ARG_DEFAULT_STD_OUTPUT
,
790 ARG_DEFAULT_STD_ERROR
,
792 ARG_SERVICE_WATCHDOGS
,
795 static const struct option options
[] = {
796 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
797 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
798 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
799 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
800 { "log-time", optional_argument
, NULL
, ARG_LOG_TIME
},
801 { "unit", required_argument
, NULL
, ARG_UNIT
},
802 { "system", no_argument
, NULL
, ARG_SYSTEM
},
803 { "user", no_argument
, NULL
, ARG_USER
},
804 { "test", no_argument
, NULL
, ARG_TEST
},
805 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
806 { "help", no_argument
, NULL
, 'h' },
807 { "version", no_argument
, NULL
, ARG_VERSION
},
808 { "dump-configuration-items", no_argument
, NULL
, ARG_DUMP_CONFIGURATION_ITEMS
},
809 { "dump-bus-properties", no_argument
, NULL
, ARG_DUMP_BUS_PROPERTIES
},
810 { "bus-introspect", required_argument
, NULL
, ARG_BUS_INTROSPECT
},
811 { "dump-core", optional_argument
, NULL
, ARG_DUMP_CORE
},
812 { "crash-chvt", required_argument
, NULL
, ARG_CRASH_CHVT
},
813 { "crash-shell", optional_argument
, NULL
, ARG_CRASH_SHELL
},
814 { "crash-reboot", optional_argument
, NULL
, ARG_CRASH_REBOOT
},
815 { "confirm-spawn", optional_argument
, NULL
, ARG_CONFIRM_SPAWN
},
816 { "show-status", optional_argument
, NULL
, ARG_SHOW_STATUS
},
817 { "deserialize", required_argument
, NULL
, ARG_DESERIALIZE
},
818 { "switched-root", no_argument
, NULL
, ARG_SWITCHED_ROOT
},
819 { "default-standard-output", required_argument
, NULL
, ARG_DEFAULT_STD_OUTPUT
, },
820 { "default-standard-error", required_argument
, NULL
, ARG_DEFAULT_STD_ERROR
, },
821 { "machine-id", required_argument
, NULL
, ARG_MACHINE_ID
},
822 { "service-watchdogs", required_argument
, NULL
, ARG_SERVICE_WATCHDOGS
},
827 bool user_arg_seen
= false;
832 if (getpid_cached() == 1)
835 while ((c
= getopt_long(argc
, argv
, "hDbsz:", options
, NULL
)) >= 0)
840 r
= log_set_max_level_from_string(optarg
);
842 return log_error_errno(r
, "Failed to parse log level \"%s\": %m", optarg
);
847 r
= log_set_target_from_string(optarg
);
849 return log_error_errno(r
, "Failed to parse log target \"%s\": %m", optarg
);
856 r
= log_show_color_from_string(optarg
);
858 return log_error_errno(r
, "Failed to parse log color setting \"%s\": %m",
861 log_show_color(true);
865 case ARG_LOG_LOCATION
:
867 r
= log_show_location_from_string(optarg
);
869 return log_error_errno(r
, "Failed to parse log location setting \"%s\": %m",
872 log_show_location(true);
879 r
= log_show_time_from_string(optarg
);
881 return log_error_errno(r
, "Failed to parse log time setting \"%s\": %m",
888 case ARG_DEFAULT_STD_OUTPUT
:
889 r
= exec_output_from_string(optarg
);
891 return log_error_errno(r
, "Failed to parse default standard output setting \"%s\": %m",
893 arg_default_std_output
= r
;
896 case ARG_DEFAULT_STD_ERROR
:
897 r
= exec_output_from_string(optarg
);
899 return log_error_errno(r
, "Failed to parse default standard error output setting \"%s\": %m",
901 arg_default_std_error
= r
;
905 r
= free_and_strdup(&arg_default_unit
, optarg
);
907 return log_error_errno(r
, "Failed to set default unit \"%s\": %m", optarg
);
917 user_arg_seen
= true;
921 arg_action
= ACTION_TEST
;
925 arg_pager_flags
|= PAGER_DISABLE
;
929 arg_action
= ACTION_VERSION
;
932 case ARG_DUMP_CONFIGURATION_ITEMS
:
933 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
936 case ARG_DUMP_BUS_PROPERTIES
:
937 arg_action
= ACTION_DUMP_BUS_PROPERTIES
;
940 case ARG_BUS_INTROSPECT
:
941 arg_bus_introspect
= optarg
;
942 arg_action
= ACTION_BUS_INTROSPECT
;
946 r
= parse_boolean_argument("--dump-core", optarg
, &arg_dump_core
);
952 r
= parse_crash_chvt(optarg
, &arg_crash_chvt
);
954 return log_error_errno(r
, "Failed to parse crash virtual terminal index: \"%s\": %m",
958 case ARG_CRASH_SHELL
:
959 r
= parse_boolean_argument("--crash-shell", optarg
, &arg_crash_shell
);
964 case ARG_CRASH_REBOOT
:
965 r
= parse_boolean_argument("--crash-reboot", optarg
, &arg_crash_reboot
);
970 case ARG_CONFIRM_SPAWN
:
971 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
973 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
975 return log_error_errno(r
, "Failed to parse confirm spawn option: \"%s\": %m",
979 case ARG_SERVICE_WATCHDOGS
:
980 r
= parse_boolean_argument("--service-watchdogs=", optarg
, &arg_service_watchdogs
);
985 case ARG_SHOW_STATUS
:
987 r
= parse_show_status(optarg
, &arg_show_status
);
989 return log_error_errno(r
, "Failed to parse show status boolean: \"%s\": %m",
992 arg_show_status
= SHOW_STATUS_YES
;
995 case ARG_DESERIALIZE
: {
999 r
= safe_atoi(optarg
, &fd
);
1001 log_error_errno(r
, "Failed to parse deserialize option \"%s\": %m", optarg
);
1003 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1004 "Invalid deserialize fd: %d",
1007 (void) fd_cloexec(fd
, true);
1009 f
= fdopen(fd
, "r");
1011 return log_error_errno(errno
, "Failed to open serialization fd %d: %m", fd
);
1013 safe_fclose(arg_serialization
);
1014 arg_serialization
= f
;
1019 case ARG_SWITCHED_ROOT
:
1020 arg_switched_root
= true;
1023 case ARG_MACHINE_ID
:
1024 r
= set_machine_id(optarg
);
1026 return log_error_errno(r
, "MachineID '%s' is not valid: %m", optarg
);
1030 arg_action
= ACTION_HELP
;
1034 log_set_max_level(LOG_DEBUG
);
1040 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1041 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1044 if (getpid_cached() != 1)
1050 assert_not_reached();
1053 if (optind
< argc
&& getpid_cached() != 1)
1054 /* Hmm, when we aren't run as init system let's complain about excess arguments */
1055 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Excess arguments.");
1057 if (arg_action
== ACTION_RUN
&& !arg_system
&& !user_arg_seen
)
1058 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1059 "Explicit --user argument required to run as user manager.");
1064 static int help(void) {
1065 _cleanup_free_
char *link
= NULL
;
1068 r
= terminal_urlify_man("systemd", "1", &link
);
1072 printf("%s [OPTIONS...]\n\n"
1073 "%sStarts and monitors system and user services.%s\n\n"
1074 "This program takes no positional arguments.\n\n"
1076 " -h --help Show this help\n"
1077 " --version Show version\n"
1078 " --test Determine initial transaction, dump it and exit\n"
1079 " --system Combined with --test: operate in system mode\n"
1080 " --user Combined with --test: operate in user mode\n"
1081 " --dump-configuration-items Dump understood unit configuration items\n"
1082 " --dump-bus-properties Dump exposed bus properties\n"
1083 " --bus-introspect=PATH Write XML introspection data\n"
1084 " --unit=UNIT Set default unit\n"
1085 " --dump-core[=BOOL] Dump core on crash\n"
1086 " --crash-vt=NR Change to specified VT on crash\n"
1087 " --crash-reboot[=BOOL] Reboot on crash\n"
1088 " --crash-shell[=BOOL] Run shell on crash\n"
1089 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1090 " --show-status[=BOOL] Show status updates on the console during boot\n"
1091 " --log-target=TARGET Set log target (console, journal, kmsg,\n"
1092 " journal-or-kmsg, null)\n"
1093 " --log-level=LEVEL Set log level (debug, info, notice, warning,\n"
1094 " err, crit, alert, emerg)\n"
1095 " --log-color[=BOOL] Highlight important log messages\n"
1096 " --log-location[=BOOL] Include code location in log messages\n"
1097 " --log-time[=BOOL] Prefix log messages with current time\n"
1098 " --default-standard-output= Set default standard output for services\n"
1099 " --default-standard-error= Set default standard error output for services\n"
1100 " --no-pager Do not pipe output into a pager\n"
1101 "\nSee the %s for details.\n",
1102 program_invocation_short_name
,
1112 static int prepare_reexecute(
1116 bool switching_root
) {
1118 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1119 _cleanup_fclose_
FILE *f
= NULL
;
1126 r
= manager_open_serialization(m
, &f
);
1128 return log_error_errno(r
, "Failed to create serialization file: %m");
1130 /* Make sure nothing is really destructed when we shut down */
1132 bus_manager_send_reloading(m
, true);
1138 r
= manager_serialize(m
, f
, fds
, switching_root
);
1142 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1143 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1145 r
= fd_cloexec(fileno(f
), false);
1147 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1149 r
= fdset_cloexec(fds
, false);
1151 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1153 *ret_f
= TAKE_PTR(f
);
1154 *ret_fds
= TAKE_PTR(fds
);
1159 static void bump_file_max_and_nr_open(void) {
1161 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
1162 * numbers of file descriptors are no longer a performance problem and their memory is properly
1163 * tracked by memcg, thus counting them and limiting them in another two layers of limits is
1164 * unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
1165 * on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
1167 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1171 #if BUMP_PROC_SYS_FS_FILE_MAX
1172 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
1173 * different, but the operation would fail silently.) */
1174 r
= sysctl_writef("fs/file-max", "%li\n", LONG_MAX
);
1176 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.file-max, ignoring: %m");
1179 #if BUMP_PROC_SYS_FS_NR_OPEN
1182 /* Argh! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know
1183 * what they are. The expression by which the maximum is determined is dependent on the architecture,
1184 * and is something we don't really want to copy to userspace, as it is dependent on implementation
1185 * details of the kernel. Since the kernel doesn't expose the maximum value to us, we can only try
1186 * and hope. Hence, let's start with INT_MAX, and then keep halving the value until we find one that
1187 * works. Ugly? Yes, absolutely, but kernel APIs are kernel APIs, so what do can we do... 🤯 */
1192 v
&= ~(__SIZEOF_POINTER__
- 1); /* Round down to next multiple of the pointer size */
1194 log_warning("Can't bump fs.nr_open, value too small.");
1200 log_error_errno(k
, "Failed to read fs.nr_open: %m");
1203 if (k
>= v
) { /* Already larger */
1204 log_debug("Skipping bump, value is already larger.");
1208 r
= sysctl_writef("fs/nr_open", "%i\n", v
);
1210 log_debug("Couldn't write fs.nr_open as %i, halving it.", v
);
1215 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.nr_open, ignoring: %m");
1219 log_debug("Successfully bumped fs.nr_open to %i", v
);
1225 static int bump_rlimit_nofile(const struct rlimit
*saved_rlimit
) {
1226 struct rlimit new_rlimit
;
1229 /* Get the underlying absolute limit the kernel enforces */
1230 nr
= read_nr_open();
1232 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1233 new_rlimit
= (struct rlimit
) {
1234 .rlim_cur
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_cur
),
1235 .rlim_max
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_max
),
1238 /* Shortcut if nothing changes. */
1239 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_max
&&
1240 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_cur
) {
1241 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1245 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1246 * both hard and soft. */
1247 r
= setrlimit_closest(RLIMIT_NOFILE
, &new_rlimit
);
1249 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1254 static int bump_rlimit_memlock(const struct rlimit
*saved_rlimit
) {
1255 struct rlimit new_rlimit
;
1259 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
1260 * which should normally disable such checks. We need them to implement IPAddressAllow= and
1261 * IPAddressDeny=, hence let's bump the value high enough for our user. */
1263 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1264 * must be unsigned, hence this is a given, but let's make this clear here. */
1265 assert_cc(RLIM_INFINITY
> 0);
1267 mm
= physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
1268 * physical RAM. We allow an eighth to be locked by us, just to
1271 new_rlimit
= (struct rlimit
) {
1272 .rlim_cur
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_cur
, mm
),
1273 .rlim_max
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_max
, mm
),
1276 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_cur
&&
1277 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_max
) {
1278 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1282 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &new_rlimit
);
1284 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1289 static void test_usr(void) {
1291 /* Check that /usr is either on the same file system as / or mounted already. */
1293 if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) <= 0)
1296 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1297 "Some things will probably break (sometimes even silently) in mysterious ways. "
1298 "Consult https://www.freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1301 static int enforce_syscall_archs(Set
*archs
) {
1305 if (!is_seccomp_available())
1308 r
= seccomp_restrict_archs(arg_syscall_archs
);
1310 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1315 static int status_welcome(void) {
1316 _cleanup_free_
char *pretty_name
= NULL
, *ansi_color
= NULL
;
1319 if (!show_status_on(arg_show_status
))
1322 r
= parse_os_release(NULL
,
1323 "PRETTY_NAME", &pretty_name
,
1324 "ANSI_COLOR", &ansi_color
);
1326 log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1327 "Failed to read os-release file, ignoring: %m");
1329 if (log_get_show_color())
1330 return status_printf(NULL
, 0,
1331 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1332 isempty(ansi_color
) ? "1" : ansi_color
,
1333 isempty(pretty_name
) ? "Linux" : pretty_name
);
1335 return status_printf(NULL
, 0,
1336 "\nWelcome to %s!\n",
1337 isempty(pretty_name
) ? "Linux" : pretty_name
);
1340 static int write_container_id(void) {
1342 int r
= 0; /* avoid false maybe-uninitialized warning */
1344 c
= getenv("container");
1348 RUN_WITH_UMASK(0022)
1349 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1351 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1356 static int bump_unix_max_dgram_qlen(void) {
1357 _cleanup_free_
char *qlen
= NULL
;
1361 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
1362 * the value really really early during boot, so that it is actually applied to all our sockets,
1363 * including the $NOTIFY_SOCKET one. */
1365 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1367 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1368 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1370 r
= safe_atolu(qlen
, &v
);
1372 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen
);
1374 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1377 r
= write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER
,
1378 "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN
);
1380 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1381 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1386 static int fixup_environment(void) {
1387 _cleanup_free_
char *term
= NULL
;
1391 /* Only fix up the environment when we are started as PID 1 */
1392 if (getpid_cached() != 1)
1395 /* We expect the environment to be set correctly if run inside a container. */
1396 if (detect_container() > 0)
1399 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
1400 * backend device used by the console. We try to make a better guess here since some consoles might
1401 * not have support for color mode for example.
1403 * However if TERM was configured through the kernel command line then leave it alone. */
1404 r
= proc_cmdline_get_key("TERM", 0, &term
);
1408 t
= term
?: default_term_for_tty("/dev/console");
1410 if (setenv("TERM", t
, 1) < 0)
1413 /* The kernels sets HOME=/ for init. Let's undo this. */
1414 if (path_equal_ptr(getenv("HOME"), "/"))
1415 assert_se(unsetenv("HOME") == 0);
1420 static void redirect_telinit(int argc
, char *argv
[]) {
1422 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1424 #if HAVE_SYSV_COMPAT
1425 if (getpid_cached() == 1)
1428 if (!invoked_as(argv
, "init"))
1431 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1432 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1437 static int become_shutdown(
1438 const char *shutdown_verb
,
1441 char log_level
[DECIMAL_STR_MAX(int) + 1],
1442 exit_code
[DECIMAL_STR_MAX(uint8_t) + 1],
1443 timeout
[DECIMAL_STR_MAX(usec_t
) + 1];
1445 const char* command_line
[13] = {
1446 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1448 "--timeout", timeout
,
1449 "--log-level", log_level
,
1453 _cleanup_strv_free_
char **env_block
= NULL
;
1454 usec_t watchdog_timer
= 0;
1458 assert(shutdown_verb
);
1459 assert(!command_line
[pos
]);
1460 env_block
= strv_copy(environ
);
1462 xsprintf(log_level
, "%d", log_get_max_level());
1463 xsprintf(timeout
, "%" PRI_USEC
"us", arg_default_timeout_stop_usec
);
1465 switch (log_get_target()) {
1467 case LOG_TARGET_KMSG
:
1468 case LOG_TARGET_JOURNAL_OR_KMSG
:
1469 case LOG_TARGET_SYSLOG_OR_KMSG
:
1470 command_line
[pos
++] = "kmsg";
1473 case LOG_TARGET_NULL
:
1474 command_line
[pos
++] = "null";
1477 case LOG_TARGET_CONSOLE
:
1479 command_line
[pos
++] = "console";
1483 if (log_get_show_color())
1484 command_line
[pos
++] = "--log-color";
1486 if (log_get_show_location())
1487 command_line
[pos
++] = "--log-location";
1489 if (log_get_show_time())
1490 command_line
[pos
++] = "--log-time";
1492 if (streq(shutdown_verb
, "exit")) {
1493 command_line
[pos
++] = "--exit-code";
1494 command_line
[pos
++] = exit_code
;
1495 xsprintf(exit_code
, "%d", retval
);
1498 assert(pos
< ELEMENTSOF(command_line
));
1500 if (streq(shutdown_verb
, "reboot"))
1501 watchdog_timer
= arg_reboot_watchdog
;
1502 else if (streq(shutdown_verb
, "kexec"))
1503 watchdog_timer
= arg_kexec_watchdog
;
1505 /* If we reboot or kexec let's set the shutdown watchdog and tell the
1506 * shutdown binary to repeatedly ping it.
1507 * Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
1508 (void) watchdog_setup_pretimeout(0);
1509 (void) watchdog_setup_pretimeout_governor(NULL
);
1510 r
= watchdog_setup(watchdog_timer
);
1511 watchdog_close(r
< 0);
1513 /* Tell the binary how often to ping, ignore failure */
1514 (void) strv_extendf(&env_block
, "WATCHDOG_USEC="USEC_FMT
, watchdog_timer
);
1516 if (arg_watchdog_device
)
1517 (void) strv_extendf(&env_block
, "WATCHDOG_DEVICE=%s", arg_watchdog_device
);
1519 /* Avoid the creation of new processes forked by the kernel; at this
1520 * point, we will not listen to the signals anyway */
1521 if (detect_container() <= 0)
1522 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1524 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1528 static void initialize_clock(void) {
1531 /* This is called very early on, before we parse the kernel command line or otherwise figure out why
1532 * we are running, but only once. */
1534 if (clock_is_localtime(NULL
) > 0) {
1537 /* The very first call of settimeofday() also does a time warp in the kernel.
1539 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
1540 * take care of maintaining the RTC and do all adjustments. This matches the behavior of
1541 * Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
1543 r
= clock_set_timezone(&min
);
1545 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1547 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1549 } else if (!in_initrd())
1551 * Do a dummy very first call to seal the kernel's time warp magic.
1553 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
1554 * LOCAL, but the real system could be set up that way. In such case, we need to delay the
1555 * time-warp or the sealing until we reach the real system.
1557 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
1558 * the time will jump or be incorrect at every daylight saving time change. All kernel local
1559 * time concepts will be treated as UTC that way.
1561 (void) clock_reset_timewarp();
1563 ClockChangeDirection change_dir
;
1564 r
= clock_apply_epoch(&change_dir
);
1565 if (r
> 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1566 log_info("System time before build time, advancing clock.");
1567 else if (r
> 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1568 log_info("System time is further ahead than %s after build time, resetting clock to build time.",
1569 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1570 else if (r
< 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1571 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1572 else if (r
< 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1573 log_error_errno(r
, "Current system time is further ahead %s after build time, but cannot correct: %m",
1574 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1577 static void apply_clock_update(void) {
1578 /* This is called later than initialize_clock(), i.e. after we parsed configuration files/kernel
1579 * command line and such. */
1581 if (arg_clock_usec
== 0)
1584 if (getpid_cached() != 1)
1587 if (clock_settime(CLOCK_REALTIME
, TIMESPEC_STORE(arg_clock_usec
)) < 0)
1588 log_error_errno(errno
, "Failed to set system clock to time specified on kernel command line: %m");
1590 log_info("Set system clock to %s, as specified on the kernel command line.",
1591 FORMAT_TIMESTAMP(arg_clock_usec
));
1594 static void cmdline_take_random_seed(void) {
1598 if (arg_random_seed_size
== 0)
1601 if (getpid_cached() != 1)
1604 assert(arg_random_seed
);
1605 suggested
= random_pool_size();
1607 if (arg_random_seed_size
< suggested
)
1608 log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
1609 arg_random_seed_size
, suggested
);
1611 r
= random_write_entropy(-1, arg_random_seed
, arg_random_seed_size
, true);
1613 log_warning_errno(r
, "Failed to credit entropy specified on kernel command line, ignoring: %m");
1617 log_notice("Successfully credited entropy passed on kernel command line.\n"
1618 "Note that the seed provided this way is accessible to unprivileged programs. "
1619 "This functionality should not be used outside of testing environments.");
1622 static void initialize_coredump(bool skip_setup
) {
1624 if (getpid_cached() != 1)
1627 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
1628 * the limit) will process core dumps for system services by default. */
1629 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1630 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1632 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1633 * until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
1634 * command line later so core dumps can still be generated during early startup and in initramfs. */
1636 disable_coredumps();
1640 static void initialize_core_pattern(bool skip_setup
) {
1643 if (skip_setup
|| !arg_early_core_pattern
)
1646 if (getpid_cached() != 1)
1649 r
= write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1651 log_warning_errno(r
, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1652 arg_early_core_pattern
);
1655 static void update_cpu_affinity(bool skip_setup
) {
1656 _cleanup_free_
char *mask
= NULL
;
1658 if (skip_setup
|| !arg_cpu_affinity
.set
)
1661 assert(arg_cpu_affinity
.allocated
> 0);
1663 mask
= cpu_set_to_range_string(&arg_cpu_affinity
);
1664 log_debug("Setting CPU affinity to {%s}.", strnull(mask
));
1666 if (sched_setaffinity(0, arg_cpu_affinity
.allocated
, arg_cpu_affinity
.set
) < 0)
1667 log_warning_errno(errno
, "Failed to set CPU affinity, ignoring: %m");
1670 static void update_numa_policy(bool skip_setup
) {
1672 _cleanup_free_
char *nodes
= NULL
;
1673 const char * policy
= NULL
;
1675 if (skip_setup
|| !mpol_is_valid(numa_policy_get_type(&arg_numa_policy
)))
1678 if (DEBUG_LOGGING
) {
1679 policy
= mpol_to_string(numa_policy_get_type(&arg_numa_policy
));
1680 nodes
= cpu_set_to_range_string(&arg_numa_policy
.nodes
);
1681 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy
), strnull(nodes
));
1684 r
= apply_numa_policy(&arg_numa_policy
);
1685 if (r
== -EOPNOTSUPP
)
1686 log_debug_errno(r
, "NUMA support not available, ignoring.");
1688 log_warning_errno(r
, "Failed to set NUMA memory policy, ignoring: %m");
1691 static void filter_args(
1700 /* Copy some filtered arguments into the dst array from src. */
1701 for (int i
= 1; i
< argc
; i
++) {
1702 if (STR_IN_SET(src
[i
],
1708 if (startswith(src
[i
], "--deserialize="))
1710 if (streq(src
[i
], "--deserialize")) {
1711 i
++; /* Skip the argument too */
1715 /* Skip target unit designators. We already acted upon this information and have queued
1716 * appropriate jobs. We don't want to redo all this after reexecution. */
1717 if (startswith(src
[i
], "--unit="))
1719 if (streq(src
[i
], "--unit")) {
1720 i
++; /* Skip the argument too */
1724 /* Seems we have a good old option. Let's pass it over to the new instance. */
1725 dst
[(*dst_index
)++] = src
[i
];
1729 static int do_reexecute(
1730 ManagerObjective objective
,
1733 const struct rlimit
*saved_rlimit_nofile
,
1734 const struct rlimit
*saved_rlimit_memlock
,
1736 const char *switch_root_dir
,
1737 const char *switch_root_init
,
1738 const char **ret_error_message
) {
1740 size_t i
, args_size
;
1744 assert(IN_SET(objective
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
));
1746 assert(saved_rlimit_nofile
);
1747 assert(saved_rlimit_memlock
);
1748 assert(ret_error_message
);
1750 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1751 * rebooted while we do that */
1752 watchdog_close(true);
1754 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1755 * the kernel default to its child processes */
1756 if (saved_rlimit_nofile
->rlim_cur
!= 0)
1757 (void) setrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
);
1758 if (saved_rlimit_memlock
->rlim_cur
!= RLIM_INFINITY
)
1759 (void) setrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
);
1761 if (switch_root_dir
) {
1762 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can
1763 * handle the SIGCHLD for them after deserializing. */
1764 broadcast_signal(SIGTERM
, false, true, arg_default_timeout_stop_usec
);
1766 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1767 r
= switch_root(switch_root_dir
, "/mnt", true, MS_MOVE
);
1769 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
1772 args_size
= argc
+ 6;
1773 args
= newa(const char*, args_size
);
1775 if (!switch_root_init
) {
1776 char sfd
[DECIMAL_STR_MAX(int)];
1778 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1779 * only if the user didn't specify an explicit init to spawn. */
1781 assert(arg_serialization
);
1784 xsprintf(sfd
, "%i", fileno(arg_serialization
));
1786 i
= 1; /* Leave args[0] empty for now. */
1787 filter_args(args
, &i
, argv
, argc
);
1789 if (switch_root_dir
)
1790 args
[i
++] = "--switched-root";
1791 args
[i
++] = arg_system
? "--system" : "--user";
1792 args
[i
++] = "--deserialize";
1796 assert(i
<= args_size
);
1799 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
1800 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
1801 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
1802 * and wait() for it in the parent, before proceeding into the exec().
1804 valgrind_summary_hack();
1806 args
[0] = SYSTEMD_BINARY_PATH
;
1807 (void) execv(args
[0], (char* const*) args
);
1809 if (objective
== MANAGER_REEXECUTE
) {
1810 *ret_error_message
= "Failed to execute our own binary";
1811 return log_error_errno(errno
, "Failed to execute our own binary %s: %m", args
[0]);
1814 log_debug_errno(errno
, "Failed to execute our own binary %s, trying fallback: %m", args
[0]);
1817 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
1818 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
1819 * but let's hope that doesn't matter.) */
1821 arg_serialization
= safe_fclose(arg_serialization
);
1822 fds
= fdset_free(fds
);
1824 /* Reopen the console */
1825 (void) make_console_stdio();
1827 i
= 1; /* Leave args[0] empty for now. */
1828 for (int j
= 1; j
<= argc
; j
++)
1829 args
[i
++] = argv
[j
];
1830 assert(i
<= args_size
);
1832 /* Re-enable any blocked signals, especially important if we switch from initial ramdisk to init=... */
1833 (void) reset_all_signal_handlers();
1834 (void) reset_signal_mask();
1835 (void) rlimit_nofile_safe();
1837 if (switch_root_init
) {
1838 args
[0] = switch_root_init
;
1839 (void) execve(args
[0], (char* const*) args
, saved_env
);
1840 log_warning_errno(errno
, "Failed to execute configured init %s, trying fallback: %m", args
[0]);
1843 args
[0] = "/sbin/init";
1844 (void) execv(args
[0], (char* const*) args
);
1847 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
1848 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
1849 "Failed to execute /sbin/init");
1851 *ret_error_message
= "Failed to execute fallback shell";
1853 log_warning("No /sbin/init, trying fallback");
1855 args
[0] = "/bin/sh";
1857 (void) execve(args
[0], (char* const*) args
, saved_env
);
1858 return log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
1860 return log_error_errno(r
, "Failed to execute /sbin/init, giving up: %m");
1863 static int invoke_main_loop(
1865 const struct rlimit
*saved_rlimit_nofile
,
1866 const struct rlimit
*saved_rlimit_memlock
,
1867 int *ret_retval
, /* Return parameters relevant for shutting down */
1868 const char **ret_shutdown_verb
, /* … */
1869 FDSet
**ret_fds
, /* Return parameters for reexecuting */
1870 char **ret_switch_root_dir
, /* … */
1871 char **ret_switch_root_init
, /* … */
1872 const char **ret_error_message
) {
1877 assert(saved_rlimit_nofile
);
1878 assert(saved_rlimit_memlock
);
1880 assert(ret_shutdown_verb
);
1882 assert(ret_switch_root_dir
);
1883 assert(ret_switch_root_init
);
1884 assert(ret_error_message
);
1887 int objective
= manager_loop(m
);
1888 if (objective
< 0) {
1889 *ret_error_message
= "Failed to run main loop";
1890 return log_emergency_errno(objective
, "Failed to run main loop: %m");
1893 switch (objective
) {
1895 case MANAGER_RELOAD
: {
1896 LogTarget saved_log_target
;
1897 int saved_log_level
;
1899 log_info("Reloading.");
1901 /* First, save any overridden log level/target, then parse the configuration file,
1902 * which might change the log level to new settings. */
1904 saved_log_level
= m
->log_level_overridden
? log_get_max_level() : -1;
1905 saved_log_target
= m
->log_target_overridden
? log_get_target() : _LOG_TARGET_INVALID
;
1907 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
1909 set_manager_defaults(m
);
1910 set_manager_settings(m
);
1912 update_cpu_affinity(false);
1913 update_numa_policy(false);
1915 if (saved_log_level
>= 0)
1916 manager_override_log_level(m
, saved_log_level
);
1917 if (saved_log_target
>= 0)
1918 manager_override_log_target(m
, saved_log_target
);
1920 if (manager_reload(m
) < 0)
1921 /* Reloading failed before the point of no return.
1922 * Let's continue running as if nothing happened. */
1923 m
->objective
= MANAGER_OK
;
1928 case MANAGER_REEXECUTE
:
1929 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, false);
1931 *ret_error_message
= "Failed to prepare for reexecution";
1935 log_notice("Reexecuting.");
1937 *ret_retval
= EXIT_SUCCESS
;
1938 *ret_shutdown_verb
= NULL
;
1939 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1943 case MANAGER_SWITCH_ROOT
:
1944 if (!m
->switch_root_init
) {
1945 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, true);
1947 *ret_error_message
= "Failed to prepare for reexecution";
1953 log_notice("Switching root.");
1955 *ret_retval
= EXIT_SUCCESS
;
1956 *ret_shutdown_verb
= NULL
;
1958 /* Steal the switch root parameters */
1959 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
1960 *ret_switch_root_init
= TAKE_PTR(m
->switch_root_init
);
1965 if (MANAGER_IS_USER(m
)) {
1968 *ret_retval
= m
->return_value
;
1969 *ret_shutdown_verb
= NULL
;
1971 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1977 case MANAGER_REBOOT
:
1978 case MANAGER_POWEROFF
:
1980 case MANAGER_KEXEC
: {
1981 static const char* const table
[_MANAGER_OBJECTIVE_MAX
] = {
1982 [MANAGER_EXIT
] = "exit",
1983 [MANAGER_REBOOT
] = "reboot",
1984 [MANAGER_POWEROFF
] = "poweroff",
1985 [MANAGER_HALT
] = "halt",
1986 [MANAGER_KEXEC
] = "kexec",
1989 log_notice("Shutting down.");
1991 *ret_retval
= m
->return_value
;
1992 assert_se(*ret_shutdown_verb
= table
[m
->objective
]);
1994 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2000 assert_not_reached();
2005 static void log_execution_mode(bool *ret_first_boot
) {
2006 assert(ret_first_boot
);
2012 log_info("systemd " GIT_VERSION
" running in %ssystem mode (%s)",
2013 arg_action
== ACTION_TEST
? "test " : "",
2016 v
= detect_virtualization();
2018 log_info("Detected virtualization %s.", virtualization_to_string(v
));
2020 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2023 *ret_first_boot
= false;
2024 log_info("Running in initial RAM disk.");
2027 _cleanup_free_
char *id_text
= NULL
;
2029 /* Let's check whether we are in first boot. We use /etc/machine-id as flag file
2030 * for this: If it is missing or contains the value "uninitialized", this is the
2031 * first boot. In any other case, it is not. This allows container managers and
2032 * installers to provision a couple of files already. If the container manager
2033 * wants to provision the machine ID itself it should pass $container_uuid to PID 1. */
2035 r
= read_one_line_file("/etc/machine-id", &id_text
);
2036 if (r
< 0 || streq(id_text
, "uninitialized")) {
2037 if (r
< 0 && r
!= -ENOENT
)
2038 log_warning_errno(r
, "Unexpected error while reading /etc/machine-id, ignoring: %m");
2040 *ret_first_boot
= true;
2041 log_info("Detected first boot.");
2043 *ret_first_boot
= false;
2044 log_debug("Detected initialized system, this is not the first boot.");
2048 assert_se(uname(&uts
) >= 0);
2050 if (strverscmp_improved(uts
.release
, KERNEL_BASELINE_VERSION
) < 0)
2051 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2052 "Your mileage may vary.", uts
.release
, KERNEL_BASELINE_VERSION
);
2054 log_debug("Kernel version %s, our baseline is %s", uts
.release
, KERNEL_BASELINE_VERSION
);
2056 if (DEBUG_LOGGING
) {
2057 _cleanup_free_
char *t
= NULL
;
2059 t
= uid_to_name(getuid());
2060 log_debug("systemd " GIT_VERSION
" running in %suser mode for user " UID_FMT
"/%s. (%s)",
2061 arg_action
== ACTION_TEST
? " test" : "",
2062 getuid(), strna(t
), systemd_features
);
2065 *ret_first_boot
= false;
2069 static int initialize_runtime(
2072 struct rlimit
*saved_rlimit_nofile
,
2073 struct rlimit
*saved_rlimit_memlock
,
2074 const char **ret_error_message
) {
2077 assert(ret_error_message
);
2079 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2081 * - Some only apply to --system instances
2082 * - Some only apply to --user instances
2083 * - Some only apply when we first start up, but not when we reexecute
2086 if (arg_action
!= ACTION_RUN
)
2089 update_cpu_affinity(skip_setup
);
2090 update_numa_policy(skip_setup
);
2093 /* Make sure we leave a core dump without panicking the kernel. */
2094 install_crash_handler();
2097 r
= mount_cgroup_controllers();
2099 *ret_error_message
= "Failed to mount cgroup hierarchies";
2104 (void) hostname_setup(true);
2105 /* Force transient machine-id on first boot. */
2106 machine_id_setup(NULL
, first_boot
, arg_machine_id
, NULL
);
2107 (void) loopback_setup();
2108 bump_unix_max_dgram_qlen();
2109 bump_file_max_and_nr_open();
2111 write_container_id();
2114 r
= watchdog_set_device(arg_watchdog_device
);
2116 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device
);
2118 _cleanup_free_
char *p
= NULL
;
2120 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2121 * user mode. In system mode mount_setup() already did that. */
2123 r
= xdg_user_runtime_dir(&p
, "/systemd");
2125 *ret_error_message
= "$XDG_RUNTIME_DIR is not set";
2126 return log_emergency_errno(r
, "Failed to determine $XDG_RUNTIME_DIR path: %m");
2129 (void) mkdir_p_label(p
, 0755);
2130 (void) make_inaccessible_nodes(p
, UID_INVALID
, GID_INVALID
);
2133 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
2134 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
2135 log_warning_errno(errno
, "Failed to adjust timer slack, ignoring: %m");
2137 if (arg_system
&& !cap_test_all(arg_capability_bounding_set
)) {
2138 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
2140 *ret_error_message
= "Failed to drop capability bounding set of usermode helpers";
2141 return log_emergency_errno(r
, "Failed to drop capability bounding set of usermode helpers: %m");
2144 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
2146 *ret_error_message
= "Failed to drop capability bounding set";
2147 return log_emergency_errno(r
, "Failed to drop capability bounding set: %m");
2151 if (arg_system
&& arg_no_new_privs
) {
2152 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2153 *ret_error_message
= "Failed to disable new privileges";
2154 return log_emergency_errno(errno
, "Failed to disable new privileges: %m");
2158 if (arg_syscall_archs
) {
2159 r
= enforce_syscall_archs(arg_syscall_archs
);
2161 *ret_error_message
= "Failed to set syscall architectures";
2167 /* Become reaper of our children */
2168 if (prctl(PR_SET_CHILD_SUBREAPER
, 1) < 0)
2169 log_warning_errno(errno
, "Failed to make us a subreaper, ignoring: %m");
2171 /* Bump up RLIMIT_NOFILE for systemd itself */
2172 (void) bump_rlimit_nofile(saved_rlimit_nofile
);
2173 (void) bump_rlimit_memlock(saved_rlimit_memlock
);
2175 /* Pull credentials from various sources into a common credential directory */
2176 if (arg_system
&& !skip_setup
)
2177 (void) import_credentials();
2182 static int do_queue_default_job(
2184 const char **ret_error_message
) {
2186 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2192 if (arg_default_unit
)
2193 unit
= arg_default_unit
;
2194 else if (in_initrd())
2195 unit
= SPECIAL_INITRD_TARGET
;
2197 unit
= SPECIAL_DEFAULT_TARGET
;
2199 log_debug("Activating default unit: %s", unit
);
2201 r
= manager_load_startable_unit_or_warn(m
, unit
, NULL
, &target
);
2202 if (r
< 0 && in_initrd() && !arg_default_unit
) {
2203 /* Fall back to default.target, which we used to always use by default. Only do this if no
2204 * explicit configuration was given. */
2206 log_info("Falling back to " SPECIAL_DEFAULT_TARGET
".");
2208 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_DEFAULT_TARGET
, NULL
, &target
);
2211 log_info("Falling back to " SPECIAL_RESCUE_TARGET
".");
2213 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_RESCUE_TARGET
, NULL
, &target
);
2215 *ret_error_message
= r
== -ERFKILL
? SPECIAL_RESCUE_TARGET
" masked"
2216 : "Failed to load " SPECIAL_RESCUE_TARGET
;
2221 assert(target
->load_state
== UNIT_LOADED
);
2223 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, NULL
, &error
, &job
);
2225 log_debug_errno(r
, "Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
2227 sd_bus_error_free(&error
);
2229 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, NULL
, &error
, &job
);
2231 *ret_error_message
= "Failed to start default target";
2232 return log_emergency_errno(r
, "Failed to start default target: %s", bus_error_message(&error
, r
));
2236 *ret_error_message
= "Failed to isolate default target";
2237 return log_emergency_errno(r
, "Failed to isolate default target: %s", bus_error_message(&error
, r
));
2239 log_info("Queued %s job for default target %s.",
2240 job_type_to_string(job
->type
),
2241 unit_status_string(job
->unit
, NULL
));
2243 m
->default_unit_job_id
= job
->id
;
2248 static void save_rlimits(struct rlimit
*saved_rlimit_nofile
,
2249 struct rlimit
*saved_rlimit_memlock
) {
2251 assert(saved_rlimit_nofile
);
2252 assert(saved_rlimit_memlock
);
2254 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
) < 0)
2255 log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2257 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
) < 0)
2258 log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2261 static void fallback_rlimit_nofile(const struct rlimit
*saved_rlimit_nofile
) {
2264 if (arg_default_rlimit
[RLIMIT_NOFILE
])
2267 /* Make sure forked processes get limits based on the original kernel setting */
2269 rl
= newdup(struct rlimit
, saved_rlimit_nofile
, 1);
2275 /* Bump the hard limit for system services to a substantially higher value. The default
2276 * hard limit current kernels set is pretty low (4K), mostly for historical
2277 * reasons. According to kernel developers, the fd handling in recent kernels has been
2278 * optimized substantially enough, so that we can bump the limit now, without paying too
2279 * high a price in memory or performance. Note however that we only bump the hard limit,
2280 * not the soft limit. That's because select() works the way it works, and chokes on fds
2281 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2282 * unexpecting programs that they get fds higher than what they can process using
2283 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2284 * this pitfall: programs that are written by folks aware of the select() problem in mind
2285 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2286 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2291 /* Get the underlying absolute limit the kernel enforces */
2292 nr
= read_nr_open();
2294 rl
->rlim_max
= MIN((rlim_t
) nr
, MAX(rl
->rlim_max
, (rlim_t
) HIGH_RLIMIT_NOFILE
));
2297 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2298 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2299 * instance), then lower what we pass on to not confuse our children */
2300 rl
->rlim_cur
= MIN(rl
->rlim_cur
, (rlim_t
) FD_SETSIZE
);
2302 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
2305 static void fallback_rlimit_memlock(const struct rlimit
*saved_rlimit_memlock
) {
2308 /* Pass the original value down to invoked processes */
2310 if (arg_default_rlimit
[RLIMIT_MEMLOCK
])
2313 rl
= newdup(struct rlimit
, saved_rlimit_memlock
, 1);
2320 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2321 * default for this since kernel 5.16) */
2322 rl
->rlim_max
= MAX(rl
->rlim_max
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2323 rl
->rlim_cur
= MAX(rl
->rlim_cur
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2326 arg_default_rlimit
[RLIMIT_MEMLOCK
] = rl
;
2329 static void setenv_manager_environment(void) {
2332 STRV_FOREACH(p
, arg_manager_environment
) {
2333 log_debug("Setting '%s' in our own environment.", *p
);
2335 r
= putenv_dup(*p
, true);
2337 log_warning_errno(errno
, "Failed to setenv \"%s\", ignoring: %m", *p
);
2341 static void reset_arguments(void) {
2342 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2344 arg_default_unit
= mfree(arg_default_unit
);
2346 /* arg_system — ignore */
2348 arg_dump_core
= true;
2349 arg_crash_chvt
= -1;
2350 arg_crash_shell
= false;
2351 arg_crash_reboot
= false;
2352 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2353 arg_show_status
= _SHOW_STATUS_INVALID
;
2354 arg_status_unit_format
= STATUS_UNIT_FORMAT_DEFAULT
;
2355 arg_switched_root
= false;
2356 arg_pager_flags
= 0;
2357 arg_service_watchdogs
= true;
2358 arg_default_std_output
= EXEC_OUTPUT_JOURNAL
;
2359 arg_default_std_error
= EXEC_OUTPUT_INHERIT
;
2360 arg_default_restart_usec
= DEFAULT_RESTART_USEC
;
2361 arg_default_timeout_start_usec
= DEFAULT_TIMEOUT_USEC
;
2362 arg_default_timeout_stop_usec
= DEFAULT_TIMEOUT_USEC
;
2363 arg_default_timeout_abort_usec
= DEFAULT_TIMEOUT_USEC
;
2364 arg_default_timeout_abort_set
= false;
2365 arg_default_start_limit_interval
= DEFAULT_START_LIMIT_INTERVAL
;
2366 arg_default_start_limit_burst
= DEFAULT_START_LIMIT_BURST
;
2367 arg_runtime_watchdog
= 0;
2368 arg_reboot_watchdog
= 10 * USEC_PER_MINUTE
;
2369 arg_kexec_watchdog
= 0;
2370 arg_pretimeout_watchdog
= 0;
2371 arg_early_core_pattern
= mfree(arg_early_core_pattern
);
2372 arg_watchdog_device
= mfree(arg_watchdog_device
);
2373 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
2375 arg_default_environment
= strv_free(arg_default_environment
);
2376 arg_manager_environment
= strv_free(arg_manager_environment
);
2377 rlimit_free_all(arg_default_rlimit
);
2379 arg_capability_bounding_set
= CAP_ALL
;
2380 arg_no_new_privs
= false;
2381 arg_timer_slack_nsec
= NSEC_INFINITY
;
2382 arg_default_timer_accuracy_usec
= 1 * USEC_PER_MINUTE
;
2384 arg_syscall_archs
= set_free(arg_syscall_archs
);
2386 /* arg_serialization — ignore */
2388 arg_default_cpu_accounting
= -1;
2389 arg_default_io_accounting
= false;
2390 arg_default_ip_accounting
= false;
2391 arg_default_blockio_accounting
= false;
2392 arg_default_memory_accounting
= MEMORY_ACCOUNTING_DEFAULT
;
2393 arg_default_tasks_accounting
= true;
2394 arg_default_tasks_max
= DEFAULT_TASKS_MAX
;
2395 arg_machine_id
= (sd_id128_t
) {};
2396 arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
2397 arg_default_oom_policy
= OOM_STOP
;
2399 cpu_set_reset(&arg_cpu_affinity
);
2400 numa_policy_reset(&arg_numa_policy
);
2402 arg_random_seed
= mfree(arg_random_seed
);
2403 arg_random_seed_size
= 0;
2406 arg_default_oom_score_adjust_set
= false;
2409 static void determine_default_oom_score_adjust(void) {
2412 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2413 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2416 if (arg_default_oom_score_adjust_set
)
2422 r
= get_oom_score_adjust(&a
);
2424 return (void) log_warning_errno(r
, "Failed to determine current OOM score adjustment value, ignoring: %m");
2426 assert_cc(100 <= OOM_SCORE_ADJ_MAX
);
2427 b
= a
>= OOM_SCORE_ADJ_MAX
- 100 ? OOM_SCORE_ADJ_MAX
: a
+ 100;
2432 arg_default_oom_score_adjust
= b
;
2433 arg_default_oom_score_adjust_set
= true;
2436 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
2437 const struct rlimit
*saved_rlimit_memlock
) {
2440 assert(saved_rlimit_nofile
);
2441 assert(saved_rlimit_memlock
);
2443 /* Assign configuration defaults */
2446 r
= parse_config_file();
2448 log_warning_errno(r
, "Failed to parse config file, ignoring: %m");
2451 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
2453 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2456 /* Initialize some default rlimits for services if they haven't been configured */
2457 fallback_rlimit_nofile(saved_rlimit_nofile
);
2458 fallback_rlimit_memlock(saved_rlimit_memlock
);
2460 /* Note that this also parses bits from the kernel command line, including "debug". */
2461 log_parse_environment();
2463 /* Initialize the show status setting if it hasn't been set explicitly yet */
2464 if (arg_show_status
== _SHOW_STATUS_INVALID
)
2465 arg_show_status
= SHOW_STATUS_YES
;
2467 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2468 determine_default_oom_score_adjust();
2470 /* Push variables into the manager environment block */
2471 setenv_manager_environment();
2473 /* Parse log environment variables again to take into account any new environment variables. */
2474 log_parse_environment();
2479 static int safety_checks(void) {
2481 if (getpid_cached() == 1 &&
2482 arg_action
!= ACTION_RUN
)
2483 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2484 "Unsupported execution mode while PID 1.");
2486 if (getpid_cached() == 1 &&
2488 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2489 "Can't run --user mode as PID 1.");
2491 if (arg_action
== ACTION_RUN
&&
2493 getpid_cached() != 1)
2494 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2495 "Can't run system mode unless PID 1.");
2497 if (arg_action
== ACTION_TEST
&&
2499 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2500 "Don't run test mode as root.");
2503 arg_action
== ACTION_RUN
&&
2505 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2506 "Trying to run as user instance, but the system has not been booted with systemd.");
2509 arg_action
== ACTION_RUN
&&
2510 !getenv("XDG_RUNTIME_DIR"))
2511 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH
),
2512 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2515 arg_action
== ACTION_RUN
&&
2516 running_in_chroot() > 0)
2517 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2518 "Cannot be run in a chroot() environment.");
2523 static int initialize_security(
2524 bool *loaded_policy
,
2525 dual_timestamp
*security_start_timestamp
,
2526 dual_timestamp
*security_finish_timestamp
,
2527 const char **ret_error_message
) {
2531 assert(loaded_policy
);
2532 assert(security_start_timestamp
);
2533 assert(security_finish_timestamp
);
2534 assert(ret_error_message
);
2536 dual_timestamp_get(security_start_timestamp
);
2538 r
= mac_selinux_setup(loaded_policy
);
2540 *ret_error_message
= "Failed to load SELinux policy";
2544 r
= mac_smack_setup(loaded_policy
);
2546 *ret_error_message
= "Failed to load SMACK policy";
2550 r
= mac_apparmor_setup();
2552 *ret_error_message
= "Failed to load AppArmor policy";
2558 *ret_error_message
= "Failed to load IMA policy";
2562 dual_timestamp_get(security_finish_timestamp
);
2566 static int collect_fds(FDSet
**ret_fds
, const char **ret_error_message
) {
2570 assert(ret_error_message
);
2572 r
= fdset_new_fill(ret_fds
);
2574 *ret_error_message
= "Failed to allocate fd set";
2575 return log_emergency_errno(r
, "Failed to allocate fd set: %m");
2578 fdset_cloexec(*ret_fds
, true);
2580 if (arg_serialization
)
2581 assert_se(fdset_remove(*ret_fds
, fileno(arg_serialization
)) >= 0);
2586 static void setup_console_terminal(bool skip_setup
) {
2591 /* Become a session leader if we aren't one yet. */
2594 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2595 * controlling tty. */
2596 (void) release_terminal();
2598 /* Reset the console, but only if this is really init and we are freshly booted */
2599 if (getpid_cached() == 1 && !skip_setup
)
2600 (void) console_setup();
2603 static bool early_skip_setup_check(int argc
, char *argv
[]) {
2604 bool found_deserialize
= false;
2606 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2607 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2608 * special setup things anyway, even if in that case we also do deserialization. */
2610 for (int i
= 1; i
< argc
; i
++)
2611 if (streq(argv
[i
], "--switched-root"))
2612 return false; /* If we switched root, don't skip the setup. */
2613 else if (streq(argv
[i
], "--deserialize"))
2614 found_deserialize
= true;
2616 return found_deserialize
; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2619 static int save_env(void) {
2622 l
= strv_copy(environ
);
2626 strv_free_and_replace(saved_env
, l
);
2630 int main(int argc
, char *argv
[]) {
2632 initrd_timestamp
= DUAL_TIMESTAMP_NULL
,
2633 userspace_timestamp
= DUAL_TIMESTAMP_NULL
,
2634 kernel_timestamp
= DUAL_TIMESTAMP_NULL
,
2635 security_start_timestamp
= DUAL_TIMESTAMP_NULL
,
2636 security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
2637 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0),
2638 saved_rlimit_memlock
= RLIMIT_MAKE_CONST(RLIM_INFINITY
); /* The original rlimits we passed
2639 * in. Note we use different values
2640 * for the two that indicate whether
2641 * these fields are initialized! */
2642 bool skip_setup
, loaded_policy
= false, queue_default_job
= false, first_boot
= false;
2643 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
2644 usec_t before_startup
, after_startup
;
2645 static char systemd
[] = "systemd";
2646 const char *shutdown_verb
= NULL
, *error_message
= NULL
;
2647 int r
, retval
= EXIT_FAILURE
;
2651 assert_se(argc
> 0 && !isempty(argv
[0]));
2653 /* SysV compatibility: redirect init → telinit */
2654 redirect_telinit(argc
, argv
);
2656 /* Take timestamps early on */
2657 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
2658 dual_timestamp_get(&userspace_timestamp
);
2660 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2662 skip_setup
= early_skip_setup_check(argc
, argv
);
2664 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2665 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2667 program_invocation_short_name
= systemd
;
2668 (void) prctl(PR_SET_NAME
, systemd
);
2670 /* Save the original command line */
2671 save_argc_argv(argc
, argv
);
2673 /* Save the original environment as we might need to restore it if we're requested to execute another
2674 * system manager later. */
2677 error_message
= "Failed to copy environment block";
2681 /* Make sure that if the user says "syslog" we actually log to the journal. */
2682 log_set_upgrade_syslog_to_journal(true);
2684 if (getpid_cached() == 1) {
2685 /* When we run as PID 1 force system mode */
2688 /* Disable the umask logic */
2691 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2692 * not be activated yet (even though the log socket for it exists). */
2693 log_set_prohibit_ipc(true);
2695 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
2696 * is important so that we never end up logging to any foreign stderr, for example if we have
2697 * to log in a child process right before execve()'ing the actual binary, at a point in time
2698 * where socket activation stderr/stdout area already set up. */
2699 log_set_always_reopen_console(true);
2701 if (detect_container() <= 0) {
2703 /* Running outside of a container as PID 1 */
2704 log_set_target(LOG_TARGET_KMSG
);
2708 initrd_timestamp
= userspace_timestamp
;
2711 r
= mount_setup_early();
2713 error_message
= "Failed to mount early API filesystems";
2717 /* Let's open the log backend a second time, in case the first time didn't
2718 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2719 * available, and it previously wasn't. */
2722 disable_printk_ratelimit();
2724 r
= initialize_security(
2726 &security_start_timestamp
,
2727 &security_finish_timestamp
,
2733 if (mac_selinux_init() < 0) {
2734 error_message
= "Failed to initialize SELinux support";
2741 /* Set the default for later on, but don't actually open the logs like this for
2742 * now. Note that if we are transitioning from the initrd there might still be
2743 * journal fd open, and we shouldn't attempt opening that before we parsed
2744 * /proc/cmdline which might redirect output elsewhere. */
2745 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
2748 /* Running inside a container, as PID 1 */
2749 log_set_target(LOG_TARGET_CONSOLE
);
2752 /* For later on, see above... */
2753 log_set_target(LOG_TARGET_JOURNAL
);
2755 /* clear the kernel timestamp, because we are in a container */
2756 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2759 initialize_coredump(skip_setup
);
2761 r
= fixup_environment();
2763 log_emergency_errno(r
, "Failed to fix up PID 1 environment: %m");
2764 error_message
= "Failed to fix up PID1 environment";
2768 /* Try to figure out if we can use colors with the console. No need to do that for user
2769 * instances since they never log into the console. */
2770 log_show_color(colors_enabled());
2772 r
= make_null_stdio();
2774 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2776 /* Load the kernel modules early. */
2778 (void) kmod_setup();
2780 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
2781 r
= mount_setup(loaded_policy
, skip_setup
);
2783 error_message
= "Failed to mount API filesystems";
2787 /* The efivarfs is now mounted, let's read the random seed off it */
2788 (void) efi_take_random_seed();
2790 /* Cache command-line options passed from EFI variables */
2792 (void) cache_efi_options_variable();
2794 /* Running as user instance */
2796 log_set_target(LOG_TARGET_AUTO
);
2799 /* clear the kernel timestamp, because we are not PID 1 */
2800 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2802 if (mac_selinux_init() < 0) {
2803 error_message
= "Failed to initialize SELinux support";
2808 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2809 * transitioning from the initrd to the main systemd or suchlike. */
2810 save_rlimits(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2812 /* Reset all signal handlers. */
2813 (void) reset_all_signal_handlers();
2814 (void) ignore_signals(SIGNALS_IGNORE
);
2816 (void) parse_configuration(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2818 r
= parse_argv(argc
, argv
);
2820 error_message
= "Failed to parse commandline arguments";
2824 r
= safety_checks();
2828 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
, ACTION_DUMP_CONFIGURATION_ITEMS
, ACTION_DUMP_BUS_PROPERTIES
, ACTION_BUS_INTROSPECT
))
2829 pager_open(arg_pager_flags
);
2831 if (arg_action
!= ACTION_RUN
)
2834 if (arg_action
== ACTION_HELP
) {
2835 retval
= help() < 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2837 } else if (arg_action
== ACTION_VERSION
) {
2840 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
2841 unit_dump_config_items(stdout
);
2842 retval
= EXIT_SUCCESS
;
2844 } else if (arg_action
== ACTION_DUMP_BUS_PROPERTIES
) {
2845 dump_bus_properties(stdout
);
2846 retval
= EXIT_SUCCESS
;
2848 } else if (arg_action
== ACTION_BUS_INTROSPECT
) {
2849 r
= bus_manager_introspect_implementations(stdout
, arg_bus_introspect
);
2850 retval
= r
>= 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
2854 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
2856 /* Move out of the way, so that we won't block unmounts */
2857 assert_se(chdir("/") == 0);
2859 if (arg_action
== ACTION_RUN
) {
2861 /* Apply the systemd.clock_usec= kernel command line switch */
2862 apply_clock_update();
2864 /* Apply random seed from kernel command line */
2865 cmdline_take_random_seed();
2868 /* A core pattern might have been specified via the cmdline. */
2869 initialize_core_pattern(skip_setup
);
2871 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
2874 /* Remember open file descriptors for later deserialization */
2875 r
= collect_fds(&fds
, &error_message
);
2879 /* Give up any control of the console, but make sure its initialized. */
2880 setup_console_terminal(skip_setup
);
2882 /* Open the logging devices, if possible and necessary */
2886 log_execution_mode(&first_boot
);
2888 r
= initialize_runtime(skip_setup
,
2890 &saved_rlimit_nofile
,
2891 &saved_rlimit_memlock
,
2896 r
= manager_new(arg_system
? LOOKUP_SCOPE_SYSTEM
: LOOKUP_SCOPE_USER
,
2897 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
2900 log_emergency_errno(r
, "Failed to allocate manager object: %m");
2901 error_message
= "Failed to allocate manager object";
2905 m
->timestamps
[MANAGER_TIMESTAMP_KERNEL
] = kernel_timestamp
;
2906 m
->timestamps
[MANAGER_TIMESTAMP_INITRD
] = initrd_timestamp
;
2907 m
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
] = userspace_timestamp
;
2908 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START
)] = security_start_timestamp
;
2909 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH
)] = security_finish_timestamp
;
2911 set_manager_defaults(m
);
2912 set_manager_settings(m
);
2913 manager_set_first_boot(m
, first_boot
);
2915 /* Remember whether we should queue the default job */
2916 queue_default_job
= !arg_serialization
|| arg_switched_root
;
2918 before_startup
= now(CLOCK_MONOTONIC
);
2920 r
= manager_startup(m
, arg_serialization
, fds
, /* root= */ NULL
);
2922 error_message
= "Failed to start up manager";
2926 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2927 fds
= fdset_free(fds
);
2928 arg_serialization
= safe_fclose(arg_serialization
);
2930 if (queue_default_job
) {
2931 r
= do_queue_default_job(m
, &error_message
);
2936 after_startup
= now(CLOCK_MONOTONIC
);
2938 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
2939 "Loaded units and determined initial transaction in %s.",
2940 FORMAT_TIMESPAN(after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
2942 if (arg_action
== ACTION_TEST
) {
2943 manager_test_summary(m
);
2944 retval
= EXIT_SUCCESS
;
2948 r
= invoke_main_loop(m
,
2949 &saved_rlimit_nofile
,
2950 &saved_rlimit_memlock
,
2957 assert(r
< 0 || IN_SET(r
, MANAGER_EXIT
, /* MANAGER_OK is not expected here. */
2964 MANAGER_SWITCH_ROOT
));
2970 arg_reboot_watchdog
= manager_get_watchdog(m
, WATCHDOG_REBOOT
);
2971 arg_kexec_watchdog
= manager_get_watchdog(m
, WATCHDOG_KEXEC
);
2972 m
= manager_free(m
);
2975 mac_selinux_finish();
2977 if (IN_SET(r
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
))
2980 &saved_rlimit_nofile
,
2981 &saved_rlimit_memlock
,
2985 &error_message
); /* This only returns if reexecution failed */
2987 arg_serialization
= safe_fclose(arg_serialization
);
2988 fds
= fdset_free(fds
);
2990 saved_env
= strv_free(saved_env
);
2992 #if HAVE_VALGRIND_VALGRIND_H
2993 /* If we are PID 1 and running under valgrind, then let's exit
2994 * here explicitly. valgrind will only generate nice output on
2995 * exit(), not on exec(), hence let's do the former not the
2997 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
2998 /* Cleanup watchdog_device strings for valgrind. We need them
2999 * in become_shutdown() so normally we cannot free them yet. */
3000 watchdog_free_device();
3006 #if HAS_FEATURE_ADDRESS_SANITIZER
3007 __lsan_do_leak_check();
3010 /* Try to invoke the shutdown binary unless we already failed.
3011 * If we failed above, we want to freeze after finishing cleanup. */
3012 if (r
>= 0 && shutdown_verb
) {
3013 r
= become_shutdown(shutdown_verb
, retval
);
3014 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3015 error_message
= "Failed to execute shutdown binary";
3018 watchdog_free_device();
3019 arg_watchdog_device
= mfree(arg_watchdog_device
);
3021 if (getpid_cached() == 1) {
3023 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
3024 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
3025 "%s.", error_message
);
3026 freeze_or_exit_or_reboot();