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"
55 #include "kmod-setup.h"
56 #include "limits-util.h"
57 #include "load-fragment.h"
59 #include "loopback-setup.h"
60 #include "machine-id-setup.h"
63 #include "manager-dump.h"
64 #include "manager-serialize.h"
65 #include "mkdir-label.h"
66 #include "mount-setup.h"
69 #include "parse-argument.h"
70 #include "parse-util.h"
71 #include "path-util.h"
72 #include "pretty-print.h"
73 #include "proc-cmdline.h"
74 #include "process-util.h"
75 #include "random-util.h"
76 #include "rlimit-util.h"
78 #include "seccomp-util.h"
80 #include "selinux-setup.h"
81 #include "selinux-util.h"
82 #include "signal-util.h"
83 #include "smack-setup.h"
85 #include "stat-util.h"
86 #include "stdio-util.h"
88 #include "switch-root.h"
89 #include "sysctl-util.h"
90 #include "terminal-util.h"
91 #include "time-util.h"
92 #include "umask-util.h"
93 #include "user-util.h"
98 #if HAS_FEATURE_ADDRESS_SANITIZER
99 #include <sanitizer/lsan_interface.h>
102 #define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
109 ACTION_DUMP_CONFIGURATION_ITEMS
,
110 ACTION_DUMP_BUS_PROPERTIES
,
111 ACTION_BUS_INTROSPECT
,
112 } arg_action
= ACTION_RUN
;
114 static const char *arg_bus_introspect
= NULL
;
116 /* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
117 * defaults are assigned in reset_arguments() below. */
118 static char *arg_default_unit
;
119 static bool arg_system
;
122 bool arg_crash_shell
;
123 bool arg_crash_reboot
;
124 static char *arg_confirm_spawn
;
125 static ShowStatus arg_show_status
;
126 static StatusUnitFormat arg_status_unit_format
;
127 static bool arg_switched_root
;
128 static PagerFlags arg_pager_flags
;
129 static bool arg_service_watchdogs
;
130 static ExecOutput arg_default_std_output
;
131 static ExecOutput arg_default_std_error
;
132 static usec_t arg_default_restart_usec
;
133 static usec_t arg_default_timeout_start_usec
;
134 static usec_t arg_default_timeout_stop_usec
;
135 static usec_t arg_default_timeout_abort_usec
;
136 static bool arg_default_timeout_abort_set
;
137 static usec_t arg_default_start_limit_interval
;
138 static unsigned arg_default_start_limit_burst
;
139 static usec_t arg_runtime_watchdog
;
140 static usec_t arg_reboot_watchdog
;
141 static usec_t arg_kexec_watchdog
;
142 static usec_t arg_pretimeout_watchdog
;
143 static char *arg_early_core_pattern
;
144 static char *arg_watchdog_pretimeout_governor
;
145 static char *arg_watchdog_device
;
146 static char **arg_default_environment
;
147 static char **arg_manager_environment
;
148 static struct rlimit
*arg_default_rlimit
[_RLIMIT_MAX
];
149 static uint64_t arg_capability_bounding_set
;
150 static bool arg_no_new_privs
;
151 static nsec_t arg_timer_slack_nsec
;
152 static usec_t arg_default_timer_accuracy_usec
;
153 static Set
* arg_syscall_archs
;
154 static FILE* arg_serialization
;
155 static int arg_default_cpu_accounting
;
156 static bool arg_default_io_accounting
;
157 static bool arg_default_ip_accounting
;
158 static bool arg_default_blockio_accounting
;
159 static bool arg_default_memory_accounting
;
160 static bool arg_default_tasks_accounting
;
161 static TasksMax arg_default_tasks_max
;
162 static sd_id128_t arg_machine_id
;
163 static EmergencyAction arg_cad_burst_action
;
164 static OOMPolicy arg_default_oom_policy
;
165 static CPUSet arg_cpu_affinity
;
166 static NUMAPolicy arg_numa_policy
;
167 static usec_t arg_clock_usec
;
168 static void *arg_random_seed
;
169 static size_t arg_random_seed_size
;
170 static int arg_default_oom_score_adjust
;
171 static bool arg_default_oom_score_adjust_set
;
173 /* A copy of the original environment block */
174 static char **saved_env
= NULL
;
176 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
177 const struct rlimit
*saved_rlimit_memlock
);
179 static int manager_find_user_config_paths(char ***ret_files
, char ***ret_dirs
) {
180 _cleanup_free_
char *base
= NULL
;
181 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
184 r
= xdg_user_config_dir(&base
, "/systemd");
188 r
= strv_extendf(&files
, "%s/user.conf", base
);
192 r
= strv_extend(&files
, PKGSYSCONFDIR
"/user.conf");
196 r
= strv_consume(&dirs
, TAKE_PTR(base
));
200 r
= strv_extend_strv(&dirs
, CONF_PATHS_STRV("systemd"), false);
204 *ret_files
= TAKE_PTR(files
);
205 *ret_dirs
= TAKE_PTR(dirs
);
209 static int console_setup(void) {
210 _cleanup_close_
int tty_fd
= -1;
213 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
215 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
217 /* We don't want to force text mode. plymouth may be showing
218 * pictures already from initrd. */
219 r
= reset_terminal_fd(tty_fd
, false);
221 return log_error_errno(r
, "Failed to reset /dev/console: %m");
226 static int set_machine_id(const char *m
) {
230 if (sd_id128_from_string(m
, &t
) < 0)
233 if (sd_id128_is_null(t
))
240 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
245 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
247 if (proc_cmdline_value_missing(key
, value
))
250 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
251 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
252 else if (in_initrd() == !!startswith(key
, "rd."))
253 return free_and_strdup_warn(&arg_default_unit
, value
);
255 } else if (proc_cmdline_key_streq(key
, "systemd.dump_core")) {
257 r
= value
? parse_boolean(value
) : true;
259 log_warning_errno(r
, "Failed to parse dump core switch %s, ignoring: %m", value
);
263 } else if (proc_cmdline_key_streq(key
, "systemd.early_core_pattern")) {
265 if (proc_cmdline_value_missing(key
, value
))
268 if (path_is_absolute(value
))
269 (void) parse_path_argument(value
, false, &arg_early_core_pattern
);
271 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value
);
273 } else if (proc_cmdline_key_streq(key
, "systemd.crash_chvt")) {
276 arg_crash_chvt
= 0; /* turn on */
278 r
= parse_crash_chvt(value
, &arg_crash_chvt
);
280 log_warning_errno(r
, "Failed to parse crash chvt switch %s, ignoring: %m", value
);
283 } else if (proc_cmdline_key_streq(key
, "systemd.crash_shell")) {
285 r
= value
? parse_boolean(value
) : true;
287 log_warning_errno(r
, "Failed to parse crash shell switch %s, ignoring: %m", value
);
291 } else if (proc_cmdline_key_streq(key
, "systemd.crash_reboot")) {
293 r
= value
? parse_boolean(value
) : true;
295 log_warning_errno(r
, "Failed to parse crash reboot switch %s, ignoring: %m", value
);
297 arg_crash_reboot
= r
;
299 } else if (proc_cmdline_key_streq(key
, "systemd.confirm_spawn")) {
302 r
= parse_confirm_spawn(value
, &s
);
304 log_warning_errno(r
, "Failed to parse confirm_spawn switch %s, ignoring: %m", value
);
306 free_and_replace(arg_confirm_spawn
, s
);
308 } else if (proc_cmdline_key_streq(key
, "systemd.service_watchdogs")) {
310 r
= value
? parse_boolean(value
) : true;
312 log_warning_errno(r
, "Failed to parse service watchdog switch %s, ignoring: %m", value
);
314 arg_service_watchdogs
= r
;
316 } else if (proc_cmdline_key_streq(key
, "systemd.show_status")) {
319 r
= parse_show_status(value
, &arg_show_status
);
321 log_warning_errno(r
, "Failed to parse show status switch %s, ignoring: %m", value
);
323 arg_show_status
= SHOW_STATUS_YES
;
325 } else if (proc_cmdline_key_streq(key
, "systemd.status_unit_format")) {
327 if (proc_cmdline_value_missing(key
, value
))
330 r
= status_unit_format_from_string(value
);
332 log_warning_errno(r
, "Failed to parse %s=%s, ignoring: %m", key
, value
);
334 arg_status_unit_format
= r
;
336 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_output")) {
338 if (proc_cmdline_value_missing(key
, value
))
341 r
= exec_output_from_string(value
);
343 log_warning_errno(r
, "Failed to parse default standard output switch %s, ignoring: %m", value
);
345 arg_default_std_output
= r
;
347 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_error")) {
349 if (proc_cmdline_value_missing(key
, value
))
352 r
= exec_output_from_string(value
);
354 log_warning_errno(r
, "Failed to parse default standard error switch %s, ignoring: %m", value
);
356 arg_default_std_error
= r
;
358 } else if (streq(key
, "systemd.setenv")) {
360 if (proc_cmdline_value_missing(key
, value
))
363 if (!env_assignment_is_valid(value
))
364 log_warning("Environment variable assignment '%s' is not valid. Ignoring.", value
);
366 r
= strv_env_replace_strdup(&arg_default_environment
, value
);
371 } else if (proc_cmdline_key_streq(key
, "systemd.machine_id")) {
373 if (proc_cmdline_value_missing(key
, value
))
376 r
= set_machine_id(value
);
378 log_warning_errno(r
, "MachineID '%s' is not valid, ignoring: %m", value
);
380 } else if (proc_cmdline_key_streq(key
, "systemd.default_timeout_start_sec")) {
382 if (proc_cmdline_value_missing(key
, value
))
385 r
= parse_sec(value
, &arg_default_timeout_start_usec
);
387 log_warning_errno(r
, "Failed to parse default start timeout '%s', ignoring: %m", value
);
389 if (arg_default_timeout_start_usec
<= 0)
390 arg_default_timeout_start_usec
= USEC_INFINITY
;
392 } else if (proc_cmdline_key_streq(key
, "systemd.cpu_affinity")) {
394 if (proc_cmdline_value_missing(key
, value
))
397 r
= parse_cpu_set(value
, &arg_cpu_affinity
);
399 log_warning_errno(r
, "Failed to parse CPU affinity mask '%s', ignoring: %m", value
);
401 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_device")) {
403 if (proc_cmdline_value_missing(key
, value
))
406 (void) parse_path_argument(value
, false, &arg_watchdog_device
);
408 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_sec")) {
410 if (proc_cmdline_value_missing(key
, value
))
413 if (streq(value
, "default"))
414 arg_runtime_watchdog
= USEC_INFINITY
;
415 else if (streq(value
, "off"))
416 arg_runtime_watchdog
= 0;
418 r
= parse_sec(value
, &arg_runtime_watchdog
);
420 log_warning_errno(r
, "Failed to parse systemd.watchdog_sec= argument '%s', ignoring: %m", value
);
425 arg_kexec_watchdog
= arg_reboot_watchdog
= arg_runtime_watchdog
;
427 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pre_sec")) {
429 if (proc_cmdline_value_missing(key
, value
))
432 if (streq(value
, "default"))
433 arg_pretimeout_watchdog
= USEC_INFINITY
;
434 else if (streq(value
, "off"))
435 arg_pretimeout_watchdog
= 0;
437 r
= parse_sec(value
, &arg_pretimeout_watchdog
);
439 log_warning_errno(r
, "Failed to parse systemd.watchdog_pre_sec= argument '%s', ignoring: %m", value
);
444 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pretimeout_governor")) {
446 if (proc_cmdline_value_missing(key
, value
) || isempty(value
)) {
447 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
451 if (!string_is_safe(value
)) {
452 log_warning("Watchdog pretimeout governor '%s' is not valid, ignoring.", value
);
456 return free_and_strdup_warn(&arg_watchdog_pretimeout_governor
, value
);
458 } else if (proc_cmdline_key_streq(key
, "systemd.clock_usec")) {
460 if (proc_cmdline_value_missing(key
, value
))
463 r
= safe_atou64(value
, &arg_clock_usec
);
465 log_warning_errno(r
, "Failed to parse systemd.clock_usec= argument, ignoring: %s", value
);
467 } else if (proc_cmdline_key_streq(key
, "systemd.random_seed")) {
471 if (proc_cmdline_value_missing(key
, value
))
474 r
= unbase64mem(value
, SIZE_MAX
, &p
, &sz
);
476 log_warning_errno(r
, "Failed to parse systemd.random_seed= argument, ignoring: %s", value
);
478 free(arg_random_seed
);
479 arg_random_seed
= sz
> 0 ? p
: mfree(p
);
480 arg_random_seed_size
= sz
;
482 } else if (streq(key
, "quiet") && !value
) {
484 if (arg_show_status
== _SHOW_STATUS_INVALID
)
485 arg_show_status
= SHOW_STATUS_ERROR
;
487 } else if (streq(key
, "debug") && !value
) {
489 /* Note that log_parse_environment() handles 'debug'
490 * too, and sets the log level to LOG_DEBUG. */
492 if (detect_container() > 0)
493 log_set_target(LOG_TARGET_CONSOLE
);
498 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
499 target
= runlevel_to_target(key
);
501 return free_and_strdup_warn(&arg_default_unit
, target
);
507 #define DEFINE_SETTER(name, func, descr) \
508 static int name(const char *unit, \
509 const char *filename, \
511 const char *section, \
512 unsigned section_line, \
513 const char *lvalue, \
515 const char *rvalue, \
527 log_syntax(unit, LOG_ERR, filename, line, r, \
528 "Invalid " descr "'%s': %m", \
534 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level");
535 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target");
536 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color");
537 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location");
538 DEFINE_SETTER(config_parse_time
, log_show_time_from_string
, "time");
540 static int config_parse_default_timeout_abort(
542 const char *filename
,
545 unsigned section_line
,
553 r
= config_parse_timeout_abort(unit
, filename
, line
, section
, section_line
, lvalue
, ltype
, rvalue
,
554 &arg_default_timeout_abort_usec
, userdata
);
556 arg_default_timeout_abort_set
= r
;
560 static int config_parse_oom_score_adjust(
562 const char *filename
,
565 unsigned section_line
,
574 if (isempty(rvalue
)) {
575 arg_default_oom_score_adjust_set
= false;
579 r
= parse_oom_score_adjust(rvalue
, &oa
);
581 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse the OOM score adjust value '%s', ignoring: %m", rvalue
);
585 arg_default_oom_score_adjust
= oa
;
586 arg_default_oom_score_adjust_set
= true;
591 static int parse_config_file(void) {
592 const ConfigTableItem items
[] = {
593 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
594 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
595 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
596 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
597 { "Manager", "LogTime", config_parse_time
, 0, NULL
},
598 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
599 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, &arg_crash_chvt
},
600 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, &arg_crash_chvt
},
601 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
602 { "Manager", "CrashReboot", config_parse_bool
, 0, &arg_crash_reboot
},
603 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
604 { "Manager", "StatusUnitFormat", config_parse_status_unit_format
, 0, &arg_status_unit_format
},
605 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, &arg_cpu_affinity
},
606 { "Manager", "NUMAPolicy", config_parse_numa_policy
, 0, &arg_numa_policy
.type
},
607 { "Manager", "NUMAMask", config_parse_numa_mask
, 0, &arg_numa_policy
},
608 { "Manager", "JoinControllers", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
609 { "Manager", "RuntimeWatchdogSec", config_parse_watchdog_sec
, 0, &arg_runtime_watchdog
},
610 { "Manager", "RuntimeWatchdogPreSec", config_parse_watchdog_sec
, 0, &arg_pretimeout_watchdog
},
611 { "Manager", "RebootWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
},
612 { "Manager", "ShutdownWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
}, /* obsolete alias */
613 { "Manager", "KExecWatchdogSec", config_parse_watchdog_sec
, 0, &arg_kexec_watchdog
},
614 { "Manager", "WatchdogDevice", config_parse_path
, 0, &arg_watchdog_device
},
615 { "Manager", "RuntimeWatchdogPreGovernor", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &arg_watchdog_pretimeout_governor
},
616 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
617 { "Manager", "NoNewPrivileges", config_parse_bool
, 0, &arg_no_new_privs
},
619 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
621 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
622 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_default_timer_accuracy_usec
},
623 { "Manager", "DefaultStandardOutput", config_parse_output_restricted
, 0, &arg_default_std_output
},
624 { "Manager", "DefaultStandardError", config_parse_output_restricted
, 0, &arg_default_std_error
},
625 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_default_timeout_start_usec
},
626 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_default_timeout_stop_usec
},
627 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort
, 0, NULL
},
628 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_default_restart_usec
},
629 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_default_start_limit_interval
}, /* obsolete alias */
630 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec
, 0, &arg_default_start_limit_interval
},
631 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_default_start_limit_burst
},
632 { "Manager", "DefaultEnvironment", config_parse_environ
, 0, &arg_default_environment
},
633 { "Manager", "ManagerEnvironment", config_parse_environ
, 0, &arg_manager_environment
},
634 { "Manager", "DefaultLimitCPU", config_parse_rlimit
, RLIMIT_CPU
, arg_default_rlimit
},
635 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit
, RLIMIT_FSIZE
, arg_default_rlimit
},
636 { "Manager", "DefaultLimitDATA", config_parse_rlimit
, RLIMIT_DATA
, arg_default_rlimit
},
637 { "Manager", "DefaultLimitSTACK", config_parse_rlimit
, RLIMIT_STACK
, arg_default_rlimit
},
638 { "Manager", "DefaultLimitCORE", config_parse_rlimit
, RLIMIT_CORE
, arg_default_rlimit
},
639 { "Manager", "DefaultLimitRSS", config_parse_rlimit
, RLIMIT_RSS
, arg_default_rlimit
},
640 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit
, RLIMIT_NOFILE
, arg_default_rlimit
},
641 { "Manager", "DefaultLimitAS", config_parse_rlimit
, RLIMIT_AS
, arg_default_rlimit
},
642 { "Manager", "DefaultLimitNPROC", config_parse_rlimit
, RLIMIT_NPROC
, arg_default_rlimit
},
643 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit
, RLIMIT_MEMLOCK
, arg_default_rlimit
},
644 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit
, RLIMIT_LOCKS
, arg_default_rlimit
},
645 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit
, RLIMIT_SIGPENDING
, arg_default_rlimit
},
646 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit
, RLIMIT_MSGQUEUE
, arg_default_rlimit
},
647 { "Manager", "DefaultLimitNICE", config_parse_rlimit
, RLIMIT_NICE
, arg_default_rlimit
},
648 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit
, RLIMIT_RTPRIO
, arg_default_rlimit
},
649 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit
, RLIMIT_RTTIME
, arg_default_rlimit
},
650 { "Manager", "DefaultCPUAccounting", config_parse_tristate
, 0, &arg_default_cpu_accounting
},
651 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_default_io_accounting
},
652 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_default_ip_accounting
},
653 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_default_blockio_accounting
},
654 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_default_memory_accounting
},
655 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_default_tasks_accounting
},
656 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_default_tasks_max
},
657 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, 0, &arg_cad_burst_action
},
658 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy
, 0, &arg_default_oom_policy
},
659 { "Manager", "DefaultOOMScoreAdjust", config_parse_oom_score_adjust
, 0, NULL
},
663 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
668 suffix
= "system.conf.d";
670 r
= manager_find_user_config_paths(&files
, &dirs
);
672 return log_error_errno(r
, "Failed to determine config file paths: %m");
674 suffix
= "user.conf.d";
677 (void) config_parse_many(
678 (const char* const*) (files
?: STRV_MAKE(PKGSYSCONFDIR
"/system.conf")),
679 (const char* const*) (dirs
?: CONF_PATHS_STRV("systemd")),
682 config_item_table_lookup
, items
,
687 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we use
688 * USEC_INFINITY like everywhere else. */
689 if (arg_default_timeout_start_usec
<= 0)
690 arg_default_timeout_start_usec
= USEC_INFINITY
;
691 if (arg_default_timeout_stop_usec
<= 0)
692 arg_default_timeout_stop_usec
= USEC_INFINITY
;
697 static void set_manager_defaults(Manager
*m
) {
701 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
702 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
703 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
705 m
->default_timer_accuracy_usec
= arg_default_timer_accuracy_usec
;
706 m
->default_std_output
= arg_default_std_output
;
707 m
->default_std_error
= arg_default_std_error
;
708 m
->default_timeout_start_usec
= arg_default_timeout_start_usec
;
709 m
->default_timeout_stop_usec
= arg_default_timeout_stop_usec
;
710 m
->default_timeout_abort_usec
= arg_default_timeout_abort_usec
;
711 m
->default_timeout_abort_set
= arg_default_timeout_abort_set
;
712 m
->default_restart_usec
= arg_default_restart_usec
;
713 m
->default_start_limit_interval
= arg_default_start_limit_interval
;
714 m
->default_start_limit_burst
= arg_default_start_limit_burst
;
716 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
717 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
718 if (arg_default_cpu_accounting
>= 0)
719 m
->default_cpu_accounting
= arg_default_cpu_accounting
;
721 m
->default_cpu_accounting
= cpu_accounting_is_cheap();
723 m
->default_io_accounting
= arg_default_io_accounting
;
724 m
->default_ip_accounting
= arg_default_ip_accounting
;
725 m
->default_blockio_accounting
= arg_default_blockio_accounting
;
726 m
->default_memory_accounting
= arg_default_memory_accounting
;
727 m
->default_tasks_accounting
= arg_default_tasks_accounting
;
728 m
->default_tasks_max
= arg_default_tasks_max
;
729 m
->default_oom_policy
= arg_default_oom_policy
;
730 m
->default_oom_score_adjust_set
= arg_default_oom_score_adjust_set
;
731 m
->default_oom_score_adjust
= arg_default_oom_score_adjust
;
733 (void) manager_set_default_rlimits(m
, arg_default_rlimit
);
735 (void) manager_default_environment(m
);
736 (void) manager_transient_environment_add(m
, arg_default_environment
);
739 static void set_manager_settings(Manager
*m
) {
744 /* Propagates the various manager settings into the manager object, i.e. properties that
745 * effect the manager itself (as opposed to just being inherited into newly allocated
746 * units, see set_manager_defaults() above). */
748 m
->confirm_spawn
= arg_confirm_spawn
;
749 m
->service_watchdogs
= arg_service_watchdogs
;
750 m
->cad_burst_action
= arg_cad_burst_action
;
752 manager_set_watchdog(m
, WATCHDOG_RUNTIME
, arg_runtime_watchdog
);
753 manager_set_watchdog(m
, WATCHDOG_REBOOT
, arg_reboot_watchdog
);
754 manager_set_watchdog(m
, WATCHDOG_KEXEC
, arg_kexec_watchdog
);
755 manager_set_watchdog(m
, WATCHDOG_PRETIMEOUT
, arg_pretimeout_watchdog
);
756 r
= manager_set_watchdog_pretimeout_governor(m
, arg_watchdog_pretimeout_governor
);
758 log_warning_errno(r
, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor
);
760 manager_set_show_status(m
, arg_show_status
, "commandline");
761 m
->status_unit_format
= arg_status_unit_format
;
764 static int parse_argv(int argc
, char *argv
[]) {
766 ARG_LOG_LEVEL
= 0x100,
777 ARG_DUMP_CONFIGURATION_ITEMS
,
778 ARG_DUMP_BUS_PROPERTIES
,
788 ARG_DEFAULT_STD_OUTPUT
,
789 ARG_DEFAULT_STD_ERROR
,
791 ARG_SERVICE_WATCHDOGS
,
794 static const struct option options
[] = {
795 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
796 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
797 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
798 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
799 { "log-time", optional_argument
, NULL
, ARG_LOG_TIME
},
800 { "unit", required_argument
, NULL
, ARG_UNIT
},
801 { "system", no_argument
, NULL
, ARG_SYSTEM
},
802 { "user", no_argument
, NULL
, ARG_USER
},
803 { "test", no_argument
, NULL
, ARG_TEST
},
804 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
805 { "help", no_argument
, NULL
, 'h' },
806 { "version", no_argument
, NULL
, ARG_VERSION
},
807 { "dump-configuration-items", no_argument
, NULL
, ARG_DUMP_CONFIGURATION_ITEMS
},
808 { "dump-bus-properties", no_argument
, NULL
, ARG_DUMP_BUS_PROPERTIES
},
809 { "bus-introspect", required_argument
, NULL
, ARG_BUS_INTROSPECT
},
810 { "dump-core", optional_argument
, NULL
, ARG_DUMP_CORE
},
811 { "crash-chvt", required_argument
, NULL
, ARG_CRASH_CHVT
},
812 { "crash-shell", optional_argument
, NULL
, ARG_CRASH_SHELL
},
813 { "crash-reboot", optional_argument
, NULL
, ARG_CRASH_REBOOT
},
814 { "confirm-spawn", optional_argument
, NULL
, ARG_CONFIRM_SPAWN
},
815 { "show-status", optional_argument
, NULL
, ARG_SHOW_STATUS
},
816 { "deserialize", required_argument
, NULL
, ARG_DESERIALIZE
},
817 { "switched-root", no_argument
, NULL
, ARG_SWITCHED_ROOT
},
818 { "default-standard-output", required_argument
, NULL
, ARG_DEFAULT_STD_OUTPUT
, },
819 { "default-standard-error", required_argument
, NULL
, ARG_DEFAULT_STD_ERROR
, },
820 { "machine-id", required_argument
, NULL
, ARG_MACHINE_ID
},
821 { "service-watchdogs", required_argument
, NULL
, ARG_SERVICE_WATCHDOGS
},
826 bool user_arg_seen
= false;
831 if (getpid_cached() == 1)
834 while ((c
= getopt_long(argc
, argv
, "hDbsz:", options
, NULL
)) >= 0)
839 r
= log_set_max_level_from_string(optarg
);
841 return log_error_errno(r
, "Failed to parse log level \"%s\": %m", optarg
);
846 r
= log_set_target_from_string(optarg
);
848 return log_error_errno(r
, "Failed to parse log target \"%s\": %m", optarg
);
855 r
= log_show_color_from_string(optarg
);
857 return log_error_errno(r
, "Failed to parse log color setting \"%s\": %m",
860 log_show_color(true);
864 case ARG_LOG_LOCATION
:
866 r
= log_show_location_from_string(optarg
);
868 return log_error_errno(r
, "Failed to parse log location setting \"%s\": %m",
871 log_show_location(true);
878 r
= log_show_time_from_string(optarg
);
880 return log_error_errno(r
, "Failed to parse log time setting \"%s\": %m",
887 case ARG_DEFAULT_STD_OUTPUT
:
888 r
= exec_output_from_string(optarg
);
890 return log_error_errno(r
, "Failed to parse default standard output setting \"%s\": %m",
892 arg_default_std_output
= r
;
895 case ARG_DEFAULT_STD_ERROR
:
896 r
= exec_output_from_string(optarg
);
898 return log_error_errno(r
, "Failed to parse default standard error output setting \"%s\": %m",
900 arg_default_std_error
= r
;
904 r
= free_and_strdup(&arg_default_unit
, optarg
);
906 return log_error_errno(r
, "Failed to set default unit \"%s\": %m", optarg
);
916 user_arg_seen
= true;
920 arg_action
= ACTION_TEST
;
924 arg_pager_flags
|= PAGER_DISABLE
;
928 arg_action
= ACTION_VERSION
;
931 case ARG_DUMP_CONFIGURATION_ITEMS
:
932 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
935 case ARG_DUMP_BUS_PROPERTIES
:
936 arg_action
= ACTION_DUMP_BUS_PROPERTIES
;
939 case ARG_BUS_INTROSPECT
:
940 arg_bus_introspect
= optarg
;
941 arg_action
= ACTION_BUS_INTROSPECT
;
945 r
= parse_boolean_argument("--dump-core", optarg
, &arg_dump_core
);
951 r
= parse_crash_chvt(optarg
, &arg_crash_chvt
);
953 return log_error_errno(r
, "Failed to parse crash virtual terminal index: \"%s\": %m",
957 case ARG_CRASH_SHELL
:
958 r
= parse_boolean_argument("--crash-shell", optarg
, &arg_crash_shell
);
963 case ARG_CRASH_REBOOT
:
964 r
= parse_boolean_argument("--crash-reboot", optarg
, &arg_crash_reboot
);
969 case ARG_CONFIRM_SPAWN
:
970 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
972 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
974 return log_error_errno(r
, "Failed to parse confirm spawn option: \"%s\": %m",
978 case ARG_SERVICE_WATCHDOGS
:
979 r
= parse_boolean_argument("--service-watchdogs=", optarg
, &arg_service_watchdogs
);
984 case ARG_SHOW_STATUS
:
986 r
= parse_show_status(optarg
, &arg_show_status
);
988 return log_error_errno(r
, "Failed to parse show status boolean: \"%s\": %m",
991 arg_show_status
= SHOW_STATUS_YES
;
994 case ARG_DESERIALIZE
: {
998 r
= safe_atoi(optarg
, &fd
);
1000 log_error_errno(r
, "Failed to parse deserialize option \"%s\": %m", optarg
);
1002 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1003 "Invalid deserialize fd: %d",
1006 (void) fd_cloexec(fd
, true);
1008 f
= fdopen(fd
, "r");
1010 return log_error_errno(errno
, "Failed to open serialization fd %d: %m", fd
);
1012 safe_fclose(arg_serialization
);
1013 arg_serialization
= f
;
1018 case ARG_SWITCHED_ROOT
:
1019 arg_switched_root
= true;
1022 case ARG_MACHINE_ID
:
1023 r
= set_machine_id(optarg
);
1025 return log_error_errno(r
, "MachineID '%s' is not valid: %m", optarg
);
1029 arg_action
= ACTION_HELP
;
1033 log_set_max_level(LOG_DEBUG
);
1039 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1040 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1043 if (getpid_cached() != 1)
1049 assert_not_reached();
1052 if (optind
< argc
&& getpid_cached() != 1)
1053 /* Hmm, when we aren't run as init system let's complain about excess arguments */
1054 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Excess arguments.");
1056 if (arg_action
== ACTION_RUN
&& !arg_system
&& !user_arg_seen
)
1057 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1058 "Explicit --user argument required to run as user manager.");
1063 static int help(void) {
1064 _cleanup_free_
char *link
= NULL
;
1067 r
= terminal_urlify_man("systemd", "1", &link
);
1071 printf("%s [OPTIONS...]\n\n"
1072 "%sStarts and monitors system and user services.%s\n\n"
1073 "This program takes no positional arguments.\n\n"
1075 " -h --help Show this help\n"
1076 " --version Show version\n"
1077 " --test Determine initial transaction, dump it and exit\n"
1078 " --system In combination with --test: operate as system service manager\n"
1079 " --user In combination with --test: operate as per-user service manager\n"
1080 " --no-pager Do not pipe output into a pager\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 bootup\n"
1091 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
1092 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1093 " --log-color[=BOOL] Highlight important log messages\n"
1094 " --log-location[=BOOL] Include code location in log messages\n"
1095 " --log-time[=BOOL] Prefix log messages with current time\n"
1096 " --default-standard-output= Set default standard output for services\n"
1097 " --default-standard-error= Set default standard error output for services\n"
1098 "\nSee the %s for details.\n",
1099 program_invocation_short_name
,
1109 static int prepare_reexecute(
1113 bool switching_root
) {
1115 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1116 _cleanup_fclose_
FILE *f
= NULL
;
1123 r
= manager_open_serialization(m
, &f
);
1125 return log_error_errno(r
, "Failed to create serialization file: %m");
1127 /* Make sure nothing is really destructed when we shut down */
1129 bus_manager_send_reloading(m
, true);
1135 r
= manager_serialize(m
, f
, fds
, switching_root
);
1139 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1140 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1142 r
= fd_cloexec(fileno(f
), false);
1144 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1146 r
= fdset_cloexec(fds
, false);
1148 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1150 *ret_f
= TAKE_PTR(f
);
1151 *ret_fds
= TAKE_PTR(fds
);
1156 static void bump_file_max_and_nr_open(void) {
1158 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
1159 * numbers of file descriptors are no longer a performance problem and their memory is properly
1160 * tracked by memcg, thus counting them and limiting them in another two layers of limits is
1161 * unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
1162 * on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
1164 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1168 #if BUMP_PROC_SYS_FS_FILE_MAX
1169 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
1170 * different, but the operation would fail silently.) */
1171 r
= sysctl_writef("fs/file-max", "%li\n", LONG_MAX
);
1173 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.file-max, ignoring: %m");
1176 #if BUMP_PROC_SYS_FS_NR_OPEN
1179 /* Argh! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know
1180 * what they are. The expression by which the maximum is determined is dependent on the architecture,
1181 * and is something we don't really want to copy to userspace, as it is dependent on implementation
1182 * details of the kernel. Since the kernel doesn't expose the maximum value to us, we can only try
1183 * and hope. Hence, let's start with INT_MAX, and then keep halving the value until we find one that
1184 * works. Ugly? Yes, absolutely, but kernel APIs are kernel APIs, so what do can we do... 🤯 */
1189 v
&= ~(__SIZEOF_POINTER__
- 1); /* Round down to next multiple of the pointer size */
1191 log_warning("Can't bump fs.nr_open, value too small.");
1197 log_error_errno(k
, "Failed to read fs.nr_open: %m");
1200 if (k
>= v
) { /* Already larger */
1201 log_debug("Skipping bump, value is already larger.");
1205 r
= sysctl_writef("fs/nr_open", "%i\n", v
);
1207 log_debug("Couldn't write fs.nr_open as %i, halving it.", v
);
1212 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.nr_open, ignoring: %m");
1216 log_debug("Successfully bumped fs.nr_open to %i", v
);
1222 static int bump_rlimit_nofile(const struct rlimit
*saved_rlimit
) {
1223 struct rlimit new_rlimit
;
1226 /* Get the underlying absolute limit the kernel enforces */
1227 nr
= read_nr_open();
1229 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1230 new_rlimit
= (struct rlimit
) {
1231 .rlim_cur
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_cur
),
1232 .rlim_max
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_max
),
1235 /* Shortcut if nothing changes. */
1236 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_max
&&
1237 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_cur
) {
1238 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1242 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1243 * both hard and soft. */
1244 r
= setrlimit_closest(RLIMIT_NOFILE
, &new_rlimit
);
1246 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1251 static int bump_rlimit_memlock(const struct rlimit
*saved_rlimit
) {
1252 struct rlimit new_rlimit
;
1256 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
1257 * which should normally disable such checks. We need them to implement IPAddressAllow= and
1258 * IPAddressDeny=, hence let's bump the value high enough for our user. */
1260 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1261 * must be unsigned, hence this is a given, but let's make this clear here. */
1262 assert_cc(RLIM_INFINITY
> 0);
1264 mm
= physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
1265 * physical RAM. We allow an eighth to be locked by us, just to
1268 new_rlimit
= (struct rlimit
) {
1269 .rlim_cur
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_cur
, mm
),
1270 .rlim_max
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_max
, mm
),
1273 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_cur
&&
1274 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_max
) {
1275 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1279 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &new_rlimit
);
1281 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1286 static void test_usr(void) {
1288 /* Check that /usr is either on the same file system as / or mounted already. */
1290 if (dir_is_empty("/usr") <= 0)
1293 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1294 "Some things will probably break (sometimes even silently) in mysterious ways. "
1295 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1298 static int enforce_syscall_archs(Set
*archs
) {
1302 if (!is_seccomp_available())
1305 r
= seccomp_restrict_archs(arg_syscall_archs
);
1307 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1312 static int status_welcome(void) {
1313 _cleanup_free_
char *pretty_name
= NULL
, *ansi_color
= NULL
;
1316 if (!show_status_on(arg_show_status
))
1319 r
= parse_os_release(NULL
,
1320 "PRETTY_NAME", &pretty_name
,
1321 "ANSI_COLOR", &ansi_color
);
1323 log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1324 "Failed to read os-release file, ignoring: %m");
1326 if (log_get_show_color())
1327 return status_printf(NULL
, 0,
1328 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1329 isempty(ansi_color
) ? "1" : ansi_color
,
1330 isempty(pretty_name
) ? "Linux" : pretty_name
);
1332 return status_printf(NULL
, 0,
1333 "\nWelcome to %s!\n",
1334 isempty(pretty_name
) ? "Linux" : pretty_name
);
1337 static int write_container_id(void) {
1339 int r
= 0; /* avoid false maybe-uninitialized warning */
1341 c
= getenv("container");
1345 RUN_WITH_UMASK(0022)
1346 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1348 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1353 static int bump_unix_max_dgram_qlen(void) {
1354 _cleanup_free_
char *qlen
= NULL
;
1358 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
1359 * the value really really early during boot, so that it is actually applied to all our sockets,
1360 * including the $NOTIFY_SOCKET one. */
1362 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1364 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1365 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1367 r
= safe_atolu(qlen
, &v
);
1369 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen
);
1371 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1374 r
= write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER
,
1375 "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN
);
1377 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1378 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1383 static int fixup_environment(void) {
1384 _cleanup_free_
char *term
= NULL
;
1388 /* Only fix up the environment when we are started as PID 1 */
1389 if (getpid_cached() != 1)
1392 /* We expect the environment to be set correctly if run inside a container. */
1393 if (detect_container() > 0)
1396 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
1397 * backend device used by the console. We try to make a better guess here since some consoles might
1398 * not have support for color mode for example.
1400 * However if TERM was configured through the kernel command line then leave it alone. */
1401 r
= proc_cmdline_get_key("TERM", 0, &term
);
1405 t
= term
?: default_term_for_tty("/dev/console");
1407 if (setenv("TERM", t
, 1) < 0)
1410 /* The kernels sets HOME=/ for init. Let's undo this. */
1411 if (path_equal_ptr(getenv("HOME"), "/"))
1412 assert_se(unsetenv("HOME") == 0);
1417 static void redirect_telinit(int argc
, char *argv
[]) {
1419 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1421 #if HAVE_SYSV_COMPAT
1422 if (getpid_cached() == 1)
1425 if (!invoked_as(argv
, "init"))
1428 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1429 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1434 static int become_shutdown(
1435 const char *shutdown_verb
,
1438 char log_level
[DECIMAL_STR_MAX(int) + 1],
1439 exit_code
[DECIMAL_STR_MAX(uint8_t) + 1],
1440 timeout
[DECIMAL_STR_MAX(usec_t
) + 1];
1442 const char* command_line
[13] = {
1443 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1445 "--timeout", timeout
,
1446 "--log-level", log_level
,
1450 _cleanup_strv_free_
char **env_block
= NULL
;
1451 usec_t watchdog_timer
= 0;
1455 assert(shutdown_verb
);
1456 assert(!command_line
[pos
]);
1457 env_block
= strv_copy(environ
);
1459 xsprintf(log_level
, "%d", log_get_max_level());
1460 xsprintf(timeout
, "%" PRI_USEC
"us", arg_default_timeout_stop_usec
);
1462 switch (log_get_target()) {
1464 case LOG_TARGET_KMSG
:
1465 case LOG_TARGET_JOURNAL_OR_KMSG
:
1466 case LOG_TARGET_SYSLOG_OR_KMSG
:
1467 command_line
[pos
++] = "kmsg";
1470 case LOG_TARGET_NULL
:
1471 command_line
[pos
++] = "null";
1474 case LOG_TARGET_CONSOLE
:
1476 command_line
[pos
++] = "console";
1480 if (log_get_show_color())
1481 command_line
[pos
++] = "--log-color";
1483 if (log_get_show_location())
1484 command_line
[pos
++] = "--log-location";
1486 if (log_get_show_time())
1487 command_line
[pos
++] = "--log-time";
1489 if (streq(shutdown_verb
, "exit")) {
1490 command_line
[pos
++] = "--exit-code";
1491 command_line
[pos
++] = exit_code
;
1492 xsprintf(exit_code
, "%d", retval
);
1495 assert(pos
< ELEMENTSOF(command_line
));
1497 if (streq(shutdown_verb
, "reboot"))
1498 watchdog_timer
= arg_reboot_watchdog
;
1499 else if (streq(shutdown_verb
, "kexec"))
1500 watchdog_timer
= arg_kexec_watchdog
;
1502 /* If we reboot or kexec let's set the shutdown watchdog and tell the
1503 * shutdown binary to repeatedly ping it.
1504 * Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
1505 (void) watchdog_setup_pretimeout(0);
1506 (void) watchdog_setup_pretimeout_governor(NULL
);
1507 r
= watchdog_setup(watchdog_timer
);
1508 watchdog_close(r
< 0);
1510 /* Tell the binary how often to ping, ignore failure */
1511 (void) strv_extendf(&env_block
, "WATCHDOG_USEC="USEC_FMT
, watchdog_timer
);
1513 if (arg_watchdog_device
)
1514 (void) strv_extendf(&env_block
, "WATCHDOG_DEVICE=%s", arg_watchdog_device
);
1516 /* Avoid the creation of new processes forked by the kernel; at this
1517 * point, we will not listen to the signals anyway */
1518 if (detect_container() <= 0)
1519 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1521 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1525 static void initialize_clock(void) {
1528 /* This is called very early on, before we parse the kernel command line or otherwise figure out why
1529 * we are running, but only once. */
1531 if (clock_is_localtime(NULL
) > 0) {
1534 /* The very first call of settimeofday() also does a time warp in the kernel.
1536 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
1537 * take care of maintaining the RTC and do all adjustments. This matches the behavior of
1538 * Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
1540 r
= clock_set_timezone(&min
);
1542 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1544 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1546 } else if (!in_initrd())
1548 * Do a dummy very first call to seal the kernel's time warp magic.
1550 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
1551 * LOCAL, but the real system could be set up that way. In such case, we need to delay the
1552 * time-warp or the sealing until we reach the real system.
1554 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
1555 * the time will jump or be incorrect at every daylight saving time change. All kernel local
1556 * time concepts will be treated as UTC that way.
1558 (void) clock_reset_timewarp();
1560 ClockChangeDirection change_dir
;
1561 r
= clock_apply_epoch(&change_dir
);
1562 if (r
> 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1563 log_info("System time before build time, advancing clock.");
1564 else if (r
> 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1565 log_info("System time is further ahead than %s after build time, resetting clock to build time.",
1566 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1567 else if (r
< 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1568 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1569 else if (r
< 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1570 log_error_errno(r
, "Current system time is further ahead %s after build time, but cannot correct: %m",
1571 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1574 static void apply_clock_update(void) {
1575 /* This is called later than initialize_clock(), i.e. after we parsed configuration files/kernel
1576 * command line and such. */
1578 if (arg_clock_usec
== 0)
1581 if (getpid_cached() != 1)
1584 if (clock_settime(CLOCK_REALTIME
, TIMESPEC_STORE(arg_clock_usec
)) < 0)
1585 log_error_errno(errno
, "Failed to set system clock to time specified on kernel command line: %m");
1587 log_info("Set system clock to %s, as specified on the kernel command line.",
1588 FORMAT_TIMESTAMP(arg_clock_usec
));
1591 static void cmdline_take_random_seed(void) {
1595 if (arg_random_seed_size
== 0)
1598 if (getpid_cached() != 1)
1601 assert(arg_random_seed
);
1602 suggested
= random_pool_size();
1604 if (arg_random_seed_size
< suggested
)
1605 log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
1606 arg_random_seed_size
, suggested
);
1608 r
= random_write_entropy(-1, arg_random_seed
, arg_random_seed_size
, true);
1610 log_warning_errno(r
, "Failed to credit entropy specified on kernel command line, ignoring: %m");
1614 log_notice("Successfully credited entropy passed on kernel command line.\n"
1615 "Note that the seed provided this way is accessible to unprivileged programs. "
1616 "This functionality should not be used outside of testing environments.");
1619 static void initialize_coredump(bool skip_setup
) {
1621 if (getpid_cached() != 1)
1624 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
1625 * the limit) will process core dumps for system services by default. */
1626 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1627 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1629 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1630 * until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
1631 * command line later so core dumps can still be generated during early startup and in initramfs. */
1633 disable_coredumps();
1637 static void initialize_core_pattern(bool skip_setup
) {
1640 if (skip_setup
|| !arg_early_core_pattern
)
1643 if (getpid_cached() != 1)
1646 r
= write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1648 log_warning_errno(r
, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1649 arg_early_core_pattern
);
1652 static void update_cpu_affinity(bool skip_setup
) {
1653 _cleanup_free_
char *mask
= NULL
;
1655 if (skip_setup
|| !arg_cpu_affinity
.set
)
1658 assert(arg_cpu_affinity
.allocated
> 0);
1660 mask
= cpu_set_to_range_string(&arg_cpu_affinity
);
1661 log_debug("Setting CPU affinity to {%s}.", strnull(mask
));
1663 if (sched_setaffinity(0, arg_cpu_affinity
.allocated
, arg_cpu_affinity
.set
) < 0)
1664 log_warning_errno(errno
, "Failed to set CPU affinity, ignoring: %m");
1667 static void update_numa_policy(bool skip_setup
) {
1669 _cleanup_free_
char *nodes
= NULL
;
1670 const char * policy
= NULL
;
1672 if (skip_setup
|| !mpol_is_valid(numa_policy_get_type(&arg_numa_policy
)))
1675 if (DEBUG_LOGGING
) {
1676 policy
= mpol_to_string(numa_policy_get_type(&arg_numa_policy
));
1677 nodes
= cpu_set_to_range_string(&arg_numa_policy
.nodes
);
1678 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy
), strnull(nodes
));
1681 r
= apply_numa_policy(&arg_numa_policy
);
1682 if (r
== -EOPNOTSUPP
)
1683 log_debug_errno(r
, "NUMA support not available, ignoring.");
1685 log_warning_errno(r
, "Failed to set NUMA memory policy, ignoring: %m");
1688 static void filter_args(
1697 /* Copy some filtered arguments into the dst array from src. */
1698 for (int i
= 1; i
< argc
; i
++) {
1699 if (STR_IN_SET(src
[i
],
1705 if (startswith(src
[i
], "--deserialize="))
1707 if (streq(src
[i
], "--deserialize")) {
1708 i
++; /* Skip the argument too */
1712 /* Skip target unit designators. We already acted upon this information and have queued
1713 * appropriate jobs. We don't want to redo all this after reexecution. */
1714 if (startswith(src
[i
], "--unit="))
1716 if (streq(src
[i
], "--unit")) {
1717 i
++; /* Skip the argument too */
1721 if (startswith(src
[i
],
1722 in_initrd() ? "rd.systemd.unit=" : "systemd.unit="))
1725 if (runlevel_to_target(src
[i
]))
1728 /* Seems we have a good old option. Let's pass it over to the new instance. */
1729 dst
[(*dst_index
)++] = src
[i
];
1733 static int do_reexecute(
1734 ManagerObjective objective
,
1737 const struct rlimit
*saved_rlimit_nofile
,
1738 const struct rlimit
*saved_rlimit_memlock
,
1740 const char *switch_root_dir
,
1741 const char *switch_root_init
,
1742 const char **ret_error_message
) {
1744 size_t i
, args_size
;
1748 assert(IN_SET(objective
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
));
1750 assert(saved_rlimit_nofile
);
1751 assert(saved_rlimit_memlock
);
1752 assert(ret_error_message
);
1754 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1755 * rebooted while we do that */
1756 watchdog_close(true);
1758 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1759 * the kernel default to its child processes */
1760 if (saved_rlimit_nofile
->rlim_cur
!= 0)
1761 (void) setrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
);
1762 if (saved_rlimit_memlock
->rlim_cur
!= RLIM_INFINITY
)
1763 (void) setrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
);
1765 if (switch_root_dir
) {
1766 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can
1767 * handle the SIGCHLD for them after deserializing. */
1768 broadcast_signal(SIGTERM
, false, true, arg_default_timeout_stop_usec
);
1770 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1771 r
= switch_root(switch_root_dir
, "/mnt", true, MS_MOVE
);
1773 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
1776 args_size
= argc
+ 6;
1777 args
= newa(const char*, args_size
);
1779 if (!switch_root_init
) {
1780 char sfd
[DECIMAL_STR_MAX(int)];
1782 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1783 * only if the user didn't specify an explicit init to spawn. */
1785 assert(arg_serialization
);
1788 xsprintf(sfd
, "%i", fileno(arg_serialization
));
1790 i
= 1; /* Leave args[0] empty for now. */
1791 filter_args(args
, &i
, argv
, argc
);
1793 if (switch_root_dir
)
1794 args
[i
++] = "--switched-root";
1795 args
[i
++] = arg_system
? "--system" : "--user";
1796 args
[i
++] = "--deserialize";
1800 assert(i
<= args_size
);
1803 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
1804 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
1805 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
1806 * and wait() for it in the parent, before proceeding into the exec().
1808 valgrind_summary_hack();
1810 args
[0] = SYSTEMD_BINARY_PATH
;
1811 (void) execv(args
[0], (char* const*) args
);
1813 if (objective
== MANAGER_REEXECUTE
) {
1814 *ret_error_message
= "Failed to execute our own binary";
1815 return log_error_errno(errno
, "Failed to execute our own binary %s: %m", args
[0]);
1818 log_debug_errno(errno
, "Failed to execute our own binary %s, trying fallback: %m", args
[0]);
1821 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
1822 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
1823 * but let's hope that doesn't matter.) */
1825 arg_serialization
= safe_fclose(arg_serialization
);
1826 fds
= fdset_free(fds
);
1828 /* Reopen the console */
1829 (void) make_console_stdio();
1831 i
= 1; /* Leave args[0] empty for now. */
1832 for (int j
= 1; j
<= argc
; j
++)
1833 args
[i
++] = argv
[j
];
1834 assert(i
<= args_size
);
1836 /* Re-enable any blocked signals, especially important if we switch from initial ramdisk to init=... */
1837 (void) reset_all_signal_handlers();
1838 (void) reset_signal_mask();
1839 (void) rlimit_nofile_safe();
1841 if (switch_root_init
) {
1842 args
[0] = switch_root_init
;
1843 (void) execve(args
[0], (char* const*) args
, saved_env
);
1844 log_warning_errno(errno
, "Failed to execute configured init %s, trying fallback: %m", args
[0]);
1847 args
[0] = "/sbin/init";
1848 (void) execv(args
[0], (char* const*) args
);
1851 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
1852 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
1853 "Failed to execute /sbin/init");
1855 *ret_error_message
= "Failed to execute fallback shell";
1857 log_warning("No /sbin/init, trying fallback");
1859 args
[0] = "/bin/sh";
1861 (void) execve(args
[0], (char* const*) args
, saved_env
);
1862 return log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
1864 return log_error_errno(r
, "Failed to execute /sbin/init, giving up: %m");
1867 static int invoke_main_loop(
1869 const struct rlimit
*saved_rlimit_nofile
,
1870 const struct rlimit
*saved_rlimit_memlock
,
1871 int *ret_retval
, /* Return parameters relevant for shutting down */
1872 const char **ret_shutdown_verb
, /* … */
1873 FDSet
**ret_fds
, /* Return parameters for reexecuting */
1874 char **ret_switch_root_dir
, /* … */
1875 char **ret_switch_root_init
, /* … */
1876 const char **ret_error_message
) {
1881 assert(saved_rlimit_nofile
);
1882 assert(saved_rlimit_memlock
);
1884 assert(ret_shutdown_verb
);
1886 assert(ret_switch_root_dir
);
1887 assert(ret_switch_root_init
);
1888 assert(ret_error_message
);
1891 int objective
= manager_loop(m
);
1892 if (objective
< 0) {
1893 *ret_error_message
= "Failed to run main loop";
1894 return log_emergency_errno(objective
, "Failed to run main loop: %m");
1897 switch (objective
) {
1899 case MANAGER_RELOAD
: {
1900 LogTarget saved_log_target
;
1901 int saved_log_level
;
1903 log_info("Reloading.");
1905 /* First, save any overridden log level/target, then parse the configuration file,
1906 * which might change the log level to new settings. */
1908 saved_log_level
= m
->log_level_overridden
? log_get_max_level() : -1;
1909 saved_log_target
= m
->log_target_overridden
? log_get_target() : _LOG_TARGET_INVALID
;
1911 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
1913 set_manager_defaults(m
);
1914 set_manager_settings(m
);
1916 update_cpu_affinity(false);
1917 update_numa_policy(false);
1919 if (saved_log_level
>= 0)
1920 manager_override_log_level(m
, saved_log_level
);
1921 if (saved_log_target
>= 0)
1922 manager_override_log_target(m
, saved_log_target
);
1924 if (manager_reload(m
) < 0)
1925 /* Reloading failed before the point of no return.
1926 * Let's continue running as if nothing happened. */
1927 m
->objective
= MANAGER_OK
;
1932 case MANAGER_REEXECUTE
:
1933 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, false);
1935 *ret_error_message
= "Failed to prepare for reexecution";
1939 log_notice("Reexecuting.");
1941 *ret_retval
= EXIT_SUCCESS
;
1942 *ret_shutdown_verb
= NULL
;
1943 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1947 case MANAGER_SWITCH_ROOT
:
1948 if (!m
->switch_root_init
) {
1949 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, true);
1951 *ret_error_message
= "Failed to prepare for reexecution";
1957 log_notice("Switching root.");
1959 *ret_retval
= EXIT_SUCCESS
;
1960 *ret_shutdown_verb
= NULL
;
1962 /* Steal the switch root parameters */
1963 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
1964 *ret_switch_root_init
= TAKE_PTR(m
->switch_root_init
);
1969 if (MANAGER_IS_USER(m
)) {
1972 *ret_retval
= m
->return_value
;
1973 *ret_shutdown_verb
= NULL
;
1975 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1981 case MANAGER_REBOOT
:
1982 case MANAGER_POWEROFF
:
1984 case MANAGER_KEXEC
: {
1985 static const char* const table
[_MANAGER_OBJECTIVE_MAX
] = {
1986 [MANAGER_EXIT
] = "exit",
1987 [MANAGER_REBOOT
] = "reboot",
1988 [MANAGER_POWEROFF
] = "poweroff",
1989 [MANAGER_HALT
] = "halt",
1990 [MANAGER_KEXEC
] = "kexec",
1993 log_notice("Shutting down.");
1995 *ret_retval
= m
->return_value
;
1996 assert_se(*ret_shutdown_verb
= table
[m
->objective
]);
1998 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2004 assert_not_reached();
2009 static void log_execution_mode(bool *ret_first_boot
) {
2010 assert(ret_first_boot
);
2016 log_info("systemd " GIT_VERSION
" running in %ssystem mode (%s)",
2017 arg_action
== ACTION_TEST
? "test " : "",
2020 v
= detect_virtualization();
2022 log_info("Detected virtualization %s.", virtualization_to_string(v
));
2024 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2027 *ret_first_boot
= false;
2028 log_info("Running in initial RAM disk.");
2031 _cleanup_free_
char *id_text
= NULL
;
2033 /* Let's check whether we are in first boot. We use /etc/machine-id as flag file
2034 * for this: If it is missing or contains the value "uninitialized", this is the
2035 * first boot. In any other case, it is not. This allows container managers and
2036 * installers to provision a couple of files already. If the container manager
2037 * wants to provision the machine ID itself it should pass $container_uuid to PID 1. */
2039 r
= read_one_line_file("/etc/machine-id", &id_text
);
2040 if (r
< 0 || streq(id_text
, "uninitialized")) {
2041 if (r
< 0 && r
!= -ENOENT
)
2042 log_warning_errno(r
, "Unexpected error while reading /etc/machine-id, ignoring: %m");
2044 *ret_first_boot
= true;
2045 log_info("Detected first boot.");
2047 *ret_first_boot
= false;
2048 log_debug("Detected initialized system, this is not the first boot.");
2052 assert(uname(&uts
) >= 0);
2054 if (strverscmp_improved(uts
.release
, KERNEL_BASELINE_VERSION
) < 0)
2055 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2056 "Your mileage may vary.", uts
.release
, KERNEL_BASELINE_VERSION
);
2058 log_debug("Kernel version %s, our baseline is %s", uts
.release
, KERNEL_BASELINE_VERSION
);
2060 if (DEBUG_LOGGING
) {
2061 _cleanup_free_
char *t
= NULL
;
2063 t
= uid_to_name(getuid());
2064 log_debug("systemd " GIT_VERSION
" running in %suser mode for user " UID_FMT
"/%s. (%s)",
2065 arg_action
== ACTION_TEST
? " test" : "",
2066 getuid(), strna(t
), systemd_features
);
2069 *ret_first_boot
= false;
2073 static int initialize_runtime(
2076 struct rlimit
*saved_rlimit_nofile
,
2077 struct rlimit
*saved_rlimit_memlock
,
2078 const char **ret_error_message
) {
2081 assert(ret_error_message
);
2083 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2085 * - Some only apply to --system instances
2086 * - Some only apply to --user instances
2087 * - Some only apply when we first start up, but not when we reexecute
2090 if (arg_action
!= ACTION_RUN
)
2093 update_cpu_affinity(skip_setup
);
2094 update_numa_policy(skip_setup
);
2097 /* Make sure we leave a core dump without panicking the kernel. */
2098 install_crash_handler();
2101 r
= mount_cgroup_controllers();
2103 *ret_error_message
= "Failed to mount cgroup hierarchies";
2108 (void) hostname_setup(true);
2109 /* Force transient machine-id on first boot. */
2110 machine_id_setup(NULL
, first_boot
, arg_machine_id
, NULL
);
2111 (void) loopback_setup();
2112 bump_unix_max_dgram_qlen();
2113 bump_file_max_and_nr_open();
2115 write_container_id();
2118 if (arg_watchdog_device
) {
2119 r
= watchdog_set_device(arg_watchdog_device
);
2121 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device
);
2124 _cleanup_free_
char *p
= NULL
;
2126 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2127 * user mode. In system mode mount_setup() already did that. */
2129 r
= xdg_user_runtime_dir(&p
, "/systemd");
2131 *ret_error_message
= "$XDG_RUNTIME_DIR is not set";
2132 return log_emergency_errno(r
, "Failed to determine $XDG_RUNTIME_DIR path: %m");
2135 (void) mkdir_p_label(p
, 0755);
2136 (void) make_inaccessible_nodes(p
, UID_INVALID
, GID_INVALID
);
2139 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
2140 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
2141 log_warning_errno(errno
, "Failed to adjust timer slack, ignoring: %m");
2143 if (arg_system
&& !cap_test_all(arg_capability_bounding_set
)) {
2144 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
2146 *ret_error_message
= "Failed to drop capability bounding set of usermode helpers";
2147 return log_emergency_errno(r
, "Failed to drop capability bounding set of usermode helpers: %m");
2150 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
2152 *ret_error_message
= "Failed to drop capability bounding set";
2153 return log_emergency_errno(r
, "Failed to drop capability bounding set: %m");
2157 if (arg_system
&& arg_no_new_privs
) {
2158 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2159 *ret_error_message
= "Failed to disable new privileges";
2160 return log_emergency_errno(errno
, "Failed to disable new privileges: %m");
2164 if (arg_syscall_archs
) {
2165 r
= enforce_syscall_archs(arg_syscall_archs
);
2167 *ret_error_message
= "Failed to set syscall architectures";
2173 /* Become reaper of our children */
2174 if (prctl(PR_SET_CHILD_SUBREAPER
, 1) < 0)
2175 log_warning_errno(errno
, "Failed to make us a subreaper, ignoring: %m");
2177 /* Bump up RLIMIT_NOFILE for systemd itself */
2178 (void) bump_rlimit_nofile(saved_rlimit_nofile
);
2179 (void) bump_rlimit_memlock(saved_rlimit_memlock
);
2184 static int do_queue_default_job(
2186 const char **ret_error_message
) {
2188 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2194 if (arg_default_unit
)
2195 unit
= arg_default_unit
;
2196 else if (in_initrd())
2197 unit
= SPECIAL_INITRD_TARGET
;
2199 unit
= SPECIAL_DEFAULT_TARGET
;
2201 log_debug("Activating default unit: %s", unit
);
2203 r
= manager_load_startable_unit_or_warn(m
, unit
, NULL
, &target
);
2204 if (r
< 0 && in_initrd() && !arg_default_unit
) {
2205 /* Fall back to default.target, which we used to always use by default. Only do this if no
2206 * explicit configuration was given. */
2208 log_info("Falling back to " SPECIAL_DEFAULT_TARGET
".");
2210 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_DEFAULT_TARGET
, NULL
, &target
);
2213 log_info("Falling back to " SPECIAL_RESCUE_TARGET
".");
2215 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_RESCUE_TARGET
, NULL
, &target
);
2217 *ret_error_message
= r
== -ERFKILL
? SPECIAL_RESCUE_TARGET
" masked"
2218 : "Failed to load " SPECIAL_RESCUE_TARGET
;
2223 assert(target
->load_state
== UNIT_LOADED
);
2225 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, NULL
, &error
, &job
);
2227 log_debug_errno(r
, "Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
2229 sd_bus_error_free(&error
);
2231 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, NULL
, &error
, &job
);
2233 *ret_error_message
= "Failed to start default target";
2234 return log_emergency_errno(r
, "Failed to start default target: %s", bus_error_message(&error
, r
));
2238 *ret_error_message
= "Failed to isolate default target";
2239 return log_emergency_errno(r
, "Failed to isolate default target: %s", bus_error_message(&error
, r
));
2241 log_info("Queued %s job for default target %s.",
2242 job_type_to_string(job
->type
),
2243 unit_status_string(job
->unit
, NULL
));
2245 m
->default_unit_job_id
= job
->id
;
2250 static void save_rlimits(struct rlimit
*saved_rlimit_nofile
,
2251 struct rlimit
*saved_rlimit_memlock
) {
2253 assert(saved_rlimit_nofile
);
2254 assert(saved_rlimit_memlock
);
2256 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
) < 0)
2257 log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2259 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
) < 0)
2260 log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2263 static void fallback_rlimit_nofile(const struct rlimit
*saved_rlimit_nofile
) {
2266 if (arg_default_rlimit
[RLIMIT_NOFILE
])
2269 /* Make sure forked processes get limits based on the original kernel setting */
2271 rl
= newdup(struct rlimit
, saved_rlimit_nofile
, 1);
2277 /* Bump the hard limit for system services to a substantially higher value. The default
2278 * hard limit current kernels set is pretty low (4K), mostly for historical
2279 * reasons. According to kernel developers, the fd handling in recent kernels has been
2280 * optimized substantially enough, so that we can bump the limit now, without paying too
2281 * high a price in memory or performance. Note however that we only bump the hard limit,
2282 * not the soft limit. That's because select() works the way it works, and chokes on fds
2283 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2284 * unexpecting programs that they get fds higher than what they can process using
2285 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2286 * this pitfall: programs that are written by folks aware of the select() problem in mind
2287 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2288 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2293 /* Get the underlying absolute limit the kernel enforces */
2294 nr
= read_nr_open();
2296 rl
->rlim_max
= MIN((rlim_t
) nr
, MAX(rl
->rlim_max
, (rlim_t
) HIGH_RLIMIT_NOFILE
));
2299 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2300 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2301 * instance), then lower what we pass on to not confuse our children */
2302 rl
->rlim_cur
= MIN(rl
->rlim_cur
, (rlim_t
) FD_SETSIZE
);
2304 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
2307 static void fallback_rlimit_memlock(const struct rlimit
*saved_rlimit_memlock
) {
2310 /* Pass the original value down to invoked processes */
2312 if (arg_default_rlimit
[RLIMIT_MEMLOCK
])
2315 rl
= newdup(struct rlimit
, saved_rlimit_memlock
, 1);
2322 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2323 * default for this since kernel 5.16) */
2324 rl
->rlim_max
= MAX(rl
->rlim_max
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2325 rl
->rlim_cur
= MAX(rl
->rlim_cur
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2328 arg_default_rlimit
[RLIMIT_MEMLOCK
] = rl
;
2331 static void setenv_manager_environment(void) {
2334 STRV_FOREACH(p
, arg_manager_environment
) {
2335 log_debug("Setting '%s' in our own environment.", *p
);
2337 r
= putenv_dup(*p
, true);
2339 log_warning_errno(errno
, "Failed to setenv \"%s\", ignoring: %m", *p
);
2343 static void reset_arguments(void) {
2344 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2346 arg_default_unit
= mfree(arg_default_unit
);
2348 /* arg_system — ignore */
2350 arg_dump_core
= true;
2351 arg_crash_chvt
= -1;
2352 arg_crash_shell
= false;
2353 arg_crash_reboot
= false;
2354 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2355 arg_show_status
= _SHOW_STATUS_INVALID
;
2356 arg_status_unit_format
= STATUS_UNIT_FORMAT_DEFAULT
;
2357 arg_switched_root
= false;
2358 arg_pager_flags
= 0;
2359 arg_service_watchdogs
= true;
2360 arg_default_std_output
= EXEC_OUTPUT_JOURNAL
;
2361 arg_default_std_error
= EXEC_OUTPUT_INHERIT
;
2362 arg_default_restart_usec
= DEFAULT_RESTART_USEC
;
2363 arg_default_timeout_start_usec
= DEFAULT_TIMEOUT_USEC
;
2364 arg_default_timeout_stop_usec
= DEFAULT_TIMEOUT_USEC
;
2365 arg_default_timeout_abort_usec
= DEFAULT_TIMEOUT_USEC
;
2366 arg_default_timeout_abort_set
= false;
2367 arg_default_start_limit_interval
= DEFAULT_START_LIMIT_INTERVAL
;
2368 arg_default_start_limit_burst
= DEFAULT_START_LIMIT_BURST
;
2369 arg_runtime_watchdog
= 0;
2370 arg_reboot_watchdog
= 10 * USEC_PER_MINUTE
;
2371 arg_kexec_watchdog
= 0;
2372 arg_pretimeout_watchdog
= 0;
2373 arg_early_core_pattern
= NULL
;
2374 arg_watchdog_device
= NULL
;
2375 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
2377 arg_default_environment
= strv_free(arg_default_environment
);
2378 arg_manager_environment
= strv_free(arg_manager_environment
);
2379 rlimit_free_all(arg_default_rlimit
);
2381 arg_capability_bounding_set
= CAP_ALL
;
2382 arg_no_new_privs
= false;
2383 arg_timer_slack_nsec
= NSEC_INFINITY
;
2384 arg_default_timer_accuracy_usec
= 1 * USEC_PER_MINUTE
;
2386 arg_syscall_archs
= set_free(arg_syscall_archs
);
2388 /* arg_serialization — ignore */
2390 arg_default_cpu_accounting
= -1;
2391 arg_default_io_accounting
= false;
2392 arg_default_ip_accounting
= false;
2393 arg_default_blockio_accounting
= false;
2394 arg_default_memory_accounting
= MEMORY_ACCOUNTING_DEFAULT
;
2395 arg_default_tasks_accounting
= true;
2396 arg_default_tasks_max
= DEFAULT_TASKS_MAX
;
2397 arg_machine_id
= (sd_id128_t
) {};
2398 arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
2399 arg_default_oom_policy
= OOM_STOP
;
2401 cpu_set_reset(&arg_cpu_affinity
);
2402 numa_policy_reset(&arg_numa_policy
);
2404 arg_random_seed
= mfree(arg_random_seed
);
2405 arg_random_seed_size
= 0;
2408 arg_default_oom_score_adjust_set
= false;
2411 static void determine_default_oom_score_adjust(void) {
2414 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2415 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2418 if (arg_default_oom_score_adjust_set
)
2424 r
= get_oom_score_adjust(&a
);
2426 return (void) log_warning_errno(r
, "Failed to determine current OOM score adjustment value, ignoring: %m");
2428 assert_cc(100 <= OOM_SCORE_ADJ_MAX
);
2429 b
= a
>= OOM_SCORE_ADJ_MAX
- 100 ? OOM_SCORE_ADJ_MAX
: a
+ 100;
2434 arg_default_oom_score_adjust
= b
;
2435 arg_default_oom_score_adjust_set
= true;
2438 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
2439 const struct rlimit
*saved_rlimit_memlock
) {
2442 assert(saved_rlimit_nofile
);
2443 assert(saved_rlimit_memlock
);
2445 /* Assign configuration defaults */
2448 r
= parse_config_file();
2450 log_warning_errno(r
, "Failed to parse config file, ignoring: %m");
2453 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
2455 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2458 /* Initialize some default rlimits for services if they haven't been configured */
2459 fallback_rlimit_nofile(saved_rlimit_nofile
);
2460 fallback_rlimit_memlock(saved_rlimit_memlock
);
2462 /* Note that this also parses bits from the kernel command line, including "debug". */
2463 log_parse_environment();
2465 /* Initialize the show status setting if it hasn't been set explicitly yet */
2466 if (arg_show_status
== _SHOW_STATUS_INVALID
)
2467 arg_show_status
= SHOW_STATUS_YES
;
2469 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2470 determine_default_oom_score_adjust();
2472 /* Push variables into the manager environment block */
2473 setenv_manager_environment();
2475 /* Parse log environment variables again to take into account any new environment variables. */
2476 log_parse_environment();
2481 static int safety_checks(void) {
2483 if (getpid_cached() == 1 &&
2484 arg_action
!= ACTION_RUN
)
2485 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2486 "Unsupported execution mode while PID 1.");
2488 if (getpid_cached() == 1 &&
2490 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2491 "Can't run --user mode as PID 1.");
2493 if (arg_action
== ACTION_RUN
&&
2495 getpid_cached() != 1)
2496 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2497 "Can't run system mode unless PID 1.");
2499 if (arg_action
== ACTION_TEST
&&
2501 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2502 "Don't run test mode as root.");
2505 arg_action
== ACTION_RUN
&&
2507 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2508 "Trying to run as user instance, but the system has not been booted with systemd.");
2511 arg_action
== ACTION_RUN
&&
2512 !getenv("XDG_RUNTIME_DIR"))
2513 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH
),
2514 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2517 arg_action
== ACTION_RUN
&&
2518 running_in_chroot() > 0)
2519 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2520 "Cannot be run in a chroot() environment.");
2525 static int initialize_security(
2526 bool *loaded_policy
,
2527 dual_timestamp
*security_start_timestamp
,
2528 dual_timestamp
*security_finish_timestamp
,
2529 const char **ret_error_message
) {
2533 assert(loaded_policy
);
2534 assert(security_start_timestamp
);
2535 assert(security_finish_timestamp
);
2536 assert(ret_error_message
);
2538 dual_timestamp_get(security_start_timestamp
);
2540 r
= mac_selinux_setup(loaded_policy
);
2542 *ret_error_message
= "Failed to load SELinux policy";
2546 r
= mac_smack_setup(loaded_policy
);
2548 *ret_error_message
= "Failed to load SMACK policy";
2552 r
= mac_apparmor_setup();
2554 *ret_error_message
= "Failed to load AppArmor policy";
2560 *ret_error_message
= "Failed to load IMA policy";
2564 dual_timestamp_get(security_finish_timestamp
);
2568 static int collect_fds(FDSet
**ret_fds
, const char **ret_error_message
) {
2572 assert(ret_error_message
);
2574 r
= fdset_new_fill(ret_fds
);
2576 *ret_error_message
= "Failed to allocate fd set";
2577 return log_emergency_errno(r
, "Failed to allocate fd set: %m");
2580 fdset_cloexec(*ret_fds
, true);
2582 if (arg_serialization
)
2583 assert_se(fdset_remove(*ret_fds
, fileno(arg_serialization
)) >= 0);
2588 static void setup_console_terminal(bool skip_setup
) {
2593 /* Become a session leader if we aren't one yet. */
2596 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2597 * controlling tty. */
2598 (void) release_terminal();
2600 /* Reset the console, but only if this is really init and we are freshly booted */
2601 if (getpid_cached() == 1 && !skip_setup
)
2602 (void) console_setup();
2605 static bool early_skip_setup_check(int argc
, char *argv
[]) {
2606 bool found_deserialize
= false;
2608 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2609 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2610 * special setup things anyway, even if in that case we also do deserialization. */
2612 for (int i
= 1; i
< argc
; i
++)
2613 if (streq(argv
[i
], "--switched-root"))
2614 return false; /* If we switched root, don't skip the setup. */
2615 else if (streq(argv
[i
], "--deserialize"))
2616 found_deserialize
= true;
2618 return found_deserialize
; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2621 static int save_env(void) {
2624 l
= strv_copy(environ
);
2628 strv_free_and_replace(saved_env
, l
);
2632 int main(int argc
, char *argv
[]) {
2634 initrd_timestamp
= DUAL_TIMESTAMP_NULL
,
2635 userspace_timestamp
= DUAL_TIMESTAMP_NULL
,
2636 kernel_timestamp
= DUAL_TIMESTAMP_NULL
,
2637 security_start_timestamp
= DUAL_TIMESTAMP_NULL
,
2638 security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
2639 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0),
2640 saved_rlimit_memlock
= RLIMIT_MAKE_CONST(RLIM_INFINITY
); /* The original rlimits we passed
2641 * in. Note we use different values
2642 * for the two that indicate whether
2643 * these fields are initialized! */
2644 bool skip_setup
, loaded_policy
= false, queue_default_job
= false, first_boot
= false;
2645 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
2646 usec_t before_startup
, after_startup
;
2647 static char systemd
[] = "systemd";
2648 const char *shutdown_verb
= NULL
, *error_message
= NULL
;
2649 int r
, retval
= EXIT_FAILURE
;
2653 assert_se(argc
> 0 && !isempty(argv
[0]));
2655 /* SysV compatibility: redirect init → telinit */
2656 redirect_telinit(argc
, argv
);
2658 /* Take timestamps early on */
2659 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
2660 dual_timestamp_get(&userspace_timestamp
);
2662 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2664 skip_setup
= early_skip_setup_check(argc
, argv
);
2666 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2667 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2669 program_invocation_short_name
= systemd
;
2670 (void) prctl(PR_SET_NAME
, systemd
);
2672 /* Save the original command line */
2673 save_argc_argv(argc
, argv
);
2675 /* Save the original environment as we might need to restore it if we're requested to execute another
2676 * system manager later. */
2679 error_message
= "Failed to copy environment block";
2683 /* Make sure that if the user says "syslog" we actually log to the journal. */
2684 log_set_upgrade_syslog_to_journal(true);
2686 if (getpid_cached() == 1) {
2687 /* When we run as PID 1 force system mode */
2690 /* Disable the umask logic */
2693 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2694 * not be activated yet (even though the log socket for it exists). */
2695 log_set_prohibit_ipc(true);
2697 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
2698 * is important so that we never end up logging to any foreign stderr, for example if we have
2699 * to log in a child process right before execve()'ing the actual binary, at a point in time
2700 * where socket activation stderr/stdout area already set up. */
2701 log_set_always_reopen_console(true);
2703 if (detect_container() <= 0) {
2705 /* Running outside of a container as PID 1 */
2706 log_set_target(LOG_TARGET_KMSG
);
2710 initrd_timestamp
= userspace_timestamp
;
2713 r
= mount_setup_early();
2715 error_message
= "Failed to mount early API filesystems";
2719 /* Let's open the log backend a second time, in case the first time didn't
2720 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2721 * available, and it previously wasn't. */
2724 disable_printk_ratelimit();
2726 r
= initialize_security(
2728 &security_start_timestamp
,
2729 &security_finish_timestamp
,
2735 if (mac_selinux_init() < 0) {
2736 error_message
= "Failed to initialize SELinux support";
2743 /* Set the default for later on, but don't actually open the logs like this for
2744 * now. Note that if we are transitioning from the initrd there might still be
2745 * journal fd open, and we shouldn't attempt opening that before we parsed
2746 * /proc/cmdline which might redirect output elsewhere. */
2747 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
2750 /* Running inside a container, as PID 1 */
2751 log_set_target(LOG_TARGET_CONSOLE
);
2754 /* For later on, see above... */
2755 log_set_target(LOG_TARGET_JOURNAL
);
2757 /* clear the kernel timestamp, because we are in a container */
2758 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2761 initialize_coredump(skip_setup
);
2763 r
= fixup_environment();
2765 log_emergency_errno(r
, "Failed to fix up PID 1 environment: %m");
2766 error_message
= "Failed to fix up PID1 environment";
2770 /* Try to figure out if we can use colors with the console. No need to do that for user
2771 * instances since they never log into the console. */
2772 log_show_color(colors_enabled());
2774 r
= make_null_stdio();
2776 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2778 /* Load the kernel modules early. */
2782 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
2783 r
= mount_setup(loaded_policy
, skip_setup
);
2785 error_message
= "Failed to mount API filesystems";
2789 /* The efivarfs is now mounted, let's read the random seed off it */
2790 (void) efi_take_random_seed();
2792 /* Cache command-line options passed from EFI variables */
2794 (void) cache_efi_options_variable();
2796 /* Running as user instance */
2798 log_set_target(LOG_TARGET_AUTO
);
2801 /* clear the kernel timestamp, because we are not PID 1 */
2802 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2804 if (mac_selinux_init() < 0) {
2805 error_message
= "Failed to initialize SELinux support";
2810 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2811 * transitioning from the initrd to the main systemd or suchlike. */
2812 save_rlimits(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2814 /* Reset all signal handlers. */
2815 (void) reset_all_signal_handlers();
2816 (void) ignore_signals(SIGNALS_IGNORE
);
2818 (void) parse_configuration(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2820 r
= parse_argv(argc
, argv
);
2822 error_message
= "Failed to parse commandline arguments";
2826 r
= safety_checks();
2830 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
, ACTION_DUMP_CONFIGURATION_ITEMS
, ACTION_DUMP_BUS_PROPERTIES
, ACTION_BUS_INTROSPECT
))
2831 pager_open(arg_pager_flags
);
2833 if (arg_action
!= ACTION_RUN
)
2836 if (arg_action
== ACTION_HELP
) {
2837 retval
= help() < 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2839 } else if (arg_action
== ACTION_VERSION
) {
2842 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
2843 unit_dump_config_items(stdout
);
2844 retval
= EXIT_SUCCESS
;
2846 } else if (arg_action
== ACTION_DUMP_BUS_PROPERTIES
) {
2847 dump_bus_properties(stdout
);
2848 retval
= EXIT_SUCCESS
;
2850 } else if (arg_action
== ACTION_BUS_INTROSPECT
) {
2851 r
= bus_manager_introspect_implementations(stdout
, arg_bus_introspect
);
2852 retval
= r
>= 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
2856 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
2858 /* Move out of the way, so that we won't block unmounts */
2859 assert_se(chdir("/") == 0);
2861 if (arg_action
== ACTION_RUN
) {
2863 /* Apply the systemd.clock_usec= kernel command line switch */
2864 apply_clock_update();
2866 /* Apply random seed from kernel command line */
2867 cmdline_take_random_seed();
2870 /* A core pattern might have been specified via the cmdline. */
2871 initialize_core_pattern(skip_setup
);
2873 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
2876 /* Remember open file descriptors for later deserialization */
2877 r
= collect_fds(&fds
, &error_message
);
2881 /* Give up any control of the console, but make sure its initialized. */
2882 setup_console_terminal(skip_setup
);
2884 /* Open the logging devices, if possible and necessary */
2888 log_execution_mode(&first_boot
);
2890 r
= initialize_runtime(skip_setup
,
2892 &saved_rlimit_nofile
,
2893 &saved_rlimit_memlock
,
2898 r
= manager_new(arg_system
? LOOKUP_SCOPE_SYSTEM
: LOOKUP_SCOPE_USER
,
2899 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
2902 log_emergency_errno(r
, "Failed to allocate manager object: %m");
2903 error_message
= "Failed to allocate manager object";
2907 m
->timestamps
[MANAGER_TIMESTAMP_KERNEL
] = kernel_timestamp
;
2908 m
->timestamps
[MANAGER_TIMESTAMP_INITRD
] = initrd_timestamp
;
2909 m
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
] = userspace_timestamp
;
2910 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START
)] = security_start_timestamp
;
2911 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH
)] = security_finish_timestamp
;
2913 set_manager_defaults(m
);
2914 set_manager_settings(m
);
2915 manager_set_first_boot(m
, first_boot
);
2917 /* Remember whether we should queue the default job */
2918 queue_default_job
= !arg_serialization
|| arg_switched_root
;
2920 before_startup
= now(CLOCK_MONOTONIC
);
2922 r
= manager_startup(m
, arg_serialization
, fds
, /* root= */ NULL
);
2924 error_message
= "Failed to start up manager";
2928 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2929 fds
= fdset_free(fds
);
2930 arg_serialization
= safe_fclose(arg_serialization
);
2932 if (queue_default_job
) {
2933 r
= do_queue_default_job(m
, &error_message
);
2938 after_startup
= now(CLOCK_MONOTONIC
);
2940 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
2941 "Loaded units and determined initial transaction in %s.",
2942 FORMAT_TIMESPAN(after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
2944 if (arg_action
== ACTION_TEST
) {
2945 manager_test_summary(m
);
2946 retval
= EXIT_SUCCESS
;
2950 r
= invoke_main_loop(m
,
2951 &saved_rlimit_nofile
,
2952 &saved_rlimit_memlock
,
2959 assert(r
< 0 || IN_SET(r
, MANAGER_EXIT
, /* MANAGER_OK is not expected here. */
2966 MANAGER_SWITCH_ROOT
));
2972 arg_reboot_watchdog
= manager_get_watchdog(m
, WATCHDOG_REBOOT
);
2973 arg_kexec_watchdog
= manager_get_watchdog(m
, WATCHDOG_KEXEC
);
2974 m
= manager_free(m
);
2977 mac_selinux_finish();
2979 if (IN_SET(r
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
))
2982 &saved_rlimit_nofile
,
2983 &saved_rlimit_memlock
,
2987 &error_message
); /* This only returns if reexecution failed */
2989 arg_serialization
= safe_fclose(arg_serialization
);
2990 fds
= fdset_free(fds
);
2992 saved_env
= strv_free(saved_env
);
2994 #if HAVE_VALGRIND_VALGRIND_H
2995 /* If we are PID 1 and running under valgrind, then let's exit
2996 * here explicitly. valgrind will only generate nice output on
2997 * exit(), not on exec(), hence let's do the former not the
2999 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
3000 /* Cleanup watchdog_device strings for valgrind. We need them
3001 * in become_shutdown() so normally we cannot free them yet. */
3002 watchdog_free_device();
3003 arg_watchdog_device
= mfree(arg_watchdog_device
);
3009 #if HAS_FEATURE_ADDRESS_SANITIZER
3010 __lsan_do_leak_check();
3013 /* Try to invoke the shutdown binary unless we already failed.
3014 * If we failed above, we want to freeze after finishing cleanup. */
3015 if (r
>= 0 && shutdown_verb
) {
3016 r
= become_shutdown(shutdown_verb
, retval
);
3017 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3018 error_message
= "Failed to execute shutdown binary";
3021 watchdog_free_device();
3022 arg_watchdog_device
= mfree(arg_watchdog_device
);
3024 if (getpid_cached() == 1) {
3026 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
3027 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
3028 "%s.", error_message
);
3029 freeze_or_exit_or_reboot();