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 usec_t arg_default_device_timeout_usec
;
138 static bool arg_default_timeout_abort_set
;
139 static usec_t arg_default_start_limit_interval
;
140 static unsigned arg_default_start_limit_burst
;
141 static usec_t arg_runtime_watchdog
;
142 static usec_t arg_reboot_watchdog
;
143 static usec_t arg_kexec_watchdog
;
144 static usec_t arg_pretimeout_watchdog
;
145 static char *arg_early_core_pattern
;
146 static char *arg_watchdog_pretimeout_governor
;
147 static char *arg_watchdog_device
;
148 static char **arg_default_environment
;
149 static char **arg_manager_environment
;
150 static struct rlimit
*arg_default_rlimit
[_RLIMIT_MAX
];
151 static uint64_t arg_capability_bounding_set
;
152 static bool arg_no_new_privs
;
153 static nsec_t arg_timer_slack_nsec
;
154 static usec_t arg_default_timer_accuracy_usec
;
155 static Set
* arg_syscall_archs
;
156 static FILE* arg_serialization
;
157 static int arg_default_cpu_accounting
;
158 static bool arg_default_io_accounting
;
159 static bool arg_default_ip_accounting
;
160 static bool arg_default_blockio_accounting
;
161 static bool arg_default_memory_accounting
;
162 static bool arg_default_tasks_accounting
;
163 static TasksMax arg_default_tasks_max
;
164 static sd_id128_t arg_machine_id
;
165 static EmergencyAction arg_cad_burst_action
;
166 static OOMPolicy arg_default_oom_policy
;
167 static CPUSet arg_cpu_affinity
;
168 static NUMAPolicy arg_numa_policy
;
169 static usec_t arg_clock_usec
;
170 static void *arg_random_seed
;
171 static size_t arg_random_seed_size
;
172 static int arg_default_oom_score_adjust
;
173 static bool arg_default_oom_score_adjust_set
;
174 static char *arg_default_smack_process_label
;
176 /* A copy of the original environment block */
177 static char **saved_env
= NULL
;
179 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
180 const struct rlimit
*saved_rlimit_memlock
);
182 static int manager_find_user_config_paths(char ***ret_files
, char ***ret_dirs
) {
183 _cleanup_free_
char *base
= NULL
;
184 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
187 r
= xdg_user_config_dir(&base
, "/systemd");
191 r
= strv_extendf(&files
, "%s/user.conf", base
);
195 r
= strv_extend(&files
, PKGSYSCONFDIR
"/user.conf");
199 r
= strv_consume(&dirs
, TAKE_PTR(base
));
203 r
= strv_extend_strv(&dirs
, CONF_PATHS_STRV("systemd"), false);
207 *ret_files
= TAKE_PTR(files
);
208 *ret_dirs
= TAKE_PTR(dirs
);
212 static int console_setup(void) {
213 _cleanup_close_
int tty_fd
= -1;
216 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
218 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
220 /* We don't want to force text mode. plymouth may be showing
221 * pictures already from initrd. */
222 r
= reset_terminal_fd(tty_fd
, false);
224 return log_error_errno(r
, "Failed to reset /dev/console: %m");
229 static int set_machine_id(const char *m
) {
233 if (sd_id128_from_string(m
, &t
) < 0)
236 if (sd_id128_is_null(t
))
243 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
248 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
250 if (proc_cmdline_value_missing(key
, value
))
253 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
254 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
255 else if (in_initrd() == !!startswith(key
, "rd."))
256 return free_and_strdup_warn(&arg_default_unit
, value
);
258 } else if (proc_cmdline_key_streq(key
, "systemd.dump_core")) {
260 r
= value
? parse_boolean(value
) : true;
262 log_warning_errno(r
, "Failed to parse dump core switch %s, ignoring: %m", value
);
266 } else if (proc_cmdline_key_streq(key
, "systemd.early_core_pattern")) {
268 if (proc_cmdline_value_missing(key
, value
))
271 if (path_is_absolute(value
))
272 (void) parse_path_argument(value
, false, &arg_early_core_pattern
);
274 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value
);
276 } else if (proc_cmdline_key_streq(key
, "systemd.crash_chvt")) {
279 arg_crash_chvt
= 0; /* turn on */
281 r
= parse_crash_chvt(value
, &arg_crash_chvt
);
283 log_warning_errno(r
, "Failed to parse crash chvt switch %s, ignoring: %m", value
);
286 } else if (proc_cmdline_key_streq(key
, "systemd.crash_shell")) {
288 r
= value
? parse_boolean(value
) : true;
290 log_warning_errno(r
, "Failed to parse crash shell switch %s, ignoring: %m", value
);
294 } else if (proc_cmdline_key_streq(key
, "systemd.crash_reboot")) {
296 r
= value
? parse_boolean(value
) : true;
298 log_warning_errno(r
, "Failed to parse crash reboot switch %s, ignoring: %m", value
);
300 arg_crash_reboot
= r
;
302 } else if (proc_cmdline_key_streq(key
, "systemd.confirm_spawn")) {
305 r
= parse_confirm_spawn(value
, &s
);
307 log_warning_errno(r
, "Failed to parse confirm_spawn switch %s, ignoring: %m", value
);
309 free_and_replace(arg_confirm_spawn
, s
);
311 } else if (proc_cmdline_key_streq(key
, "systemd.service_watchdogs")) {
313 r
= value
? parse_boolean(value
) : true;
315 log_warning_errno(r
, "Failed to parse service watchdog switch %s, ignoring: %m", value
);
317 arg_service_watchdogs
= r
;
319 } else if (proc_cmdline_key_streq(key
, "systemd.show_status")) {
322 r
= parse_show_status(value
, &arg_show_status
);
324 log_warning_errno(r
, "Failed to parse show status switch %s, ignoring: %m", value
);
326 arg_show_status
= SHOW_STATUS_YES
;
328 } else if (proc_cmdline_key_streq(key
, "systemd.status_unit_format")) {
330 if (proc_cmdline_value_missing(key
, value
))
333 r
= status_unit_format_from_string(value
);
335 log_warning_errno(r
, "Failed to parse %s=%s, ignoring: %m", key
, value
);
337 arg_status_unit_format
= r
;
339 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_output")) {
341 if (proc_cmdline_value_missing(key
, value
))
344 r
= exec_output_from_string(value
);
346 log_warning_errno(r
, "Failed to parse default standard output switch %s, ignoring: %m", value
);
348 arg_default_std_output
= r
;
350 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_error")) {
352 if (proc_cmdline_value_missing(key
, value
))
355 r
= exec_output_from_string(value
);
357 log_warning_errno(r
, "Failed to parse default standard error switch %s, ignoring: %m", value
);
359 arg_default_std_error
= r
;
361 } else if (streq(key
, "systemd.setenv")) {
363 if (proc_cmdline_value_missing(key
, value
))
366 if (!env_assignment_is_valid(value
))
367 log_warning("Environment variable assignment '%s' is not valid. Ignoring.", value
);
369 r
= strv_env_replace_strdup(&arg_default_environment
, value
);
374 } else if (proc_cmdline_key_streq(key
, "systemd.machine_id")) {
376 if (proc_cmdline_value_missing(key
, value
))
379 r
= set_machine_id(value
);
381 log_warning_errno(r
, "MachineID '%s' is not valid, ignoring: %m", value
);
383 } else if (proc_cmdline_key_streq(key
, "systemd.default_timeout_start_sec")) {
385 if (proc_cmdline_value_missing(key
, value
))
388 r
= parse_sec(value
, &arg_default_timeout_start_usec
);
390 log_warning_errno(r
, "Failed to parse default start timeout '%s', ignoring: %m", value
);
392 if (arg_default_timeout_start_usec
<= 0)
393 arg_default_timeout_start_usec
= USEC_INFINITY
;
395 } else if (proc_cmdline_key_streq(key
, "systemd.cpu_affinity")) {
397 if (proc_cmdline_value_missing(key
, value
))
400 r
= parse_cpu_set(value
, &arg_cpu_affinity
);
402 log_warning_errno(r
, "Failed to parse CPU affinity mask '%s', ignoring: %m", value
);
404 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_device")) {
406 if (proc_cmdline_value_missing(key
, value
))
409 (void) parse_path_argument(value
, false, &arg_watchdog_device
);
411 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_sec")) {
413 if (proc_cmdline_value_missing(key
, value
))
416 if (streq(value
, "default"))
417 arg_runtime_watchdog
= USEC_INFINITY
;
418 else if (streq(value
, "off"))
419 arg_runtime_watchdog
= 0;
421 r
= parse_sec(value
, &arg_runtime_watchdog
);
423 log_warning_errno(r
, "Failed to parse systemd.watchdog_sec= argument '%s', ignoring: %m", value
);
428 arg_kexec_watchdog
= arg_reboot_watchdog
= arg_runtime_watchdog
;
430 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pre_sec")) {
432 if (proc_cmdline_value_missing(key
, value
))
435 if (streq(value
, "default"))
436 arg_pretimeout_watchdog
= USEC_INFINITY
;
437 else if (streq(value
, "off"))
438 arg_pretimeout_watchdog
= 0;
440 r
= parse_sec(value
, &arg_pretimeout_watchdog
);
442 log_warning_errno(r
, "Failed to parse systemd.watchdog_pre_sec= argument '%s', ignoring: %m", value
);
447 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pretimeout_governor")) {
449 if (proc_cmdline_value_missing(key
, value
) || isempty(value
)) {
450 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
454 if (!string_is_safe(value
)) {
455 log_warning("Watchdog pretimeout governor '%s' is not valid, ignoring.", value
);
459 return free_and_strdup_warn(&arg_watchdog_pretimeout_governor
, value
);
461 } else if (proc_cmdline_key_streq(key
, "systemd.clock_usec")) {
463 if (proc_cmdline_value_missing(key
, value
))
466 r
= safe_atou64(value
, &arg_clock_usec
);
468 log_warning_errno(r
, "Failed to parse systemd.clock_usec= argument, ignoring: %s", value
);
470 } else if (proc_cmdline_key_streq(key
, "systemd.random_seed")) {
474 if (proc_cmdline_value_missing(key
, value
))
477 r
= unbase64mem(value
, SIZE_MAX
, &p
, &sz
);
479 log_warning_errno(r
, "Failed to parse systemd.random_seed= argument, ignoring: %s", value
);
481 free(arg_random_seed
);
482 arg_random_seed
= sz
> 0 ? p
: mfree(p
);
483 arg_random_seed_size
= sz
;
485 } else if (streq(key
, "quiet") && !value
) {
487 if (arg_show_status
== _SHOW_STATUS_INVALID
)
488 arg_show_status
= SHOW_STATUS_ERROR
;
490 } else if (streq(key
, "debug") && !value
) {
492 /* Note that log_parse_environment() handles 'debug'
493 * too, and sets the log level to LOG_DEBUG. */
495 if (detect_container() > 0)
496 log_set_target(LOG_TARGET_CONSOLE
);
501 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
502 target
= runlevel_to_target(key
);
504 return free_and_strdup_warn(&arg_default_unit
, target
);
510 #define DEFINE_SETTER(name, func, descr) \
511 static int name(const char *unit, \
512 const char *filename, \
514 const char *section, \
515 unsigned section_line, \
516 const char *lvalue, \
518 const char *rvalue, \
530 log_syntax(unit, LOG_ERR, filename, line, r, \
531 "Invalid " descr "'%s': %m", \
537 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level");
538 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target");
539 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color");
540 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location");
541 DEFINE_SETTER(config_parse_time
, log_show_time_from_string
, "time");
543 static int config_parse_default_timeout_abort(
545 const char *filename
,
548 unsigned section_line
,
556 r
= config_parse_timeout_abort(unit
, filename
, line
, section
, section_line
, lvalue
, ltype
, rvalue
,
557 &arg_default_timeout_abort_usec
, userdata
);
559 arg_default_timeout_abort_set
= r
;
563 static int config_parse_oom_score_adjust(
565 const char *filename
,
568 unsigned section_line
,
577 if (isempty(rvalue
)) {
578 arg_default_oom_score_adjust_set
= false;
582 r
= parse_oom_score_adjust(rvalue
, &oa
);
584 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse the OOM score adjust value '%s', ignoring: %m", rvalue
);
588 arg_default_oom_score_adjust
= oa
;
589 arg_default_oom_score_adjust_set
= true;
594 static int parse_config_file(void) {
595 const ConfigTableItem items
[] = {
596 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
597 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
598 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
599 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
600 { "Manager", "LogTime", config_parse_time
, 0, NULL
},
601 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
602 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, &arg_crash_chvt
},
603 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, &arg_crash_chvt
},
604 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
605 { "Manager", "CrashReboot", config_parse_bool
, 0, &arg_crash_reboot
},
606 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
607 { "Manager", "StatusUnitFormat", config_parse_status_unit_format
, 0, &arg_status_unit_format
},
608 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, &arg_cpu_affinity
},
609 { "Manager", "NUMAPolicy", config_parse_numa_policy
, 0, &arg_numa_policy
.type
},
610 { "Manager", "NUMAMask", config_parse_numa_mask
, 0, &arg_numa_policy
},
611 { "Manager", "JoinControllers", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
612 { "Manager", "RuntimeWatchdogSec", config_parse_watchdog_sec
, 0, &arg_runtime_watchdog
},
613 { "Manager", "RuntimeWatchdogPreSec", config_parse_watchdog_sec
, 0, &arg_pretimeout_watchdog
},
614 { "Manager", "RebootWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
},
615 { "Manager", "ShutdownWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
}, /* obsolete alias */
616 { "Manager", "KExecWatchdogSec", config_parse_watchdog_sec
, 0, &arg_kexec_watchdog
},
617 { "Manager", "WatchdogDevice", config_parse_path
, 0, &arg_watchdog_device
},
618 { "Manager", "RuntimeWatchdogPreGovernor", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &arg_watchdog_pretimeout_governor
},
619 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
620 { "Manager", "NoNewPrivileges", config_parse_bool
, 0, &arg_no_new_privs
},
622 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
624 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
625 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_default_timer_accuracy_usec
},
626 { "Manager", "DefaultStandardOutput", config_parse_output_restricted
, 0, &arg_default_std_output
},
627 { "Manager", "DefaultStandardError", config_parse_output_restricted
, 0, &arg_default_std_error
},
628 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_default_timeout_start_usec
},
629 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_default_timeout_stop_usec
},
630 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort
, 0, NULL
},
631 { "Manager", "DefaultDeviceTimeoutSec", config_parse_sec
, 0, &arg_default_device_timeout_usec
},
632 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_default_restart_usec
},
633 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_default_start_limit_interval
}, /* obsolete alias */
634 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec
, 0, &arg_default_start_limit_interval
},
635 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_default_start_limit_burst
},
636 { "Manager", "DefaultEnvironment", config_parse_environ
, 0, &arg_default_environment
},
637 { "Manager", "ManagerEnvironment", config_parse_environ
, 0, &arg_manager_environment
},
638 { "Manager", "DefaultLimitCPU", config_parse_rlimit
, RLIMIT_CPU
, arg_default_rlimit
},
639 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit
, RLIMIT_FSIZE
, arg_default_rlimit
},
640 { "Manager", "DefaultLimitDATA", config_parse_rlimit
, RLIMIT_DATA
, arg_default_rlimit
},
641 { "Manager", "DefaultLimitSTACK", config_parse_rlimit
, RLIMIT_STACK
, arg_default_rlimit
},
642 { "Manager", "DefaultLimitCORE", config_parse_rlimit
, RLIMIT_CORE
, arg_default_rlimit
},
643 { "Manager", "DefaultLimitRSS", config_parse_rlimit
, RLIMIT_RSS
, arg_default_rlimit
},
644 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit
, RLIMIT_NOFILE
, arg_default_rlimit
},
645 { "Manager", "DefaultLimitAS", config_parse_rlimit
, RLIMIT_AS
, arg_default_rlimit
},
646 { "Manager", "DefaultLimitNPROC", config_parse_rlimit
, RLIMIT_NPROC
, arg_default_rlimit
},
647 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit
, RLIMIT_MEMLOCK
, arg_default_rlimit
},
648 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit
, RLIMIT_LOCKS
, arg_default_rlimit
},
649 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit
, RLIMIT_SIGPENDING
, arg_default_rlimit
},
650 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit
, RLIMIT_MSGQUEUE
, arg_default_rlimit
},
651 { "Manager", "DefaultLimitNICE", config_parse_rlimit
, RLIMIT_NICE
, arg_default_rlimit
},
652 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit
, RLIMIT_RTPRIO
, arg_default_rlimit
},
653 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit
, RLIMIT_RTTIME
, arg_default_rlimit
},
654 { "Manager", "DefaultCPUAccounting", config_parse_tristate
, 0, &arg_default_cpu_accounting
},
655 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_default_io_accounting
},
656 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_default_ip_accounting
},
657 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_default_blockio_accounting
},
658 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_default_memory_accounting
},
659 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_default_tasks_accounting
},
660 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_default_tasks_max
},
661 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, 0, &arg_cad_burst_action
},
662 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy
, 0, &arg_default_oom_policy
},
663 { "Manager", "DefaultOOMScoreAdjust", config_parse_oom_score_adjust
, 0, NULL
},
665 { "Manager", "DefaultSmackProcessLabel", config_parse_string
, 0, &arg_default_smack_process_label
},
667 { "Manager", "DefaultSmackProcessLabel", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
672 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
677 suffix
= "system.conf.d";
679 r
= manager_find_user_config_paths(&files
, &dirs
);
681 return log_error_errno(r
, "Failed to determine config file paths: %m");
683 suffix
= "user.conf.d";
686 (void) config_parse_many(
687 (const char* const*) (files
?: STRV_MAKE(PKGSYSCONFDIR
"/system.conf")),
688 (const char* const*) (dirs
?: CONF_PATHS_STRV("systemd")),
691 config_item_table_lookup
, items
,
697 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we use
698 * USEC_INFINITY like everywhere else. */
699 if (arg_default_timeout_start_usec
<= 0)
700 arg_default_timeout_start_usec
= USEC_INFINITY
;
701 if (arg_default_timeout_stop_usec
<= 0)
702 arg_default_timeout_stop_usec
= USEC_INFINITY
;
707 static void set_manager_defaults(Manager
*m
) {
711 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
712 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
713 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
715 m
->default_timer_accuracy_usec
= arg_default_timer_accuracy_usec
;
716 m
->default_std_output
= arg_default_std_output
;
717 m
->default_std_error
= arg_default_std_error
;
718 m
->default_timeout_start_usec
= arg_default_timeout_start_usec
;
719 m
->default_timeout_stop_usec
= arg_default_timeout_stop_usec
;
720 m
->default_timeout_abort_usec
= arg_default_timeout_abort_usec
;
721 m
->default_timeout_abort_set
= arg_default_timeout_abort_set
;
722 m
->default_device_timeout_usec
= arg_default_device_timeout_usec
;
723 m
->default_restart_usec
= arg_default_restart_usec
;
724 m
->default_start_limit_interval
= arg_default_start_limit_interval
;
725 m
->default_start_limit_burst
= arg_default_start_limit_burst
;
727 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
728 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
729 if (arg_default_cpu_accounting
>= 0)
730 m
->default_cpu_accounting
= arg_default_cpu_accounting
;
732 m
->default_cpu_accounting
= cpu_accounting_is_cheap();
734 m
->default_io_accounting
= arg_default_io_accounting
;
735 m
->default_ip_accounting
= arg_default_ip_accounting
;
736 m
->default_blockio_accounting
= arg_default_blockio_accounting
;
737 m
->default_memory_accounting
= arg_default_memory_accounting
;
738 m
->default_tasks_accounting
= arg_default_tasks_accounting
;
739 m
->default_tasks_max
= arg_default_tasks_max
;
740 m
->default_oom_policy
= arg_default_oom_policy
;
741 m
->default_oom_score_adjust_set
= arg_default_oom_score_adjust_set
;
742 m
->default_oom_score_adjust
= arg_default_oom_score_adjust
;
744 (void) manager_set_default_smack_process_label(m
, arg_default_smack_process_label
);
746 (void) manager_set_default_rlimits(m
, arg_default_rlimit
);
748 (void) manager_default_environment(m
);
749 (void) manager_transient_environment_add(m
, arg_default_environment
);
752 static void set_manager_settings(Manager
*m
) {
757 /* Propagates the various manager settings into the manager object, i.e. properties that
758 * effect the manager itself (as opposed to just being inherited into newly allocated
759 * units, see set_manager_defaults() above). */
761 m
->confirm_spawn
= arg_confirm_spawn
;
762 m
->service_watchdogs
= arg_service_watchdogs
;
763 m
->cad_burst_action
= arg_cad_burst_action
;
765 manager_set_watchdog(m
, WATCHDOG_RUNTIME
, arg_runtime_watchdog
);
766 manager_set_watchdog(m
, WATCHDOG_REBOOT
, arg_reboot_watchdog
);
767 manager_set_watchdog(m
, WATCHDOG_KEXEC
, arg_kexec_watchdog
);
768 manager_set_watchdog(m
, WATCHDOG_PRETIMEOUT
, arg_pretimeout_watchdog
);
769 r
= manager_set_watchdog_pretimeout_governor(m
, arg_watchdog_pretimeout_governor
);
771 log_warning_errno(r
, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor
);
773 manager_set_show_status(m
, arg_show_status
, "commandline");
774 m
->status_unit_format
= arg_status_unit_format
;
777 static int parse_argv(int argc
, char *argv
[]) {
779 ARG_LOG_LEVEL
= 0x100,
790 ARG_DUMP_CONFIGURATION_ITEMS
,
791 ARG_DUMP_BUS_PROPERTIES
,
801 ARG_DEFAULT_STD_OUTPUT
,
802 ARG_DEFAULT_STD_ERROR
,
804 ARG_SERVICE_WATCHDOGS
,
807 static const struct option options
[] = {
808 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
809 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
810 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
811 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
812 { "log-time", optional_argument
, NULL
, ARG_LOG_TIME
},
813 { "unit", required_argument
, NULL
, ARG_UNIT
},
814 { "system", no_argument
, NULL
, ARG_SYSTEM
},
815 { "user", no_argument
, NULL
, ARG_USER
},
816 { "test", no_argument
, NULL
, ARG_TEST
},
817 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
818 { "help", no_argument
, NULL
, 'h' },
819 { "version", no_argument
, NULL
, ARG_VERSION
},
820 { "dump-configuration-items", no_argument
, NULL
, ARG_DUMP_CONFIGURATION_ITEMS
},
821 { "dump-bus-properties", no_argument
, NULL
, ARG_DUMP_BUS_PROPERTIES
},
822 { "bus-introspect", required_argument
, NULL
, ARG_BUS_INTROSPECT
},
823 { "dump-core", optional_argument
, NULL
, ARG_DUMP_CORE
},
824 { "crash-chvt", required_argument
, NULL
, ARG_CRASH_CHVT
},
825 { "crash-shell", optional_argument
, NULL
, ARG_CRASH_SHELL
},
826 { "crash-reboot", optional_argument
, NULL
, ARG_CRASH_REBOOT
},
827 { "confirm-spawn", optional_argument
, NULL
, ARG_CONFIRM_SPAWN
},
828 { "show-status", optional_argument
, NULL
, ARG_SHOW_STATUS
},
829 { "deserialize", required_argument
, NULL
, ARG_DESERIALIZE
},
830 { "switched-root", no_argument
, NULL
, ARG_SWITCHED_ROOT
},
831 { "default-standard-output", required_argument
, NULL
, ARG_DEFAULT_STD_OUTPUT
, },
832 { "default-standard-error", required_argument
, NULL
, ARG_DEFAULT_STD_ERROR
, },
833 { "machine-id", required_argument
, NULL
, ARG_MACHINE_ID
},
834 { "service-watchdogs", required_argument
, NULL
, ARG_SERVICE_WATCHDOGS
},
839 bool user_arg_seen
= false;
844 if (getpid_cached() == 1)
847 while ((c
= getopt_long(argc
, argv
, "hDbsz:", options
, NULL
)) >= 0)
852 r
= log_set_max_level_from_string(optarg
);
854 return log_error_errno(r
, "Failed to parse log level \"%s\": %m", optarg
);
859 r
= log_set_target_from_string(optarg
);
861 return log_error_errno(r
, "Failed to parse log target \"%s\": %m", optarg
);
868 r
= log_show_color_from_string(optarg
);
870 return log_error_errno(r
, "Failed to parse log color setting \"%s\": %m",
873 log_show_color(true);
877 case ARG_LOG_LOCATION
:
879 r
= log_show_location_from_string(optarg
);
881 return log_error_errno(r
, "Failed to parse log location setting \"%s\": %m",
884 log_show_location(true);
891 r
= log_show_time_from_string(optarg
);
893 return log_error_errno(r
, "Failed to parse log time setting \"%s\": %m",
900 case ARG_DEFAULT_STD_OUTPUT
:
901 r
= exec_output_from_string(optarg
);
903 return log_error_errno(r
, "Failed to parse default standard output setting \"%s\": %m",
905 arg_default_std_output
= r
;
908 case ARG_DEFAULT_STD_ERROR
:
909 r
= exec_output_from_string(optarg
);
911 return log_error_errno(r
, "Failed to parse default standard error output setting \"%s\": %m",
913 arg_default_std_error
= r
;
917 r
= free_and_strdup(&arg_default_unit
, optarg
);
919 return log_error_errno(r
, "Failed to set default unit \"%s\": %m", optarg
);
929 user_arg_seen
= true;
933 arg_action
= ACTION_TEST
;
937 arg_pager_flags
|= PAGER_DISABLE
;
941 arg_action
= ACTION_VERSION
;
944 case ARG_DUMP_CONFIGURATION_ITEMS
:
945 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
948 case ARG_DUMP_BUS_PROPERTIES
:
949 arg_action
= ACTION_DUMP_BUS_PROPERTIES
;
952 case ARG_BUS_INTROSPECT
:
953 arg_bus_introspect
= optarg
;
954 arg_action
= ACTION_BUS_INTROSPECT
;
958 r
= parse_boolean_argument("--dump-core", optarg
, &arg_dump_core
);
964 r
= parse_crash_chvt(optarg
, &arg_crash_chvt
);
966 return log_error_errno(r
, "Failed to parse crash virtual terminal index: \"%s\": %m",
970 case ARG_CRASH_SHELL
:
971 r
= parse_boolean_argument("--crash-shell", optarg
, &arg_crash_shell
);
976 case ARG_CRASH_REBOOT
:
977 r
= parse_boolean_argument("--crash-reboot", optarg
, &arg_crash_reboot
);
982 case ARG_CONFIRM_SPAWN
:
983 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
985 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
987 return log_error_errno(r
, "Failed to parse confirm spawn option: \"%s\": %m",
991 case ARG_SERVICE_WATCHDOGS
:
992 r
= parse_boolean_argument("--service-watchdogs=", optarg
, &arg_service_watchdogs
);
997 case ARG_SHOW_STATUS
:
999 r
= parse_show_status(optarg
, &arg_show_status
);
1001 return log_error_errno(r
, "Failed to parse show status boolean: \"%s\": %m",
1004 arg_show_status
= SHOW_STATUS_YES
;
1007 case ARG_DESERIALIZE
: {
1011 r
= safe_atoi(optarg
, &fd
);
1013 log_error_errno(r
, "Failed to parse deserialize option \"%s\": %m", optarg
);
1015 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1016 "Invalid deserialize fd: %d",
1019 (void) fd_cloexec(fd
, true);
1021 f
= fdopen(fd
, "r");
1023 return log_error_errno(errno
, "Failed to open serialization fd %d: %m", fd
);
1025 safe_fclose(arg_serialization
);
1026 arg_serialization
= f
;
1031 case ARG_SWITCHED_ROOT
:
1032 arg_switched_root
= true;
1035 case ARG_MACHINE_ID
:
1036 r
= set_machine_id(optarg
);
1038 return log_error_errno(r
, "MachineID '%s' is not valid: %m", optarg
);
1042 arg_action
= ACTION_HELP
;
1046 log_set_max_level(LOG_DEBUG
);
1052 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1053 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1056 if (getpid_cached() != 1)
1062 assert_not_reached();
1065 if (optind
< argc
&& getpid_cached() != 1)
1066 /* Hmm, when we aren't run as init system let's complain about excess arguments */
1067 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Excess arguments.");
1069 if (arg_action
== ACTION_RUN
&& !arg_system
&& !user_arg_seen
)
1070 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1071 "Explicit --user argument required to run as user manager.");
1076 static int help(void) {
1077 _cleanup_free_
char *link
= NULL
;
1080 r
= terminal_urlify_man("systemd", "1", &link
);
1084 printf("%s [OPTIONS...]\n\n"
1085 "%sStarts and monitors system and user services.%s\n\n"
1086 "This program takes no positional arguments.\n\n"
1088 " -h --help Show this help\n"
1089 " --version Show version\n"
1090 " --test Determine initial transaction, dump it and exit\n"
1091 " --system Combined with --test: operate in system mode\n"
1092 " --user Combined with --test: operate in user mode\n"
1093 " --dump-configuration-items Dump understood unit configuration items\n"
1094 " --dump-bus-properties Dump exposed bus properties\n"
1095 " --bus-introspect=PATH Write XML introspection data\n"
1096 " --unit=UNIT Set default unit\n"
1097 " --dump-core[=BOOL] Dump core on crash\n"
1098 " --crash-vt=NR Change to specified VT on crash\n"
1099 " --crash-reboot[=BOOL] Reboot on crash\n"
1100 " --crash-shell[=BOOL] Run shell on crash\n"
1101 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1102 " --show-status[=BOOL] Show status updates on the console during boot\n"
1103 " --log-target=TARGET Set log target (console, journal, kmsg,\n"
1104 " journal-or-kmsg, null)\n"
1105 " --log-level=LEVEL Set log level (debug, info, notice, warning,\n"
1106 " err, crit, alert, emerg)\n"
1107 " --log-color[=BOOL] Highlight important log messages\n"
1108 " --log-location[=BOOL] Include code location in log messages\n"
1109 " --log-time[=BOOL] Prefix log messages with current time\n"
1110 " --default-standard-output= Set default standard output for services\n"
1111 " --default-standard-error= Set default standard error output for services\n"
1112 " --no-pager Do not pipe output into a pager\n"
1113 "\nSee the %s for details.\n",
1114 program_invocation_short_name
,
1124 static int prepare_reexecute(
1128 bool switching_root
) {
1130 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1131 _cleanup_fclose_
FILE *f
= NULL
;
1138 r
= manager_open_serialization(m
, &f
);
1140 return log_error_errno(r
, "Failed to create serialization file: %m");
1142 /* Make sure nothing is really destructed when we shut down */
1144 bus_manager_send_reloading(m
, true);
1150 r
= manager_serialize(m
, f
, fds
, switching_root
);
1154 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1155 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1157 r
= fd_cloexec(fileno(f
), false);
1159 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1161 r
= fdset_cloexec(fds
, false);
1163 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1165 *ret_f
= TAKE_PTR(f
);
1166 *ret_fds
= TAKE_PTR(fds
);
1171 static void bump_file_max_and_nr_open(void) {
1173 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
1174 * numbers of file descriptors are no longer a performance problem and their memory is properly
1175 * tracked by memcg, thus counting them and limiting them in another two layers of limits is
1176 * unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
1177 * on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
1179 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1183 #if BUMP_PROC_SYS_FS_FILE_MAX
1184 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
1185 * different, but the operation would fail silently.) */
1186 r
= sysctl_writef("fs/file-max", "%li\n", LONG_MAX
);
1188 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.file-max, ignoring: %m");
1191 #if BUMP_PROC_SYS_FS_NR_OPEN
1194 /* Argh! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know
1195 * what they are. The expression by which the maximum is determined is dependent on the architecture,
1196 * and is something we don't really want to copy to userspace, as it is dependent on implementation
1197 * details of the kernel. Since the kernel doesn't expose the maximum value to us, we can only try
1198 * and hope. Hence, let's start with INT_MAX, and then keep halving the value until we find one that
1199 * works. Ugly? Yes, absolutely, but kernel APIs are kernel APIs, so what do can we do... 🤯 */
1204 v
&= ~(__SIZEOF_POINTER__
- 1); /* Round down to next multiple of the pointer size */
1206 log_warning("Can't bump fs.nr_open, value too small.");
1212 log_error_errno(k
, "Failed to read fs.nr_open: %m");
1215 if (k
>= v
) { /* Already larger */
1216 log_debug("Skipping bump, value is already larger.");
1220 r
= sysctl_writef("fs/nr_open", "%i\n", v
);
1222 log_debug("Couldn't write fs.nr_open as %i, halving it.", v
);
1227 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.nr_open, ignoring: %m");
1231 log_debug("Successfully bumped fs.nr_open to %i", v
);
1237 static int bump_rlimit_nofile(const struct rlimit
*saved_rlimit
) {
1238 struct rlimit new_rlimit
;
1241 /* Get the underlying absolute limit the kernel enforces */
1242 nr
= read_nr_open();
1244 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1245 new_rlimit
= (struct rlimit
) {
1246 .rlim_cur
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_cur
),
1247 .rlim_max
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_max
),
1250 /* Shortcut if nothing changes. */
1251 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_max
&&
1252 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_cur
) {
1253 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1257 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1258 * both hard and soft. */
1259 r
= setrlimit_closest(RLIMIT_NOFILE
, &new_rlimit
);
1261 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1266 static int bump_rlimit_memlock(const struct rlimit
*saved_rlimit
) {
1267 struct rlimit new_rlimit
;
1271 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
1272 * which should normally disable such checks. We need them to implement IPAddressAllow= and
1273 * IPAddressDeny=, hence let's bump the value high enough for our user. */
1275 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1276 * must be unsigned, hence this is a given, but let's make this clear here. */
1277 assert_cc(RLIM_INFINITY
> 0);
1279 mm
= physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
1280 * physical RAM. We allow an eighth to be locked by us, just to
1283 new_rlimit
= (struct rlimit
) {
1284 .rlim_cur
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_cur
, mm
),
1285 .rlim_max
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_max
, mm
),
1288 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_cur
&&
1289 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_max
) {
1290 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1294 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &new_rlimit
);
1296 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1301 static void test_usr(void) {
1303 /* Check that /usr is either on the same file system as / or mounted already. */
1305 if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) <= 0)
1308 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1309 "Some things will probably break (sometimes even silently) in mysterious ways. "
1310 "Consult https://www.freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1313 static int enforce_syscall_archs(Set
*archs
) {
1317 if (!is_seccomp_available())
1320 r
= seccomp_restrict_archs(arg_syscall_archs
);
1322 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1327 static int os_release_status(void) {
1328 _cleanup_free_
char *pretty_name
= NULL
, *name
= NULL
, *version
= NULL
,
1329 *ansi_color
= NULL
, *support_end
= NULL
;
1332 r
= parse_os_release(NULL
,
1333 "PRETTY_NAME", &pretty_name
,
1335 "VERSION", &version
,
1336 "ANSI_COLOR", &ansi_color
,
1337 "SUPPORT_END", &support_end
);
1339 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1340 "Failed to read os-release file, ignoring: %m");
1342 const char *label
= empty_to_null(pretty_name
) ?: empty_to_null(name
) ?: "Linux";
1344 if (show_status_on(arg_show_status
)) {
1345 if (log_get_show_color())
1346 status_printf(NULL
, 0,
1347 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1348 empty_to_null(ansi_color
) ?: "1",
1351 status_printf(NULL
, 0,
1352 "\nWelcome to %s!\n",
1356 if (support_end
&& os_release_support_ended(support_end
, false) > 0)
1357 /* pretty_name may include the version already, so we'll print the version only if we
1358 * have it and we're not using pretty_name. */
1359 status_printf(ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
, 0,
1360 "This OS version (%s%s%s) is past its end-of-support date (%s)",
1362 (pretty_name
|| !version
) ? "" : " version ",
1363 (pretty_name
|| !version
) ? "" : version
,
1369 static int write_container_id(void) {
1371 int r
= 0; /* avoid false maybe-uninitialized warning */
1373 c
= getenv("container");
1377 RUN_WITH_UMASK(0022)
1378 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1380 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1385 static int bump_unix_max_dgram_qlen(void) {
1386 _cleanup_free_
char *qlen
= NULL
;
1390 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
1391 * the value really really early during boot, so that it is actually applied to all our sockets,
1392 * including the $NOTIFY_SOCKET one. */
1394 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1396 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1397 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1399 r
= safe_atolu(qlen
, &v
);
1401 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen
);
1403 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1406 r
= write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER
,
1407 "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN
);
1409 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1410 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1415 static int fixup_environment(void) {
1416 _cleanup_free_
char *term
= NULL
;
1420 /* Only fix up the environment when we are started as PID 1 */
1421 if (getpid_cached() != 1)
1424 /* We expect the environment to be set correctly if run inside a container. */
1425 if (detect_container() > 0)
1428 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
1429 * backend device used by the console. We try to make a better guess here since some consoles might
1430 * not have support for color mode for example.
1432 * However if TERM was configured through the kernel command line then leave it alone. */
1433 r
= proc_cmdline_get_key("TERM", 0, &term
);
1437 t
= term
?: default_term_for_tty("/dev/console");
1439 if (setenv("TERM", t
, 1) < 0)
1442 /* The kernels sets HOME=/ for init. Let's undo this. */
1443 if (path_equal_ptr(getenv("HOME"), "/"))
1444 assert_se(unsetenv("HOME") == 0);
1449 static void redirect_telinit(int argc
, char *argv
[]) {
1451 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1453 #if HAVE_SYSV_COMPAT
1454 if (getpid_cached() == 1)
1457 if (!invoked_as(argv
, "init"))
1460 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1461 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1466 static int become_shutdown(
1467 const char *shutdown_verb
,
1470 char log_level
[DECIMAL_STR_MAX(int) + 1],
1471 exit_code
[DECIMAL_STR_MAX(uint8_t) + 1],
1472 timeout
[DECIMAL_STR_MAX(usec_t
) + 1];
1474 const char* command_line
[13] = {
1475 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1477 "--timeout", timeout
,
1478 "--log-level", log_level
,
1482 _cleanup_strv_free_
char **env_block
= NULL
;
1483 usec_t watchdog_timer
= 0;
1487 assert(shutdown_verb
);
1488 assert(!command_line
[pos
]);
1489 env_block
= strv_copy(environ
);
1491 xsprintf(log_level
, "%d", log_get_max_level());
1492 xsprintf(timeout
, "%" PRI_USEC
"us", arg_default_timeout_stop_usec
);
1494 switch (log_get_target()) {
1496 case LOG_TARGET_KMSG
:
1497 case LOG_TARGET_JOURNAL_OR_KMSG
:
1498 case LOG_TARGET_SYSLOG_OR_KMSG
:
1499 command_line
[pos
++] = "kmsg";
1502 case LOG_TARGET_NULL
:
1503 command_line
[pos
++] = "null";
1506 case LOG_TARGET_CONSOLE
:
1508 command_line
[pos
++] = "console";
1512 if (log_get_show_color())
1513 command_line
[pos
++] = "--log-color";
1515 if (log_get_show_location())
1516 command_line
[pos
++] = "--log-location";
1518 if (log_get_show_time())
1519 command_line
[pos
++] = "--log-time";
1521 if (streq(shutdown_verb
, "exit")) {
1522 command_line
[pos
++] = "--exit-code";
1523 command_line
[pos
++] = exit_code
;
1524 xsprintf(exit_code
, "%d", retval
);
1527 assert(pos
< ELEMENTSOF(command_line
));
1529 if (streq(shutdown_verb
, "reboot"))
1530 watchdog_timer
= arg_reboot_watchdog
;
1531 else if (streq(shutdown_verb
, "kexec"))
1532 watchdog_timer
= arg_kexec_watchdog
;
1534 /* If we reboot or kexec let's set the shutdown watchdog and tell the
1535 * shutdown binary to repeatedly ping it.
1536 * Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
1537 (void) watchdog_setup_pretimeout(0);
1538 (void) watchdog_setup_pretimeout_governor(NULL
);
1539 r
= watchdog_setup(watchdog_timer
);
1540 watchdog_close(r
< 0);
1542 /* Tell the binary how often to ping, ignore failure */
1543 (void) strv_extendf(&env_block
, "WATCHDOG_USEC="USEC_FMT
, watchdog_timer
);
1545 if (arg_watchdog_device
)
1546 (void) strv_extendf(&env_block
, "WATCHDOG_DEVICE=%s", arg_watchdog_device
);
1548 /* Avoid the creation of new processes forked by the kernel; at this
1549 * point, we will not listen to the signals anyway */
1550 if (detect_container() <= 0)
1551 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1553 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1557 static void initialize_clock(void) {
1560 /* This is called very early on, before we parse the kernel command line or otherwise figure out why
1561 * we are running, but only once. */
1563 if (clock_is_localtime(NULL
) > 0) {
1566 /* The very first call of settimeofday() also does a time warp in the kernel.
1568 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
1569 * take care of maintaining the RTC and do all adjustments. This matches the behavior of
1570 * Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
1572 r
= clock_set_timezone(&min
);
1574 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1576 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1578 } else if (!in_initrd())
1580 * Do a dummy very first call to seal the kernel's time warp magic.
1582 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
1583 * LOCAL, but the real system could be set up that way. In such case, we need to delay the
1584 * time-warp or the sealing until we reach the real system.
1586 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
1587 * the time will jump or be incorrect at every daylight saving time change. All kernel local
1588 * time concepts will be treated as UTC that way.
1590 (void) clock_reset_timewarp();
1592 ClockChangeDirection change_dir
;
1593 r
= clock_apply_epoch(&change_dir
);
1594 if (r
> 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1595 log_info("System time before build time, advancing clock.");
1596 else if (r
> 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1597 log_info("System time is further ahead than %s after build time, resetting clock to build time.",
1598 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1599 else if (r
< 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1600 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1601 else if (r
< 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1602 log_error_errno(r
, "Current system time is further ahead %s after build time, but cannot correct: %m",
1603 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1606 static void apply_clock_update(void) {
1607 /* This is called later than initialize_clock(), i.e. after we parsed configuration files/kernel
1608 * command line and such. */
1610 if (arg_clock_usec
== 0)
1613 if (getpid_cached() != 1)
1616 if (clock_settime(CLOCK_REALTIME
, TIMESPEC_STORE(arg_clock_usec
)) < 0)
1617 log_error_errno(errno
, "Failed to set system clock to time specified on kernel command line: %m");
1619 log_info("Set system clock to %s, as specified on the kernel command line.",
1620 FORMAT_TIMESTAMP(arg_clock_usec
));
1623 static void cmdline_take_random_seed(void) {
1627 if (arg_random_seed_size
== 0)
1630 if (getpid_cached() != 1)
1633 assert(arg_random_seed
);
1634 suggested
= random_pool_size();
1636 if (arg_random_seed_size
< suggested
)
1637 log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
1638 arg_random_seed_size
, suggested
);
1640 r
= random_write_entropy(-1, arg_random_seed
, arg_random_seed_size
, true);
1642 log_warning_errno(r
, "Failed to credit entropy specified on kernel command line, ignoring: %m");
1646 log_notice("Successfully credited entropy passed on kernel command line.\n"
1647 "Note that the seed provided this way is accessible to unprivileged programs. "
1648 "This functionality should not be used outside of testing environments.");
1651 static void initialize_coredump(bool skip_setup
) {
1653 if (getpid_cached() != 1)
1656 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
1657 * the limit) will process core dumps for system services by default. */
1658 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1659 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1661 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1662 * until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
1663 * command line later so core dumps can still be generated during early startup and in initrd. */
1665 disable_coredumps();
1669 static void initialize_core_pattern(bool skip_setup
) {
1672 if (skip_setup
|| !arg_early_core_pattern
)
1675 if (getpid_cached() != 1)
1678 r
= write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1680 log_warning_errno(r
, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1681 arg_early_core_pattern
);
1684 static void update_cpu_affinity(bool skip_setup
) {
1685 _cleanup_free_
char *mask
= NULL
;
1687 if (skip_setup
|| !arg_cpu_affinity
.set
)
1690 assert(arg_cpu_affinity
.allocated
> 0);
1692 mask
= cpu_set_to_range_string(&arg_cpu_affinity
);
1693 log_debug("Setting CPU affinity to {%s}.", strnull(mask
));
1695 if (sched_setaffinity(0, arg_cpu_affinity
.allocated
, arg_cpu_affinity
.set
) < 0)
1696 log_warning_errno(errno
, "Failed to set CPU affinity, ignoring: %m");
1699 static void update_numa_policy(bool skip_setup
) {
1701 _cleanup_free_
char *nodes
= NULL
;
1702 const char * policy
= NULL
;
1704 if (skip_setup
|| !mpol_is_valid(numa_policy_get_type(&arg_numa_policy
)))
1707 if (DEBUG_LOGGING
) {
1708 policy
= mpol_to_string(numa_policy_get_type(&arg_numa_policy
));
1709 nodes
= cpu_set_to_range_string(&arg_numa_policy
.nodes
);
1710 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy
), strnull(nodes
));
1713 r
= apply_numa_policy(&arg_numa_policy
);
1714 if (r
== -EOPNOTSUPP
)
1715 log_debug_errno(r
, "NUMA support not available, ignoring.");
1717 log_warning_errno(r
, "Failed to set NUMA memory policy, ignoring: %m");
1720 static void filter_args(
1729 /* Copy some filtered arguments into the dst array from src. */
1730 for (int i
= 1; i
< argc
; i
++) {
1731 if (STR_IN_SET(src
[i
],
1737 if (startswith(src
[i
], "--deserialize="))
1739 if (streq(src
[i
], "--deserialize")) {
1740 i
++; /* Skip the argument too */
1744 /* Skip target unit designators. We already acted upon this information and have queued
1745 * appropriate jobs. We don't want to redo all this after reexecution. */
1746 if (startswith(src
[i
], "--unit="))
1748 if (streq(src
[i
], "--unit")) {
1749 i
++; /* Skip the argument too */
1753 /* Seems we have a good old option. Let's pass it over to the new instance. */
1754 dst
[(*dst_index
)++] = src
[i
];
1758 static int do_reexecute(
1759 ManagerObjective objective
,
1762 const struct rlimit
*saved_rlimit_nofile
,
1763 const struct rlimit
*saved_rlimit_memlock
,
1765 const char *switch_root_dir
,
1766 const char *switch_root_init
,
1767 const char **ret_error_message
) {
1769 size_t i
, args_size
;
1773 assert(IN_SET(objective
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
));
1775 assert(saved_rlimit_nofile
);
1776 assert(saved_rlimit_memlock
);
1777 assert(ret_error_message
);
1779 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1780 * rebooted while we do that */
1781 watchdog_close(true);
1783 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1784 * the kernel default to its child processes */
1785 if (saved_rlimit_nofile
->rlim_cur
!= 0)
1786 (void) setrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
);
1787 if (saved_rlimit_memlock
->rlim_cur
!= RLIM_INFINITY
)
1788 (void) setrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
);
1790 if (switch_root_dir
) {
1791 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can
1792 * handle the SIGCHLD for them after deserializing. */
1793 broadcast_signal(SIGTERM
, false, true, arg_default_timeout_stop_usec
);
1795 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1796 r
= switch_root(switch_root_dir
, "/mnt", true, MS_MOVE
);
1798 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
1801 args_size
= argc
+ 6;
1802 args
= newa(const char*, args_size
);
1804 if (!switch_root_init
) {
1805 char sfd
[DECIMAL_STR_MAX(int)];
1807 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1808 * only if the user didn't specify an explicit init to spawn. */
1810 assert(arg_serialization
);
1813 xsprintf(sfd
, "%i", fileno(arg_serialization
));
1815 i
= 1; /* Leave args[0] empty for now. */
1816 filter_args(args
, &i
, argv
, argc
);
1818 if (switch_root_dir
)
1819 args
[i
++] = "--switched-root";
1820 args
[i
++] = arg_system
? "--system" : "--user";
1821 args
[i
++] = "--deserialize";
1825 assert(i
<= args_size
);
1828 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
1829 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
1830 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
1831 * and wait() for it in the parent, before proceeding into the exec().
1833 valgrind_summary_hack();
1835 args
[0] = SYSTEMD_BINARY_PATH
;
1836 (void) execv(args
[0], (char* const*) args
);
1838 if (objective
== MANAGER_REEXECUTE
) {
1839 *ret_error_message
= "Failed to execute our own binary";
1840 return log_error_errno(errno
, "Failed to execute our own binary %s: %m", args
[0]);
1843 log_debug_errno(errno
, "Failed to execute our own binary %s, trying fallback: %m", args
[0]);
1846 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
1847 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
1848 * but let's hope that doesn't matter.) */
1850 arg_serialization
= safe_fclose(arg_serialization
);
1851 fds
= fdset_free(fds
);
1853 /* Reopen the console */
1854 (void) make_console_stdio();
1856 i
= 1; /* Leave args[0] empty for now. */
1857 for (int j
= 1; j
<= argc
; j
++)
1858 args
[i
++] = argv
[j
];
1859 assert(i
<= args_size
);
1861 /* Re-enable any blocked signals, especially important if we switch from initrd to init=... */
1862 (void) reset_all_signal_handlers();
1863 (void) reset_signal_mask();
1864 (void) rlimit_nofile_safe();
1866 if (switch_root_init
) {
1867 args
[0] = switch_root_init
;
1868 (void) execve(args
[0], (char* const*) args
, saved_env
);
1869 log_warning_errno(errno
, "Failed to execute configured init %s, trying fallback: %m", args
[0]);
1872 args
[0] = "/sbin/init";
1873 (void) execv(args
[0], (char* const*) args
);
1876 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
1877 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
1878 "Failed to execute /sbin/init");
1880 *ret_error_message
= "Failed to execute fallback shell";
1882 log_warning("No /sbin/init, trying fallback");
1884 args
[0] = "/bin/sh";
1886 (void) execve(args
[0], (char* const*) args
, saved_env
);
1887 return log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
1889 return log_error_errno(r
, "Failed to execute /sbin/init, giving up: %m");
1892 static int invoke_main_loop(
1894 const struct rlimit
*saved_rlimit_nofile
,
1895 const struct rlimit
*saved_rlimit_memlock
,
1896 int *ret_retval
, /* Return parameters relevant for shutting down */
1897 const char **ret_shutdown_verb
, /* … */
1898 FDSet
**ret_fds
, /* Return parameters for reexecuting */
1899 char **ret_switch_root_dir
, /* … */
1900 char **ret_switch_root_init
, /* … */
1901 const char **ret_error_message
) {
1906 assert(saved_rlimit_nofile
);
1907 assert(saved_rlimit_memlock
);
1909 assert(ret_shutdown_verb
);
1911 assert(ret_switch_root_dir
);
1912 assert(ret_switch_root_init
);
1913 assert(ret_error_message
);
1916 int objective
= manager_loop(m
);
1917 if (objective
< 0) {
1918 *ret_error_message
= "Failed to run main loop";
1919 return log_emergency_errno(objective
, "Failed to run main loop: %m");
1922 switch (objective
) {
1924 case MANAGER_RELOAD
: {
1925 LogTarget saved_log_target
;
1926 int saved_log_level
;
1928 log_info("Reloading.");
1930 /* First, save any overridden log level/target, then parse the configuration file,
1931 * which might change the log level to new settings. */
1933 saved_log_level
= m
->log_level_overridden
? log_get_max_level() : -1;
1934 saved_log_target
= m
->log_target_overridden
? log_get_target() : _LOG_TARGET_INVALID
;
1936 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
1938 set_manager_defaults(m
);
1939 set_manager_settings(m
);
1941 update_cpu_affinity(false);
1942 update_numa_policy(false);
1944 if (saved_log_level
>= 0)
1945 manager_override_log_level(m
, saved_log_level
);
1946 if (saved_log_target
>= 0)
1947 manager_override_log_target(m
, saved_log_target
);
1949 if (manager_reload(m
) < 0)
1950 /* Reloading failed before the point of no return.
1951 * Let's continue running as if nothing happened. */
1952 m
->objective
= MANAGER_OK
;
1957 case MANAGER_REEXECUTE
:
1958 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, false);
1960 *ret_error_message
= "Failed to prepare for reexecution";
1964 log_notice("Reexecuting.");
1966 *ret_retval
= EXIT_SUCCESS
;
1967 *ret_shutdown_verb
= NULL
;
1968 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1972 case MANAGER_SWITCH_ROOT
:
1973 manager_set_switching_root(m
, true);
1975 if (!m
->switch_root_init
) {
1976 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, true);
1978 *ret_error_message
= "Failed to prepare for reexecution";
1984 log_notice("Switching root.");
1986 *ret_retval
= EXIT_SUCCESS
;
1987 *ret_shutdown_verb
= NULL
;
1989 /* Steal the switch root parameters */
1990 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
1991 *ret_switch_root_init
= TAKE_PTR(m
->switch_root_init
);
1996 if (MANAGER_IS_USER(m
)) {
1999 *ret_retval
= m
->return_value
;
2000 *ret_shutdown_verb
= NULL
;
2002 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2008 case MANAGER_REBOOT
:
2009 case MANAGER_POWEROFF
:
2011 case MANAGER_KEXEC
: {
2012 static const char* const table
[_MANAGER_OBJECTIVE_MAX
] = {
2013 [MANAGER_EXIT
] = "exit",
2014 [MANAGER_REBOOT
] = "reboot",
2015 [MANAGER_POWEROFF
] = "poweroff",
2016 [MANAGER_HALT
] = "halt",
2017 [MANAGER_KEXEC
] = "kexec",
2020 log_notice("Shutting down.");
2022 *ret_retval
= m
->return_value
;
2023 assert_se(*ret_shutdown_verb
= table
[m
->objective
]);
2025 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2031 assert_not_reached();
2036 static void log_execution_mode(bool *ret_first_boot
) {
2037 bool first_boot
= false;
2039 assert(ret_first_boot
);
2045 log_info("systemd " GIT_VERSION
" running in %ssystem mode (%s)",
2046 arg_action
== ACTION_TEST
? "test " : "",
2049 v
= detect_virtualization();
2051 log_info("Detected virtualization %s.", virtualization_to_string(v
));
2053 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2056 log_info("Running in initrd.");
2059 _cleanup_free_
char *id_text
= NULL
;
2061 /* Let's check whether we are in first boot. First, check if an override was
2062 * specified on the kernel commandline. If yes, we honour that. */
2064 r
= proc_cmdline_get_bool("systemd.condition-first-boot", &first_boot
);
2066 log_debug_errno(r
, "Failed to parse systemd.condition-first-boot= kernel commandline argument, ignoring: %m");
2069 log_full(first_boot
? LOG_INFO
: LOG_DEBUG
,
2070 "Kernel commandline argument says we are %s first boot.",
2071 first_boot
? "in" : "not in");
2073 /* Second, perform autodetection. We use /etc/machine-id as flag file for
2074 * this: If it is missing or contains the value "uninitialized", this is the
2075 * first boot. In other cases, it is not. This allows container managers and
2076 * installers to provision a couple of files in /etc but still permit the
2077 * first-boot initialization to occur. If the container manager wants to
2078 * provision the machine ID it should pass $container_uuid to PID 1. */
2080 r
= read_one_line_file("/etc/machine-id", &id_text
);
2081 if (r
< 0 || streq(id_text
, "uninitialized")) {
2082 if (r
< 0 && r
!= -ENOENT
)
2083 log_warning_errno(r
, "Unexpected error while reading /etc/machine-id, ignoring: %m");
2086 log_info("Detected first boot.");
2088 log_debug("Detected initialized system, this is not the first boot.");
2092 assert_se(uname(&uts
) >= 0);
2094 if (strverscmp_improved(uts
.release
, KERNEL_BASELINE_VERSION
) < 0)
2095 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2096 "Your mileage may vary.", uts
.release
, KERNEL_BASELINE_VERSION
);
2098 log_debug("Kernel version %s, our baseline is %s", uts
.release
, KERNEL_BASELINE_VERSION
);
2100 if (DEBUG_LOGGING
) {
2101 _cleanup_free_
char *t
= NULL
;
2103 t
= uid_to_name(getuid());
2104 log_debug("systemd " GIT_VERSION
" running in %suser mode for user " UID_FMT
"/%s. (%s)",
2105 arg_action
== ACTION_TEST
? " test" : "",
2106 getuid(), strna(t
), systemd_features
);
2110 *ret_first_boot
= first_boot
;
2113 static int initialize_runtime(
2116 struct rlimit
*saved_rlimit_nofile
,
2117 struct rlimit
*saved_rlimit_memlock
,
2118 const char **ret_error_message
) {
2121 assert(ret_error_message
);
2123 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2125 * - Some only apply to --system instances
2126 * - Some only apply to --user instances
2127 * - Some only apply when we first start up, but not when we reexecute
2130 if (arg_action
!= ACTION_RUN
)
2133 update_cpu_affinity(skip_setup
);
2134 update_numa_policy(skip_setup
);
2137 /* Make sure we leave a core dump without panicking the kernel. */
2138 install_crash_handler();
2141 r
= mount_cgroup_controllers();
2143 *ret_error_message
= "Failed to mount cgroup hierarchies";
2147 (void) os_release_status();
2148 (void) hostname_setup(true);
2149 /* Force transient machine-id on first boot. */
2150 machine_id_setup(NULL
, /* force_transient= */ first_boot
, arg_machine_id
, NULL
);
2151 (void) loopback_setup();
2152 bump_unix_max_dgram_qlen();
2153 bump_file_max_and_nr_open();
2155 write_container_id();
2158 r
= watchdog_set_device(arg_watchdog_device
);
2160 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device
);
2162 _cleanup_free_
char *p
= NULL
;
2164 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2165 * user mode. In system mode mount_setup() already did that. */
2167 r
= xdg_user_runtime_dir(&p
, "/systemd");
2169 *ret_error_message
= "$XDG_RUNTIME_DIR is not set";
2170 return log_emergency_errno(r
, "Failed to determine $XDG_RUNTIME_DIR path: %m");
2173 (void) mkdir_p_label(p
, 0755);
2174 (void) make_inaccessible_nodes(p
, UID_INVALID
, GID_INVALID
);
2177 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
2178 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
2179 log_warning_errno(errno
, "Failed to adjust timer slack, ignoring: %m");
2181 if (arg_system
&& !cap_test_all(arg_capability_bounding_set
)) {
2182 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
2184 *ret_error_message
= "Failed to drop capability bounding set of usermode helpers";
2185 return log_emergency_errno(r
, "Failed to drop capability bounding set of usermode helpers: %m");
2188 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
2190 *ret_error_message
= "Failed to drop capability bounding set";
2191 return log_emergency_errno(r
, "Failed to drop capability bounding set: %m");
2195 if (arg_system
&& arg_no_new_privs
) {
2196 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2197 *ret_error_message
= "Failed to disable new privileges";
2198 return log_emergency_errno(errno
, "Failed to disable new privileges: %m");
2202 if (arg_syscall_archs
) {
2203 r
= enforce_syscall_archs(arg_syscall_archs
);
2205 *ret_error_message
= "Failed to set syscall architectures";
2211 /* Become reaper of our children */
2212 if (prctl(PR_SET_CHILD_SUBREAPER
, 1) < 0)
2213 log_warning_errno(errno
, "Failed to make us a subreaper, ignoring: %m");
2215 /* Bump up RLIMIT_NOFILE for systemd itself */
2216 (void) bump_rlimit_nofile(saved_rlimit_nofile
);
2217 (void) bump_rlimit_memlock(saved_rlimit_memlock
);
2219 /* Pull credentials from various sources into a common credential directory */
2220 if (arg_system
&& !skip_setup
)
2221 (void) import_credentials();
2226 static int do_queue_default_job(
2228 const char **ret_error_message
) {
2230 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2236 if (arg_default_unit
)
2237 unit
= arg_default_unit
;
2238 else if (in_initrd())
2239 unit
= SPECIAL_INITRD_TARGET
;
2241 unit
= SPECIAL_DEFAULT_TARGET
;
2243 log_debug("Activating default unit: %s", unit
);
2245 r
= manager_load_startable_unit_or_warn(m
, unit
, NULL
, &target
);
2246 if (r
< 0 && in_initrd() && !arg_default_unit
) {
2247 /* Fall back to default.target, which we used to always use by default. Only do this if no
2248 * explicit configuration was given. */
2250 log_info("Falling back to " SPECIAL_DEFAULT_TARGET
".");
2252 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_DEFAULT_TARGET
, NULL
, &target
);
2255 log_info("Falling back to " SPECIAL_RESCUE_TARGET
".");
2257 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_RESCUE_TARGET
, NULL
, &target
);
2259 *ret_error_message
= r
== -ERFKILL
? SPECIAL_RESCUE_TARGET
" masked"
2260 : "Failed to load " SPECIAL_RESCUE_TARGET
;
2265 assert(target
->load_state
== UNIT_LOADED
);
2267 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, NULL
, &error
, &job
);
2269 log_debug_errno(r
, "Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
2271 sd_bus_error_free(&error
);
2273 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, NULL
, &error
, &job
);
2275 *ret_error_message
= "Failed to start default target";
2276 return log_emergency_errno(r
, "Failed to start default target: %s", bus_error_message(&error
, r
));
2280 *ret_error_message
= "Failed to isolate default target";
2281 return log_emergency_errno(r
, "Failed to isolate default target: %s", bus_error_message(&error
, r
));
2283 log_info("Queued %s job for default target %s.",
2284 job_type_to_string(job
->type
),
2285 unit_status_string(job
->unit
, NULL
));
2287 m
->default_unit_job_id
= job
->id
;
2292 static void save_rlimits(struct rlimit
*saved_rlimit_nofile
,
2293 struct rlimit
*saved_rlimit_memlock
) {
2295 assert(saved_rlimit_nofile
);
2296 assert(saved_rlimit_memlock
);
2298 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
) < 0)
2299 log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2301 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
) < 0)
2302 log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2305 static void fallback_rlimit_nofile(const struct rlimit
*saved_rlimit_nofile
) {
2308 if (arg_default_rlimit
[RLIMIT_NOFILE
])
2311 /* Make sure forked processes get limits based on the original kernel setting */
2313 rl
= newdup(struct rlimit
, saved_rlimit_nofile
, 1);
2319 /* Bump the hard limit for system services to a substantially higher value. The default
2320 * hard limit current kernels set is pretty low (4K), mostly for historical
2321 * reasons. According to kernel developers, the fd handling in recent kernels has been
2322 * optimized substantially enough, so that we can bump the limit now, without paying too
2323 * high a price in memory or performance. Note however that we only bump the hard limit,
2324 * not the soft limit. That's because select() works the way it works, and chokes on fds
2325 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2326 * unexpecting programs that they get fds higher than what they can process using
2327 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2328 * this pitfall: programs that are written by folks aware of the select() problem in mind
2329 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2330 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2335 /* Get the underlying absolute limit the kernel enforces */
2336 nr
= read_nr_open();
2338 rl
->rlim_max
= MIN((rlim_t
) nr
, MAX(rl
->rlim_max
, (rlim_t
) HIGH_RLIMIT_NOFILE
));
2341 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2342 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2343 * instance), then lower what we pass on to not confuse our children */
2344 rl
->rlim_cur
= MIN(rl
->rlim_cur
, (rlim_t
) FD_SETSIZE
);
2346 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
2349 static void fallback_rlimit_memlock(const struct rlimit
*saved_rlimit_memlock
) {
2352 /* Pass the original value down to invoked processes */
2354 if (arg_default_rlimit
[RLIMIT_MEMLOCK
])
2357 rl
= newdup(struct rlimit
, saved_rlimit_memlock
, 1);
2364 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2365 * default for this since kernel 5.16) */
2366 rl
->rlim_max
= MAX(rl
->rlim_max
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2367 rl
->rlim_cur
= MAX(rl
->rlim_cur
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2370 arg_default_rlimit
[RLIMIT_MEMLOCK
] = rl
;
2373 static void setenv_manager_environment(void) {
2376 STRV_FOREACH(p
, arg_manager_environment
) {
2377 log_debug("Setting '%s' in our own environment.", *p
);
2379 r
= putenv_dup(*p
, true);
2381 log_warning_errno(errno
, "Failed to setenv \"%s\", ignoring: %m", *p
);
2385 static void reset_arguments(void) {
2386 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2388 arg_default_unit
= mfree(arg_default_unit
);
2390 /* arg_system — ignore */
2392 arg_dump_core
= true;
2393 arg_crash_chvt
= -1;
2394 arg_crash_shell
= false;
2395 arg_crash_reboot
= false;
2396 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2397 arg_show_status
= _SHOW_STATUS_INVALID
;
2398 arg_status_unit_format
= STATUS_UNIT_FORMAT_DEFAULT
;
2399 arg_switched_root
= false;
2400 arg_pager_flags
= 0;
2401 arg_service_watchdogs
= true;
2402 arg_default_std_output
= EXEC_OUTPUT_JOURNAL
;
2403 arg_default_std_error
= EXEC_OUTPUT_INHERIT
;
2404 arg_default_restart_usec
= DEFAULT_RESTART_USEC
;
2405 arg_default_timeout_start_usec
= DEFAULT_TIMEOUT_USEC
;
2406 arg_default_timeout_stop_usec
= DEFAULT_TIMEOUT_USEC
;
2407 arg_default_timeout_abort_usec
= DEFAULT_TIMEOUT_USEC
;
2408 arg_default_timeout_abort_set
= false;
2409 arg_default_device_timeout_usec
= DEFAULT_TIMEOUT_USEC
;
2410 arg_default_start_limit_interval
= DEFAULT_START_LIMIT_INTERVAL
;
2411 arg_default_start_limit_burst
= DEFAULT_START_LIMIT_BURST
;
2412 arg_runtime_watchdog
= 0;
2413 arg_reboot_watchdog
= 10 * USEC_PER_MINUTE
;
2414 arg_kexec_watchdog
= 0;
2415 arg_pretimeout_watchdog
= 0;
2416 arg_early_core_pattern
= mfree(arg_early_core_pattern
);
2417 arg_watchdog_device
= mfree(arg_watchdog_device
);
2418 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
2420 arg_default_environment
= strv_free(arg_default_environment
);
2421 arg_manager_environment
= strv_free(arg_manager_environment
);
2422 rlimit_free_all(arg_default_rlimit
);
2424 arg_capability_bounding_set
= CAP_ALL
;
2425 arg_no_new_privs
= false;
2426 arg_timer_slack_nsec
= NSEC_INFINITY
;
2427 arg_default_timer_accuracy_usec
= 1 * USEC_PER_MINUTE
;
2429 arg_syscall_archs
= set_free(arg_syscall_archs
);
2431 /* arg_serialization — ignore */
2433 arg_default_cpu_accounting
= -1;
2434 arg_default_io_accounting
= false;
2435 arg_default_ip_accounting
= false;
2436 arg_default_blockio_accounting
= false;
2437 arg_default_memory_accounting
= MEMORY_ACCOUNTING_DEFAULT
;
2438 arg_default_tasks_accounting
= true;
2439 arg_default_tasks_max
= DEFAULT_TASKS_MAX
;
2440 arg_machine_id
= (sd_id128_t
) {};
2441 arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
2442 arg_default_oom_policy
= OOM_STOP
;
2444 cpu_set_reset(&arg_cpu_affinity
);
2445 numa_policy_reset(&arg_numa_policy
);
2447 arg_random_seed
= mfree(arg_random_seed
);
2448 arg_random_seed_size
= 0;
2451 arg_default_oom_score_adjust_set
= false;
2452 arg_default_smack_process_label
= mfree(arg_default_smack_process_label
);
2455 static void determine_default_oom_score_adjust(void) {
2458 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2459 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2462 if (arg_default_oom_score_adjust_set
)
2468 r
= get_oom_score_adjust(&a
);
2470 return (void) log_warning_errno(r
, "Failed to determine current OOM score adjustment value, ignoring: %m");
2472 assert_cc(100 <= OOM_SCORE_ADJ_MAX
);
2473 b
= a
>= OOM_SCORE_ADJ_MAX
- 100 ? OOM_SCORE_ADJ_MAX
: a
+ 100;
2478 arg_default_oom_score_adjust
= b
;
2479 arg_default_oom_score_adjust_set
= true;
2482 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
2483 const struct rlimit
*saved_rlimit_memlock
) {
2486 assert(saved_rlimit_nofile
);
2487 assert(saved_rlimit_memlock
);
2489 /* Assign configuration defaults */
2492 r
= parse_config_file();
2494 log_warning_errno(r
, "Failed to parse config file, ignoring: %m");
2497 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
2499 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2502 /* Initialize some default rlimits for services if they haven't been configured */
2503 fallback_rlimit_nofile(saved_rlimit_nofile
);
2504 fallback_rlimit_memlock(saved_rlimit_memlock
);
2506 /* Note that this also parses bits from the kernel command line, including "debug". */
2507 log_parse_environment();
2509 /* Initialize the show status setting if it hasn't been set explicitly yet */
2510 if (arg_show_status
== _SHOW_STATUS_INVALID
)
2511 arg_show_status
= SHOW_STATUS_YES
;
2513 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2514 determine_default_oom_score_adjust();
2516 /* Push variables into the manager environment block */
2517 setenv_manager_environment();
2519 /* Parse log environment variables again to take into account any new environment variables. */
2520 log_parse_environment();
2525 static int safety_checks(void) {
2527 if (getpid_cached() == 1 &&
2528 arg_action
!= ACTION_RUN
)
2529 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2530 "Unsupported execution mode while PID 1.");
2532 if (getpid_cached() == 1 &&
2534 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2535 "Can't run --user mode as PID 1.");
2537 if (arg_action
== ACTION_RUN
&&
2539 getpid_cached() != 1)
2540 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2541 "Can't run system mode unless PID 1.");
2543 if (arg_action
== ACTION_TEST
&&
2545 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2546 "Don't run test mode as root.");
2549 arg_action
== ACTION_RUN
&&
2551 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2552 "Trying to run as user instance, but the system has not been booted with systemd.");
2555 arg_action
== ACTION_RUN
&&
2556 !getenv("XDG_RUNTIME_DIR"))
2557 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH
),
2558 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2561 arg_action
== ACTION_RUN
&&
2562 running_in_chroot() > 0)
2563 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2564 "Cannot be run in a chroot() environment.");
2569 static int initialize_security(
2570 bool *loaded_policy
,
2571 dual_timestamp
*security_start_timestamp
,
2572 dual_timestamp
*security_finish_timestamp
,
2573 const char **ret_error_message
) {
2577 assert(loaded_policy
);
2578 assert(security_start_timestamp
);
2579 assert(security_finish_timestamp
);
2580 assert(ret_error_message
);
2582 dual_timestamp_get(security_start_timestamp
);
2584 r
= mac_selinux_setup(loaded_policy
);
2586 *ret_error_message
= "Failed to load SELinux policy";
2590 r
= mac_smack_setup(loaded_policy
);
2592 *ret_error_message
= "Failed to load SMACK policy";
2596 r
= mac_apparmor_setup();
2598 *ret_error_message
= "Failed to load AppArmor policy";
2604 *ret_error_message
= "Failed to load IMA policy";
2608 dual_timestamp_get(security_finish_timestamp
);
2612 static int collect_fds(FDSet
**ret_fds
, const char **ret_error_message
) {
2616 assert(ret_error_message
);
2618 r
= fdset_new_fill(ret_fds
);
2620 *ret_error_message
= "Failed to allocate fd set";
2621 return log_emergency_errno(r
, "Failed to allocate fd set: %m");
2624 fdset_cloexec(*ret_fds
, true);
2626 if (arg_serialization
)
2627 assert_se(fdset_remove(*ret_fds
, fileno(arg_serialization
)) >= 0);
2632 static void setup_console_terminal(bool skip_setup
) {
2637 /* Become a session leader if we aren't one yet. */
2640 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2641 * controlling tty. */
2642 (void) release_terminal();
2644 /* Reset the console, but only if this is really init and we are freshly booted */
2645 if (getpid_cached() == 1 && !skip_setup
)
2646 (void) console_setup();
2649 static bool early_skip_setup_check(int argc
, char *argv
[]) {
2650 bool found_deserialize
= false;
2652 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2653 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2654 * special setup things anyway, even if in that case we also do deserialization. */
2656 for (int i
= 1; i
< argc
; i
++)
2657 if (streq(argv
[i
], "--switched-root"))
2658 return false; /* If we switched root, don't skip the setup. */
2659 else if (streq(argv
[i
], "--deserialize"))
2660 found_deserialize
= true;
2662 return found_deserialize
; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2665 static int save_env(void) {
2668 l
= strv_copy(environ
);
2672 strv_free_and_replace(saved_env
, l
);
2676 int main(int argc
, char *argv
[]) {
2678 initrd_timestamp
= DUAL_TIMESTAMP_NULL
,
2679 userspace_timestamp
= DUAL_TIMESTAMP_NULL
,
2680 kernel_timestamp
= DUAL_TIMESTAMP_NULL
,
2681 security_start_timestamp
= DUAL_TIMESTAMP_NULL
,
2682 security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
2683 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0),
2684 saved_rlimit_memlock
= RLIMIT_MAKE_CONST(RLIM_INFINITY
); /* The original rlimits we passed
2685 * in. Note we use different values
2686 * for the two that indicate whether
2687 * these fields are initialized! */
2688 bool skip_setup
, loaded_policy
= false, queue_default_job
= false, first_boot
= false;
2689 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
2690 usec_t before_startup
, after_startup
;
2691 static char systemd
[] = "systemd";
2692 const char *shutdown_verb
= NULL
, *error_message
= NULL
;
2693 int r
, retval
= EXIT_FAILURE
;
2697 assert_se(argc
> 0 && !isempty(argv
[0]));
2699 /* SysV compatibility: redirect init → telinit */
2700 redirect_telinit(argc
, argv
);
2702 /* Take timestamps early on */
2703 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
2704 dual_timestamp_get(&userspace_timestamp
);
2706 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2708 skip_setup
= early_skip_setup_check(argc
, argv
);
2710 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2711 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2713 program_invocation_short_name
= systemd
;
2714 (void) prctl(PR_SET_NAME
, systemd
);
2716 /* Save the original command line */
2717 save_argc_argv(argc
, argv
);
2719 /* Save the original environment as we might need to restore it if we're requested to execute another
2720 * system manager later. */
2723 error_message
= "Failed to copy environment block";
2727 /* Make sure that if the user says "syslog" we actually log to the journal. */
2728 log_set_upgrade_syslog_to_journal(true);
2730 if (getpid_cached() == 1) {
2731 /* When we run as PID 1 force system mode */
2734 /* Disable the umask logic */
2737 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2738 * not be activated yet (even though the log socket for it exists). */
2739 log_set_prohibit_ipc(true);
2741 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
2742 * is important so that we never end up logging to any foreign stderr, for example if we have
2743 * to log in a child process right before execve()'ing the actual binary, at a point in time
2744 * where socket activation stderr/stdout area already set up. */
2745 log_set_always_reopen_console(true);
2747 if (detect_container() <= 0) {
2749 /* Running outside of a container as PID 1 */
2750 log_set_target(LOG_TARGET_KMSG
);
2754 initrd_timestamp
= userspace_timestamp
;
2757 r
= mount_setup_early();
2759 error_message
= "Failed to mount early API filesystems";
2763 /* Let's open the log backend a second time, in case the first time didn't
2764 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2765 * available, and it previously wasn't. */
2768 disable_printk_ratelimit();
2770 r
= initialize_security(
2772 &security_start_timestamp
,
2773 &security_finish_timestamp
,
2779 if (mac_selinux_init() < 0) {
2780 error_message
= "Failed to initialize SELinux support";
2787 /* Set the default for later on, but don't actually open the logs like this for
2788 * now. Note that if we are transitioning from the initrd there might still be
2789 * journal fd open, and we shouldn't attempt opening that before we parsed
2790 * /proc/cmdline which might redirect output elsewhere. */
2791 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
2794 /* Running inside a container, as PID 1 */
2795 log_set_target(LOG_TARGET_CONSOLE
);
2798 /* For later on, see above... */
2799 log_set_target(LOG_TARGET_JOURNAL
);
2801 /* clear the kernel timestamp, because we are in a container */
2802 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2805 initialize_coredump(skip_setup
);
2807 r
= fixup_environment();
2809 log_emergency_errno(r
, "Failed to fix up PID 1 environment: %m");
2810 error_message
= "Failed to fix up PID1 environment";
2814 /* Try to figure out if we can use colors with the console. No need to do that for user
2815 * instances since they never log into the console. */
2816 log_show_color(colors_enabled());
2818 r
= make_null_stdio();
2820 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2822 /* Load the kernel modules early. */
2824 (void) kmod_setup();
2826 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
2827 r
= mount_setup(loaded_policy
, skip_setup
);
2829 error_message
= "Failed to mount API filesystems";
2833 /* The efivarfs is now mounted, let's read the random seed off it */
2834 (void) efi_take_random_seed();
2836 /* Cache command-line options passed from EFI variables */
2838 (void) cache_efi_options_variable();
2840 /* Running as user instance */
2842 log_set_always_reopen_console(true);
2843 log_set_target(LOG_TARGET_AUTO
);
2846 /* clear the kernel timestamp, because we are not PID 1 */
2847 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2849 /* Clear ambient capabilities, so services do not inherit them implicitly. Dropping them does
2850 * not affect the permitted and effective sets which are important for the manager itself to
2852 capability_ambient_set_apply(0, /* also_inherit= */ false);
2854 if (mac_selinux_init() < 0) {
2855 error_message
= "Failed to initialize SELinux support";
2860 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2861 * transitioning from the initrd to the main systemd or suchlike. */
2862 save_rlimits(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2864 /* Reset all signal handlers. */
2865 (void) reset_all_signal_handlers();
2866 (void) ignore_signals(SIGNALS_IGNORE
);
2868 (void) parse_configuration(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2870 r
= parse_argv(argc
, argv
);
2872 error_message
= "Failed to parse commandline arguments";
2876 r
= safety_checks();
2880 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
, ACTION_DUMP_CONFIGURATION_ITEMS
, ACTION_DUMP_BUS_PROPERTIES
, ACTION_BUS_INTROSPECT
))
2881 pager_open(arg_pager_flags
);
2883 if (arg_action
!= ACTION_RUN
)
2886 if (arg_action
== ACTION_HELP
) {
2887 retval
= help() < 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2889 } else if (arg_action
== ACTION_VERSION
) {
2892 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
2893 unit_dump_config_items(stdout
);
2894 retval
= EXIT_SUCCESS
;
2896 } else if (arg_action
== ACTION_DUMP_BUS_PROPERTIES
) {
2897 dump_bus_properties(stdout
);
2898 retval
= EXIT_SUCCESS
;
2900 } else if (arg_action
== ACTION_BUS_INTROSPECT
) {
2901 r
= bus_manager_introspect_implementations(stdout
, arg_bus_introspect
);
2902 retval
= r
>= 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
2906 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
2908 /* Move out of the way, so that we won't block unmounts */
2909 assert_se(chdir("/") == 0);
2911 if (arg_action
== ACTION_RUN
) {
2913 /* Apply the systemd.clock_usec= kernel command line switch */
2914 apply_clock_update();
2916 /* Apply random seed from kernel command line */
2917 cmdline_take_random_seed();
2920 /* A core pattern might have been specified via the cmdline. */
2921 initialize_core_pattern(skip_setup
);
2923 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
2926 /* Remember open file descriptors for later deserialization */
2927 r
= collect_fds(&fds
, &error_message
);
2931 /* Give up any control of the console, but make sure its initialized. */
2932 setup_console_terminal(skip_setup
);
2934 /* Open the logging devices, if possible and necessary */
2938 log_execution_mode(&first_boot
);
2940 r
= initialize_runtime(skip_setup
,
2942 &saved_rlimit_nofile
,
2943 &saved_rlimit_memlock
,
2948 r
= manager_new(arg_system
? LOOKUP_SCOPE_SYSTEM
: LOOKUP_SCOPE_USER
,
2949 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
2952 log_emergency_errno(r
, "Failed to allocate manager object: %m");
2953 error_message
= "Failed to allocate manager object";
2957 m
->timestamps
[MANAGER_TIMESTAMP_KERNEL
] = kernel_timestamp
;
2958 m
->timestamps
[MANAGER_TIMESTAMP_INITRD
] = initrd_timestamp
;
2959 m
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
] = userspace_timestamp
;
2960 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START
)] = security_start_timestamp
;
2961 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH
)] = security_finish_timestamp
;
2963 set_manager_defaults(m
);
2964 set_manager_settings(m
);
2965 manager_set_first_boot(m
, first_boot
);
2966 manager_set_switching_root(m
, arg_switched_root
);
2968 /* Remember whether we should queue the default job */
2969 queue_default_job
= !arg_serialization
|| arg_switched_root
;
2971 before_startup
= now(CLOCK_MONOTONIC
);
2973 r
= manager_startup(m
, arg_serialization
, fds
, /* root= */ NULL
);
2975 error_message
= "Failed to start up manager";
2979 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2980 fds
= fdset_free(fds
);
2981 arg_serialization
= safe_fclose(arg_serialization
);
2983 if (queue_default_job
) {
2984 r
= do_queue_default_job(m
, &error_message
);
2989 after_startup
= now(CLOCK_MONOTONIC
);
2991 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
2992 "Loaded units and determined initial transaction in %s.",
2993 FORMAT_TIMESPAN(after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
2995 if (arg_action
== ACTION_TEST
) {
2996 manager_test_summary(m
);
2997 retval
= EXIT_SUCCESS
;
3001 r
= invoke_main_loop(m
,
3002 &saved_rlimit_nofile
,
3003 &saved_rlimit_memlock
,
3010 assert(r
< 0 || IN_SET(r
, MANAGER_EXIT
, /* MANAGER_OK is not expected here. */
3017 MANAGER_SWITCH_ROOT
));
3023 arg_reboot_watchdog
= manager_get_watchdog(m
, WATCHDOG_REBOOT
);
3024 arg_kexec_watchdog
= manager_get_watchdog(m
, WATCHDOG_KEXEC
);
3025 m
= manager_free(m
);
3028 mac_selinux_finish();
3030 if (IN_SET(r
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
))
3033 &saved_rlimit_nofile
,
3034 &saved_rlimit_memlock
,
3038 &error_message
); /* This only returns if reexecution failed */
3040 arg_serialization
= safe_fclose(arg_serialization
);
3041 fds
= fdset_free(fds
);
3043 saved_env
= strv_free(saved_env
);
3045 #if HAVE_VALGRIND_VALGRIND_H
3046 /* If we are PID 1 and running under valgrind, then let's exit
3047 * here explicitly. valgrind will only generate nice output on
3048 * exit(), not on exec(), hence let's do the former not the
3050 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
3051 /* Cleanup watchdog_device strings for valgrind. We need them
3052 * in become_shutdown() so normally we cannot free them yet. */
3053 watchdog_free_device();
3059 #if HAS_FEATURE_ADDRESS_SANITIZER
3060 __lsan_do_leak_check();
3063 /* Try to invoke the shutdown binary unless we already failed.
3064 * If we failed above, we want to freeze after finishing cleanup. */
3065 if (r
>= 0 && shutdown_verb
) {
3066 r
= become_shutdown(shutdown_verb
, retval
);
3067 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3068 error_message
= "Failed to execute shutdown binary";
3071 watchdog_free_device();
3072 arg_watchdog_device
= mfree(arg_watchdog_device
);
3074 if (getpid_cached() == 1) {
3076 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
3077 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
3078 "%s.", error_message
);
3079 freeze_or_exit_or_reboot();