1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include <sys/utsname.h>
14 #if HAVE_VALGRIND_VALGRIND_H
15 # include <valgrind/valgrind.h>
19 #include "sd-daemon.h"
20 #include "sd-messages.h"
22 #include "alloc-util.h"
23 #include "apparmor-setup.h"
24 #include "architecture.h"
25 #include "argv-util.h"
30 #include "bus-error.h"
32 #include "capability-util.h"
33 #include "cgroup-util.h"
34 #include "clock-util.h"
35 #include "conf-parser.h"
36 #include "cpu-set-util.h"
37 #include "crash-handler.h"
38 #include "dbus-manager.h"
40 #include "constants.h"
41 #include "dev-setup.h"
42 #include "efi-random.h"
44 #include "emergency-action.h"
46 #include "exit-status.h"
50 #include "format-util.h"
52 #include "hexdecoct.h"
53 #include "hostname-setup.h"
54 #include "ima-setup.h"
55 #include "import-creds.h"
56 #include "initrd-util.h"
58 #include "kmod-setup.h"
59 #include "limits-util.h"
60 #include "load-fragment.h"
62 #include "loopback-setup.h"
63 #include "machine-id-setup.h"
66 #include "manager-dump.h"
67 #include "manager-serialize.h"
68 #include "mkdir-label.h"
69 #include "mount-setup.h"
72 #include "parse-argument.h"
73 #include "parse-util.h"
74 #include "path-util.h"
75 #include "pretty-print.h"
76 #include "proc-cmdline.h"
77 #include "process-util.h"
79 #include "random-util.h"
80 #include "rlimit-util.h"
82 #include "seccomp-util.h"
84 #include "selinux-setup.h"
85 #include "selinux-util.h"
86 #include "signal-util.h"
87 #include "smack-setup.h"
89 #include "stat-util.h"
90 #include "stdio-util.h"
92 #include "switch-root.h"
93 #include "sysctl-util.h"
94 #include "terminal-util.h"
95 #include "time-util.h"
96 #include "umask-util.h"
97 #include "user-util.h"
101 #if HAS_FEATURE_ADDRESS_SANITIZER
102 #include <sanitizer/lsan_interface.h>
105 #define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
112 ACTION_DUMP_CONFIGURATION_ITEMS
,
113 ACTION_DUMP_BUS_PROPERTIES
,
114 ACTION_BUS_INTROSPECT
,
115 } arg_action
= ACTION_RUN
;
117 static const char *arg_bus_introspect
= NULL
;
119 /* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
120 * defaults are assigned in reset_arguments() below. */
121 static char *arg_default_unit
;
122 static RuntimeScope arg_runtime_scope
;
125 bool arg_crash_shell
;
126 bool arg_crash_reboot
;
127 static char *arg_confirm_spawn
;
128 static ShowStatus arg_show_status
;
129 static StatusUnitFormat arg_status_unit_format
;
130 static bool arg_switched_root
;
131 static PagerFlags arg_pager_flags
;
132 static bool arg_service_watchdogs
;
133 static ExecOutput arg_default_std_output
;
134 static ExecOutput arg_default_std_error
;
135 static usec_t arg_default_restart_usec
;
136 static usec_t arg_default_timeout_start_usec
;
137 static usec_t arg_default_timeout_stop_usec
;
138 static usec_t arg_default_timeout_abort_usec
;
139 static usec_t arg_default_device_timeout_usec
;
140 static bool arg_default_timeout_abort_set
;
141 static usec_t arg_default_start_limit_interval
;
142 static unsigned arg_default_start_limit_burst
;
143 static usec_t arg_runtime_watchdog
;
144 static usec_t arg_reboot_watchdog
;
145 static usec_t arg_kexec_watchdog
;
146 static usec_t arg_pretimeout_watchdog
;
147 static char *arg_early_core_pattern
;
148 static char *arg_watchdog_pretimeout_governor
;
149 static char *arg_watchdog_device
;
150 static char **arg_default_environment
;
151 static char **arg_manager_environment
;
152 static struct rlimit
*arg_default_rlimit
[_RLIMIT_MAX
];
153 static uint64_t arg_capability_bounding_set
;
154 static bool arg_no_new_privs
;
155 static nsec_t arg_timer_slack_nsec
;
156 static usec_t arg_default_timer_accuracy_usec
;
157 static Set
* arg_syscall_archs
;
158 static FILE* arg_serialization
;
159 static int arg_default_cpu_accounting
;
160 static bool arg_default_io_accounting
;
161 static bool arg_default_ip_accounting
;
162 static bool arg_default_blockio_accounting
;
163 static bool arg_default_memory_accounting
;
164 static bool arg_default_tasks_accounting
;
165 static TasksMax arg_default_tasks_max
;
166 static usec_t arg_default_memory_pressure_threshold_usec
;
167 static CGroupPressureWatch arg_default_memory_pressure_watch
;
168 static sd_id128_t arg_machine_id
;
169 static EmergencyAction arg_cad_burst_action
;
170 static OOMPolicy arg_default_oom_policy
;
171 static CPUSet arg_cpu_affinity
;
172 static NUMAPolicy arg_numa_policy
;
173 static usec_t arg_clock_usec
;
174 static void *arg_random_seed
;
175 static size_t arg_random_seed_size
;
176 static int arg_default_oom_score_adjust
;
177 static bool arg_default_oom_score_adjust_set
;
178 static char *arg_default_smack_process_label
;
179 static usec_t arg_reload_limit_interval_sec
;
180 static unsigned arg_reload_limit_burst
;
182 /* A copy of the original environment block */
183 static char **saved_env
= NULL
;
185 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
186 const struct rlimit
*saved_rlimit_memlock
);
188 static int manager_find_user_config_paths(char ***ret_files
, char ***ret_dirs
) {
189 _cleanup_free_
char *base
= NULL
;
190 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
193 r
= xdg_user_config_dir(&base
, "/systemd");
197 r
= strv_extendf(&files
, "%s/user.conf", base
);
201 r
= strv_extend(&files
, PKGSYSCONFDIR
"/user.conf");
205 r
= strv_consume(&dirs
, TAKE_PTR(base
));
209 r
= strv_extend_strv(&dirs
, CONF_PATHS_STRV("systemd"), false);
213 *ret_files
= TAKE_PTR(files
);
214 *ret_dirs
= TAKE_PTR(dirs
);
218 static int console_setup(void) {
219 _cleanup_close_
int tty_fd
= -EBADF
;
222 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
224 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
226 /* We don't want to force text mode. plymouth may be showing
227 * pictures already from initrd. */
228 r
= reset_terminal_fd(tty_fd
, false);
230 return log_error_errno(r
, "Failed to reset /dev/console: %m");
235 static int set_machine_id(const char *m
) {
239 if (sd_id128_from_string(m
, &t
) < 0)
242 if (sd_id128_is_null(t
))
249 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
254 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
256 if (proc_cmdline_value_missing(key
, value
))
259 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
260 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
261 else if (in_initrd() == !!startswith(key
, "rd."))
262 return free_and_strdup_warn(&arg_default_unit
, value
);
264 } else if (proc_cmdline_key_streq(key
, "systemd.dump_core")) {
266 r
= value
? parse_boolean(value
) : true;
268 log_warning_errno(r
, "Failed to parse dump core switch %s, ignoring: %m", value
);
272 } else if (proc_cmdline_key_streq(key
, "systemd.early_core_pattern")) {
274 if (proc_cmdline_value_missing(key
, value
))
277 if (path_is_absolute(value
))
278 (void) parse_path_argument(value
, false, &arg_early_core_pattern
);
280 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value
);
282 } else if (proc_cmdline_key_streq(key
, "systemd.crash_chvt")) {
285 arg_crash_chvt
= 0; /* turn on */
287 r
= parse_crash_chvt(value
, &arg_crash_chvt
);
289 log_warning_errno(r
, "Failed to parse crash chvt switch %s, ignoring: %m", value
);
292 } else if (proc_cmdline_key_streq(key
, "systemd.crash_shell")) {
294 r
= value
? parse_boolean(value
) : true;
296 log_warning_errno(r
, "Failed to parse crash shell switch %s, ignoring: %m", value
);
300 } else if (proc_cmdline_key_streq(key
, "systemd.crash_reboot")) {
302 r
= value
? parse_boolean(value
) : true;
304 log_warning_errno(r
, "Failed to parse crash reboot switch %s, ignoring: %m", value
);
306 arg_crash_reboot
= r
;
308 } else if (proc_cmdline_key_streq(key
, "systemd.confirm_spawn")) {
311 r
= parse_confirm_spawn(value
, &s
);
313 log_warning_errno(r
, "Failed to parse confirm_spawn switch %s, ignoring: %m", value
);
315 free_and_replace(arg_confirm_spawn
, s
);
317 } else if (proc_cmdline_key_streq(key
, "systemd.service_watchdogs")) {
319 r
= value
? parse_boolean(value
) : true;
321 log_warning_errno(r
, "Failed to parse service watchdog switch %s, ignoring: %m", value
);
323 arg_service_watchdogs
= r
;
325 } else if (proc_cmdline_key_streq(key
, "systemd.show_status")) {
328 r
= parse_show_status(value
, &arg_show_status
);
330 log_warning_errno(r
, "Failed to parse show status switch %s, ignoring: %m", value
);
332 arg_show_status
= SHOW_STATUS_YES
;
334 } else if (proc_cmdline_key_streq(key
, "systemd.status_unit_format")) {
336 if (proc_cmdline_value_missing(key
, value
))
339 r
= status_unit_format_from_string(value
);
341 log_warning_errno(r
, "Failed to parse %s=%s, ignoring: %m", key
, value
);
343 arg_status_unit_format
= r
;
345 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_output")) {
347 if (proc_cmdline_value_missing(key
, value
))
350 r
= exec_output_from_string(value
);
352 log_warning_errno(r
, "Failed to parse default standard output switch %s, ignoring: %m", value
);
354 arg_default_std_output
= r
;
356 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_error")) {
358 if (proc_cmdline_value_missing(key
, value
))
361 r
= exec_output_from_string(value
);
363 log_warning_errno(r
, "Failed to parse default standard error switch %s, ignoring: %m", value
);
365 arg_default_std_error
= r
;
367 } else if (streq(key
, "systemd.setenv")) {
369 if (proc_cmdline_value_missing(key
, value
))
372 if (!env_assignment_is_valid(value
))
373 log_warning("Environment variable assignment '%s' is not valid. Ignoring.", value
);
375 r
= strv_env_replace_strdup(&arg_default_environment
, value
);
380 } else if (proc_cmdline_key_streq(key
, "systemd.machine_id")) {
382 if (proc_cmdline_value_missing(key
, value
))
385 r
= set_machine_id(value
);
387 log_warning_errno(r
, "MachineID '%s' is not valid, ignoring: %m", value
);
389 } else if (proc_cmdline_key_streq(key
, "systemd.default_timeout_start_sec")) {
391 if (proc_cmdline_value_missing(key
, value
))
394 r
= parse_sec(value
, &arg_default_timeout_start_usec
);
396 log_warning_errno(r
, "Failed to parse default start timeout '%s', ignoring: %m", value
);
398 if (arg_default_timeout_start_usec
<= 0)
399 arg_default_timeout_start_usec
= USEC_INFINITY
;
401 } else if (proc_cmdline_key_streq(key
, "systemd.cpu_affinity")) {
403 if (proc_cmdline_value_missing(key
, value
))
406 r
= parse_cpu_set(value
, &arg_cpu_affinity
);
408 log_warning_errno(r
, "Failed to parse CPU affinity mask '%s', ignoring: %m", value
);
410 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_device")) {
412 if (proc_cmdline_value_missing(key
, value
))
415 (void) parse_path_argument(value
, false, &arg_watchdog_device
);
417 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_sec")) {
419 if (proc_cmdline_value_missing(key
, value
))
422 if (streq(value
, "default"))
423 arg_runtime_watchdog
= USEC_INFINITY
;
424 else if (streq(value
, "off"))
425 arg_runtime_watchdog
= 0;
427 r
= parse_sec(value
, &arg_runtime_watchdog
);
429 log_warning_errno(r
, "Failed to parse systemd.watchdog_sec= argument '%s', ignoring: %m", value
);
434 arg_kexec_watchdog
= arg_reboot_watchdog
= arg_runtime_watchdog
;
436 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pre_sec")) {
438 if (proc_cmdline_value_missing(key
, value
))
441 if (streq(value
, "default"))
442 arg_pretimeout_watchdog
= USEC_INFINITY
;
443 else if (streq(value
, "off"))
444 arg_pretimeout_watchdog
= 0;
446 r
= parse_sec(value
, &arg_pretimeout_watchdog
);
448 log_warning_errno(r
, "Failed to parse systemd.watchdog_pre_sec= argument '%s', ignoring: %m", value
);
453 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pretimeout_governor")) {
455 if (proc_cmdline_value_missing(key
, value
) || isempty(value
)) {
456 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
460 if (!string_is_safe(value
)) {
461 log_warning("Watchdog pretimeout governor '%s' is not valid, ignoring.", value
);
465 return free_and_strdup_warn(&arg_watchdog_pretimeout_governor
, value
);
467 } else if (proc_cmdline_key_streq(key
, "systemd.clock_usec")) {
469 if (proc_cmdline_value_missing(key
, value
))
472 r
= safe_atou64(value
, &arg_clock_usec
);
474 log_warning_errno(r
, "Failed to parse systemd.clock_usec= argument, ignoring: %s", value
);
476 } else if (proc_cmdline_key_streq(key
, "systemd.random_seed")) {
480 if (proc_cmdline_value_missing(key
, value
))
483 r
= unbase64mem(value
, SIZE_MAX
, &p
, &sz
);
485 log_warning_errno(r
, "Failed to parse systemd.random_seed= argument, ignoring: %s", value
);
487 free(arg_random_seed
);
488 arg_random_seed
= sz
> 0 ? p
: mfree(p
);
489 arg_random_seed_size
= sz
;
491 } else if (proc_cmdline_key_streq(key
, "systemd.reload_limit_interval_sec")) {
493 if (proc_cmdline_value_missing(key
, value
))
496 r
= parse_sec(value
, &arg_reload_limit_interval_sec
);
498 log_warning_errno(r
, "Failed to parse systemd.reload_limit_interval_sec= argument '%s', ignoring: %m", value
);
502 } else if (proc_cmdline_key_streq(key
, "systemd.reload_limit_burst")) {
504 if (proc_cmdline_value_missing(key
, value
))
507 r
= safe_atou(value
, &arg_reload_limit_burst
);
509 log_warning_errno(r
, "Failed to parse systemd.reload_limit_burst= argument '%s', ignoring: %m", value
);
513 } else if (streq(key
, "quiet") && !value
) {
515 if (arg_show_status
== _SHOW_STATUS_INVALID
)
516 arg_show_status
= SHOW_STATUS_ERROR
;
518 } else if (streq(key
, "debug") && !value
) {
520 /* Note that log_parse_environment() handles 'debug'
521 * too, and sets the log level to LOG_DEBUG. */
523 if (detect_container() > 0)
524 log_set_target(LOG_TARGET_CONSOLE
);
529 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
530 target
= runlevel_to_target(key
);
532 return free_and_strdup_warn(&arg_default_unit
, target
);
538 #define DEFINE_SETTER(name, func, descr) \
539 static int name(const char *unit, \
540 const char *filename, \
542 const char *section, \
543 unsigned section_line, \
544 const char *lvalue, \
546 const char *rvalue, \
558 log_syntax(unit, LOG_ERR, filename, line, r, \
559 "Invalid " descr "'%s': %m", \
565 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level");
566 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target");
567 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color");
568 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location");
569 DEFINE_SETTER(config_parse_time
, log_show_time_from_string
, "time");
571 static int config_parse_default_timeout_abort(
573 const char *filename
,
576 unsigned section_line
,
584 r
= config_parse_timeout_abort(unit
, filename
, line
, section
, section_line
, lvalue
, ltype
, rvalue
,
585 &arg_default_timeout_abort_usec
, userdata
);
587 arg_default_timeout_abort_set
= r
;
591 static int config_parse_oom_score_adjust(
593 const char *filename
,
596 unsigned section_line
,
605 if (isempty(rvalue
)) {
606 arg_default_oom_score_adjust_set
= false;
610 r
= parse_oom_score_adjust(rvalue
, &oa
);
612 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse the OOM score adjust value '%s', ignoring: %m", rvalue
);
616 arg_default_oom_score_adjust
= oa
;
617 arg_default_oom_score_adjust_set
= true;
622 static int parse_config_file(void) {
623 const ConfigTableItem items
[] = {
624 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
625 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
626 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
627 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
628 { "Manager", "LogTime", config_parse_time
, 0, NULL
},
629 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
630 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, &arg_crash_chvt
},
631 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, &arg_crash_chvt
},
632 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
633 { "Manager", "CrashReboot", config_parse_bool
, 0, &arg_crash_reboot
},
634 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
635 { "Manager", "StatusUnitFormat", config_parse_status_unit_format
, 0, &arg_status_unit_format
},
636 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, &arg_cpu_affinity
},
637 { "Manager", "NUMAPolicy", config_parse_numa_policy
, 0, &arg_numa_policy
.type
},
638 { "Manager", "NUMAMask", config_parse_numa_mask
, 0, &arg_numa_policy
},
639 { "Manager", "JoinControllers", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
640 { "Manager", "RuntimeWatchdogSec", config_parse_watchdog_sec
, 0, &arg_runtime_watchdog
},
641 { "Manager", "RuntimeWatchdogPreSec", config_parse_watchdog_sec
, 0, &arg_pretimeout_watchdog
},
642 { "Manager", "RebootWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
},
643 { "Manager", "ShutdownWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
}, /* obsolete alias */
644 { "Manager", "KExecWatchdogSec", config_parse_watchdog_sec
, 0, &arg_kexec_watchdog
},
645 { "Manager", "WatchdogDevice", config_parse_path
, 0, &arg_watchdog_device
},
646 { "Manager", "RuntimeWatchdogPreGovernor", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &arg_watchdog_pretimeout_governor
},
647 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
648 { "Manager", "NoNewPrivileges", config_parse_bool
, 0, &arg_no_new_privs
},
650 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
652 { "Manager", "SystemCallArchitectures", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
655 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
656 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_default_timer_accuracy_usec
},
657 { "Manager", "DefaultStandardOutput", config_parse_output_restricted
, 0, &arg_default_std_output
},
658 { "Manager", "DefaultStandardError", config_parse_output_restricted
, 0, &arg_default_std_error
},
659 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_default_timeout_start_usec
},
660 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_default_timeout_stop_usec
},
661 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort
, 0, NULL
},
662 { "Manager", "DefaultDeviceTimeoutSec", config_parse_sec
, 0, &arg_default_device_timeout_usec
},
663 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_default_restart_usec
},
664 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_default_start_limit_interval
}, /* obsolete alias */
665 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec
, 0, &arg_default_start_limit_interval
},
666 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_default_start_limit_burst
},
667 { "Manager", "DefaultEnvironment", config_parse_environ
, arg_runtime_scope
, &arg_default_environment
},
668 { "Manager", "ManagerEnvironment", config_parse_environ
, arg_runtime_scope
, &arg_manager_environment
},
669 { "Manager", "DefaultLimitCPU", config_parse_rlimit
, RLIMIT_CPU
, arg_default_rlimit
},
670 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit
, RLIMIT_FSIZE
, arg_default_rlimit
},
671 { "Manager", "DefaultLimitDATA", config_parse_rlimit
, RLIMIT_DATA
, arg_default_rlimit
},
672 { "Manager", "DefaultLimitSTACK", config_parse_rlimit
, RLIMIT_STACK
, arg_default_rlimit
},
673 { "Manager", "DefaultLimitCORE", config_parse_rlimit
, RLIMIT_CORE
, arg_default_rlimit
},
674 { "Manager", "DefaultLimitRSS", config_parse_rlimit
, RLIMIT_RSS
, arg_default_rlimit
},
675 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit
, RLIMIT_NOFILE
, arg_default_rlimit
},
676 { "Manager", "DefaultLimitAS", config_parse_rlimit
, RLIMIT_AS
, arg_default_rlimit
},
677 { "Manager", "DefaultLimitNPROC", config_parse_rlimit
, RLIMIT_NPROC
, arg_default_rlimit
},
678 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit
, RLIMIT_MEMLOCK
, arg_default_rlimit
},
679 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit
, RLIMIT_LOCKS
, arg_default_rlimit
},
680 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit
, RLIMIT_SIGPENDING
, arg_default_rlimit
},
681 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit
, RLIMIT_MSGQUEUE
, arg_default_rlimit
},
682 { "Manager", "DefaultLimitNICE", config_parse_rlimit
, RLIMIT_NICE
, arg_default_rlimit
},
683 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit
, RLIMIT_RTPRIO
, arg_default_rlimit
},
684 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit
, RLIMIT_RTTIME
, arg_default_rlimit
},
685 { "Manager", "DefaultCPUAccounting", config_parse_tristate
, 0, &arg_default_cpu_accounting
},
686 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_default_io_accounting
},
687 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_default_ip_accounting
},
688 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_default_blockio_accounting
},
689 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_default_memory_accounting
},
690 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_default_tasks_accounting
},
691 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_default_tasks_max
},
692 { "Manager", "DefaultMemoryPressureThresholdSec", config_parse_sec
, 0, &arg_default_memory_pressure_threshold_usec
},
693 { "Manager", "DefaultMemoryPressureWatch", config_parse_memory_pressure_watch
, 0, &arg_default_memory_pressure_watch
},
694 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, arg_runtime_scope
, &arg_cad_burst_action
},
695 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy
, 0, &arg_default_oom_policy
},
696 { "Manager", "DefaultOOMScoreAdjust", config_parse_oom_score_adjust
, 0, NULL
},
697 { "Manager", "ReloadLimitIntervalSec", config_parse_sec
, 0, &arg_reload_limit_interval_sec
},
698 { "Manager", "ReloadLimitBurst", config_parse_unsigned
, 0, &arg_reload_limit_burst
},
700 { "Manager", "DefaultSmackProcessLabel", config_parse_string
, 0, &arg_default_smack_process_label
},
702 { "Manager", "DefaultSmackProcessLabel", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
707 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
711 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
)
712 suffix
= "system.conf.d";
714 assert(arg_runtime_scope
== RUNTIME_SCOPE_USER
);
716 r
= manager_find_user_config_paths(&files
, &dirs
);
718 return log_error_errno(r
, "Failed to determine config file paths: %m");
720 suffix
= "user.conf.d";
723 (void) config_parse_many(
724 (const char* const*) (files
?: STRV_MAKE(PKGSYSCONFDIR
"/system.conf")),
725 (const char* const*) (dirs
?: CONF_PATHS_STRV("systemd")),
728 config_item_table_lookup
, items
,
734 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we use
735 * USEC_INFINITY like everywhere else. */
736 if (arg_default_timeout_start_usec
<= 0)
737 arg_default_timeout_start_usec
= USEC_INFINITY
;
738 if (arg_default_timeout_stop_usec
<= 0)
739 arg_default_timeout_stop_usec
= USEC_INFINITY
;
744 static void set_manager_defaults(Manager
*m
) {
748 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
749 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
750 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
752 m
->default_timer_accuracy_usec
= arg_default_timer_accuracy_usec
;
753 m
->default_std_output
= arg_default_std_output
;
754 m
->default_std_error
= arg_default_std_error
;
755 m
->default_timeout_start_usec
= arg_default_timeout_start_usec
;
756 m
->default_timeout_stop_usec
= arg_default_timeout_stop_usec
;
757 m
->default_timeout_abort_usec
= arg_default_timeout_abort_usec
;
758 m
->default_timeout_abort_set
= arg_default_timeout_abort_set
;
759 m
->default_device_timeout_usec
= arg_default_device_timeout_usec
;
760 m
->default_restart_usec
= arg_default_restart_usec
;
761 m
->default_start_limit_interval
= arg_default_start_limit_interval
;
762 m
->default_start_limit_burst
= arg_default_start_limit_burst
;
764 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
765 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
766 if (arg_default_cpu_accounting
>= 0)
767 m
->default_cpu_accounting
= arg_default_cpu_accounting
;
769 m
->default_cpu_accounting
= cpu_accounting_is_cheap();
771 m
->default_io_accounting
= arg_default_io_accounting
;
772 m
->default_ip_accounting
= arg_default_ip_accounting
;
773 m
->default_blockio_accounting
= arg_default_blockio_accounting
;
774 m
->default_memory_accounting
= arg_default_memory_accounting
;
775 m
->default_tasks_accounting
= arg_default_tasks_accounting
;
776 m
->default_tasks_max
= arg_default_tasks_max
;
777 m
->default_memory_pressure_watch
= arg_default_memory_pressure_watch
;
778 m
->default_memory_pressure_threshold_usec
= arg_default_memory_pressure_threshold_usec
;
779 m
->default_oom_policy
= arg_default_oom_policy
;
780 m
->default_oom_score_adjust_set
= arg_default_oom_score_adjust_set
;
781 m
->default_oom_score_adjust
= arg_default_oom_score_adjust
;
783 (void) manager_set_default_smack_process_label(m
, arg_default_smack_process_label
);
785 (void) manager_set_default_rlimits(m
, arg_default_rlimit
);
787 (void) manager_default_environment(m
);
788 (void) manager_transient_environment_add(m
, arg_default_environment
);
791 static void set_manager_settings(Manager
*m
) {
796 /* Propagates the various manager settings into the manager object, i.e. properties that
797 * effect the manager itself (as opposed to just being inherited into newly allocated
798 * units, see set_manager_defaults() above). */
800 m
->confirm_spawn
= arg_confirm_spawn
;
801 m
->service_watchdogs
= arg_service_watchdogs
;
802 m
->cad_burst_action
= arg_cad_burst_action
;
803 /* Note that we don't do structured initialization here, otherwise it will reset the rate limit
804 * counter on every daemon-reload. */
805 m
->reload_ratelimit
.interval
= arg_reload_limit_interval_sec
;
806 m
->reload_ratelimit
.burst
= arg_reload_limit_burst
;
808 manager_set_watchdog(m
, WATCHDOG_RUNTIME
, arg_runtime_watchdog
);
809 manager_set_watchdog(m
, WATCHDOG_REBOOT
, arg_reboot_watchdog
);
810 manager_set_watchdog(m
, WATCHDOG_KEXEC
, arg_kexec_watchdog
);
811 manager_set_watchdog(m
, WATCHDOG_PRETIMEOUT
, arg_pretimeout_watchdog
);
812 r
= manager_set_watchdog_pretimeout_governor(m
, arg_watchdog_pretimeout_governor
);
814 log_warning_errno(r
, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor
);
816 manager_set_show_status(m
, arg_show_status
, "commandline");
817 m
->status_unit_format
= arg_status_unit_format
;
820 static int parse_argv(int argc
, char *argv
[]) {
822 ARG_LOG_LEVEL
= 0x100,
833 ARG_DUMP_CONFIGURATION_ITEMS
,
834 ARG_DUMP_BUS_PROPERTIES
,
844 ARG_DEFAULT_STD_OUTPUT
,
845 ARG_DEFAULT_STD_ERROR
,
847 ARG_SERVICE_WATCHDOGS
,
850 static const struct option options
[] = {
851 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
852 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
853 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
854 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
855 { "log-time", optional_argument
, NULL
, ARG_LOG_TIME
},
856 { "unit", required_argument
, NULL
, ARG_UNIT
},
857 { "system", no_argument
, NULL
, ARG_SYSTEM
},
858 { "user", no_argument
, NULL
, ARG_USER
},
859 { "test", no_argument
, NULL
, ARG_TEST
},
860 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
861 { "help", no_argument
, NULL
, 'h' },
862 { "version", no_argument
, NULL
, ARG_VERSION
},
863 { "dump-configuration-items", no_argument
, NULL
, ARG_DUMP_CONFIGURATION_ITEMS
},
864 { "dump-bus-properties", no_argument
, NULL
, ARG_DUMP_BUS_PROPERTIES
},
865 { "bus-introspect", required_argument
, NULL
, ARG_BUS_INTROSPECT
},
866 { "dump-core", optional_argument
, NULL
, ARG_DUMP_CORE
},
867 { "crash-chvt", required_argument
, NULL
, ARG_CRASH_CHVT
},
868 { "crash-shell", optional_argument
, NULL
, ARG_CRASH_SHELL
},
869 { "crash-reboot", optional_argument
, NULL
, ARG_CRASH_REBOOT
},
870 { "confirm-spawn", optional_argument
, NULL
, ARG_CONFIRM_SPAWN
},
871 { "show-status", optional_argument
, NULL
, ARG_SHOW_STATUS
},
872 { "deserialize", required_argument
, NULL
, ARG_DESERIALIZE
},
873 { "switched-root", no_argument
, NULL
, ARG_SWITCHED_ROOT
},
874 { "default-standard-output", required_argument
, NULL
, ARG_DEFAULT_STD_OUTPUT
, },
875 { "default-standard-error", required_argument
, NULL
, ARG_DEFAULT_STD_ERROR
, },
876 { "machine-id", required_argument
, NULL
, ARG_MACHINE_ID
},
877 { "service-watchdogs", required_argument
, NULL
, ARG_SERVICE_WATCHDOGS
},
882 bool user_arg_seen
= false;
887 if (getpid_cached() == 1)
890 while ((c
= getopt_long(argc
, argv
, "hDbsz:", options
, NULL
)) >= 0)
895 r
= log_set_max_level_from_string(optarg
);
897 return log_error_errno(r
, "Failed to parse log level \"%s\": %m", optarg
);
902 r
= log_set_target_from_string(optarg
);
904 return log_error_errno(r
, "Failed to parse log target \"%s\": %m", optarg
);
911 r
= log_show_color_from_string(optarg
);
913 return log_error_errno(r
, "Failed to parse log color setting \"%s\": %m",
916 log_show_color(true);
920 case ARG_LOG_LOCATION
:
922 r
= log_show_location_from_string(optarg
);
924 return log_error_errno(r
, "Failed to parse log location setting \"%s\": %m",
927 log_show_location(true);
934 r
= log_show_time_from_string(optarg
);
936 return log_error_errno(r
, "Failed to parse log time setting \"%s\": %m",
943 case ARG_DEFAULT_STD_OUTPUT
:
944 r
= exec_output_from_string(optarg
);
946 return log_error_errno(r
, "Failed to parse default standard output setting \"%s\": %m",
948 arg_default_std_output
= r
;
951 case ARG_DEFAULT_STD_ERROR
:
952 r
= exec_output_from_string(optarg
);
954 return log_error_errno(r
, "Failed to parse default standard error output setting \"%s\": %m",
956 arg_default_std_error
= r
;
960 r
= free_and_strdup(&arg_default_unit
, optarg
);
962 return log_error_errno(r
, "Failed to set default unit \"%s\": %m", optarg
);
967 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
971 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
972 user_arg_seen
= true;
976 arg_action
= ACTION_TEST
;
980 arg_pager_flags
|= PAGER_DISABLE
;
984 arg_action
= ACTION_VERSION
;
987 case ARG_DUMP_CONFIGURATION_ITEMS
:
988 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
991 case ARG_DUMP_BUS_PROPERTIES
:
992 arg_action
= ACTION_DUMP_BUS_PROPERTIES
;
995 case ARG_BUS_INTROSPECT
:
996 arg_bus_introspect
= optarg
;
997 arg_action
= ACTION_BUS_INTROSPECT
;
1001 r
= parse_boolean_argument("--dump-core", optarg
, &arg_dump_core
);
1006 case ARG_CRASH_CHVT
:
1007 r
= parse_crash_chvt(optarg
, &arg_crash_chvt
);
1009 return log_error_errno(r
, "Failed to parse crash virtual terminal index: \"%s\": %m",
1013 case ARG_CRASH_SHELL
:
1014 r
= parse_boolean_argument("--crash-shell", optarg
, &arg_crash_shell
);
1019 case ARG_CRASH_REBOOT
:
1020 r
= parse_boolean_argument("--crash-reboot", optarg
, &arg_crash_reboot
);
1025 case ARG_CONFIRM_SPAWN
:
1026 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
1028 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
1030 return log_error_errno(r
, "Failed to parse confirm spawn option: \"%s\": %m",
1034 case ARG_SERVICE_WATCHDOGS
:
1035 r
= parse_boolean_argument("--service-watchdogs=", optarg
, &arg_service_watchdogs
);
1040 case ARG_SHOW_STATUS
:
1042 r
= parse_show_status(optarg
, &arg_show_status
);
1044 return log_error_errno(r
, "Failed to parse show status boolean: \"%s\": %m",
1047 arg_show_status
= SHOW_STATUS_YES
;
1050 case ARG_DESERIALIZE
: {
1054 r
= safe_atoi(optarg
, &fd
);
1056 log_error_errno(r
, "Failed to parse deserialize option \"%s\": %m", optarg
);
1058 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1059 "Invalid deserialize fd: %d",
1062 (void) fd_cloexec(fd
, true);
1064 f
= fdopen(fd
, "r");
1066 return log_error_errno(errno
, "Failed to open serialization fd %d: %m", fd
);
1068 safe_fclose(arg_serialization
);
1069 arg_serialization
= f
;
1074 case ARG_SWITCHED_ROOT
:
1075 arg_switched_root
= true;
1078 case ARG_MACHINE_ID
:
1079 r
= set_machine_id(optarg
);
1081 return log_error_errno(r
, "MachineID '%s' is not valid: %m", optarg
);
1085 arg_action
= ACTION_HELP
;
1089 log_set_max_level(LOG_DEBUG
);
1095 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1096 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1099 if (getpid_cached() != 1)
1105 assert_not_reached();
1108 if (optind
< argc
&& getpid_cached() != 1)
1109 /* Hmm, when we aren't run as init system let's complain about excess arguments */
1110 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Excess arguments.");
1112 if (arg_action
== ACTION_RUN
&& arg_runtime_scope
== RUNTIME_SCOPE_USER
&& !user_arg_seen
)
1113 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1114 "Explicit --user argument required to run as user manager.");
1119 static int help(void) {
1120 _cleanup_free_
char *link
= NULL
;
1123 r
= terminal_urlify_man("systemd", "1", &link
);
1127 printf("%s [OPTIONS...]\n\n"
1128 "%sStarts and monitors system and user services.%s\n\n"
1129 "This program takes no positional arguments.\n\n"
1131 " -h --help Show this help\n"
1132 " --version Show version\n"
1133 " --test Determine initial transaction, dump it and exit\n"
1134 " --system Combined with --test: operate in system mode\n"
1135 " --user Combined with --test: operate in user mode\n"
1136 " --dump-configuration-items Dump understood unit configuration items\n"
1137 " --dump-bus-properties Dump exposed bus properties\n"
1138 " --bus-introspect=PATH Write XML introspection data\n"
1139 " --unit=UNIT Set default unit\n"
1140 " --dump-core[=BOOL] Dump core on crash\n"
1141 " --crash-vt=NR Change to specified VT on crash\n"
1142 " --crash-reboot[=BOOL] Reboot on crash\n"
1143 " --crash-shell[=BOOL] Run shell on crash\n"
1144 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1145 " --show-status[=BOOL] Show status updates on the console during boot\n"
1146 " --log-target=TARGET Set log target (console, journal, kmsg,\n"
1147 " journal-or-kmsg, null)\n"
1148 " --log-level=LEVEL Set log level (debug, info, notice, warning,\n"
1149 " err, crit, alert, emerg)\n"
1150 " --log-color[=BOOL] Highlight important log messages\n"
1151 " --log-location[=BOOL] Include code location in log messages\n"
1152 " --log-time[=BOOL] Prefix log messages with current time\n"
1153 " --default-standard-output= Set default standard output for services\n"
1154 " --default-standard-error= Set default standard error output for services\n"
1155 " --no-pager Do not pipe output into a pager\n"
1156 "\nSee the %s for details.\n",
1157 program_invocation_short_name
,
1167 static int prepare_reexecute(
1171 bool switching_root
) {
1173 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1174 _cleanup_fclose_
FILE *f
= NULL
;
1181 r
= manager_open_serialization(m
, &f
);
1183 return log_error_errno(r
, "Failed to create serialization file: %m");
1185 /* Make sure nothing is really destructed when we shut down */
1187 bus_manager_send_reloading(m
, true);
1193 r
= manager_serialize(m
, f
, fds
, switching_root
);
1197 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1198 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1200 r
= fd_cloexec(fileno(f
), false);
1202 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1204 r
= fdset_cloexec(fds
, false);
1206 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1208 *ret_f
= TAKE_PTR(f
);
1209 *ret_fds
= TAKE_PTR(fds
);
1214 static void bump_file_max_and_nr_open(void) {
1216 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
1217 * numbers of file descriptors are no longer a performance problem and their memory is properly
1218 * tracked by memcg, thus counting them and limiting them in another two layers of limits is
1219 * unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
1220 * on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
1222 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1226 #if BUMP_PROC_SYS_FS_FILE_MAX
1227 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
1228 * different, but the operation would fail silently.) */
1229 r
= sysctl_write("fs/file-max", LONG_MAX_STR
);
1231 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
,
1232 r
, "Failed to bump fs.file-max, ignoring: %m");
1235 #if BUMP_PROC_SYS_FS_NR_OPEN
1238 /* Argh! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know
1239 * what they are. The expression by which the maximum is determined is dependent on the architecture,
1240 * and is something we don't really want to copy to userspace, as it is dependent on implementation
1241 * details of the kernel. Since the kernel doesn't expose the maximum value to us, we can only try
1242 * and hope. Hence, let's start with INT_MAX, and then keep halving the value until we find one that
1243 * works. Ugly? Yes, absolutely, but kernel APIs are kernel APIs, so what do can we do... 🤯 */
1248 v
&= ~(__SIZEOF_POINTER__
- 1); /* Round down to next multiple of the pointer size */
1250 log_warning("Can't bump fs.nr_open, value too small.");
1256 log_error_errno(k
, "Failed to read fs.nr_open: %m");
1259 if (k
>= v
) { /* Already larger */
1260 log_debug("Skipping bump, value is already larger.");
1264 r
= sysctl_writef("fs/nr_open", "%i", v
);
1266 log_debug("Couldn't write fs.nr_open as %i, halving it.", v
);
1271 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.nr_open, ignoring: %m");
1275 log_debug("Successfully bumped fs.nr_open to %i", v
);
1281 static int bump_rlimit_nofile(const struct rlimit
*saved_rlimit
) {
1282 struct rlimit new_rlimit
;
1285 /* Get the underlying absolute limit the kernel enforces */
1286 nr
= read_nr_open();
1288 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1289 new_rlimit
= (struct rlimit
) {
1290 .rlim_cur
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_cur
),
1291 .rlim_max
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_max
),
1294 /* Shortcut if nothing changes. */
1295 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_max
&&
1296 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_cur
) {
1297 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1301 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1302 * both hard and soft. */
1303 r
= setrlimit_closest(RLIMIT_NOFILE
, &new_rlimit
);
1305 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1310 static int bump_rlimit_memlock(const struct rlimit
*saved_rlimit
) {
1311 struct rlimit new_rlimit
;
1315 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
1316 * which should normally disable such checks. We need them to implement IPAddressAllow= and
1317 * IPAddressDeny=, hence let's bump the value high enough for our user. */
1319 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1320 * must be unsigned, hence this is a given, but let's make this clear here. */
1321 assert_cc(RLIM_INFINITY
> 0);
1323 mm
= physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
1324 * physical RAM. We allow an eighth to be locked by us, just to
1327 new_rlimit
= (struct rlimit
) {
1328 .rlim_cur
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_cur
, mm
),
1329 .rlim_max
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_max
, mm
),
1332 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_cur
&&
1333 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_max
) {
1334 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1338 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &new_rlimit
);
1340 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1345 static void test_usr(void) {
1347 /* Check that /usr is either on the same file system as / or mounted already. */
1349 if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) <= 0)
1352 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1353 "Some things will probably break (sometimes even silently) in mysterious ways. "
1354 "Consult https://www.freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1357 static int enforce_syscall_archs(Set
*archs
) {
1361 if (!is_seccomp_available())
1364 r
= seccomp_restrict_archs(arg_syscall_archs
);
1366 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1371 static int os_release_status(void) {
1372 _cleanup_free_
char *pretty_name
= NULL
, *name
= NULL
, *version
= NULL
,
1373 *ansi_color
= NULL
, *support_end
= NULL
;
1376 r
= parse_os_release(NULL
,
1377 "PRETTY_NAME", &pretty_name
,
1379 "VERSION", &version
,
1380 "ANSI_COLOR", &ansi_color
,
1381 "SUPPORT_END", &support_end
);
1383 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1384 "Failed to read os-release file, ignoring: %m");
1386 const char *label
= os_release_pretty_name(pretty_name
, name
);
1388 if (show_status_on(arg_show_status
)) {
1389 if (log_get_show_color())
1390 status_printf(NULL
, 0,
1391 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1392 empty_to_null(ansi_color
) ?: "1",
1395 status_printf(NULL
, 0,
1396 "\nWelcome to %s!\n",
1400 if (support_end
&& os_release_support_ended(support_end
, /* quiet */ false, NULL
) > 0)
1401 /* pretty_name may include the version already, so we'll print the version only if we
1402 * have it and we're not using pretty_name. */
1403 status_printf(ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
, 0,
1404 "This OS version (%s%s%s) is past its end-of-support date (%s)",
1406 (pretty_name
|| !version
) ? "" : " version ",
1407 (pretty_name
|| !version
) ? "" : version
,
1413 static int write_container_id(void) {
1415 int r
= 0; /* avoid false maybe-uninitialized warning */
1417 c
= getenv("container");
1422 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1424 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1429 static int bump_unix_max_dgram_qlen(void) {
1430 _cleanup_free_
char *qlen
= NULL
;
1434 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
1435 * the value really really early during boot, so that it is actually applied to all our sockets,
1436 * including the $NOTIFY_SOCKET one. */
1438 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1440 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1441 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1443 r
= safe_atolu(qlen
, &v
);
1445 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen
);
1447 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1450 r
= sysctl_write("net/unix/max_dgram_qlen", STRINGIFY(DEFAULT_UNIX_MAX_DGRAM_QLEN
));
1452 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1453 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1458 static int fixup_environment(void) {
1459 _cleanup_free_
char *term
= NULL
;
1463 /* Only fix up the environment when we are started as PID 1 */
1464 if (getpid_cached() != 1)
1467 /* We expect the environment to be set correctly if run inside a container. */
1468 if (detect_container() > 0)
1471 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
1472 * backend device used by the console. We try to make a better guess here since some consoles might
1473 * not have support for color mode for example.
1475 * However if TERM was configured through the kernel command line then leave it alone. */
1476 r
= proc_cmdline_get_key("TERM", 0, &term
);
1480 t
= term
?: default_term_for_tty("/dev/console");
1482 if (setenv("TERM", t
, 1) < 0)
1485 /* The kernels sets HOME=/ for init. Let's undo this. */
1486 if (path_equal_ptr(getenv("HOME"), "/"))
1487 assert_se(unsetenv("HOME") == 0);
1492 static void redirect_telinit(int argc
, char *argv
[]) {
1494 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1496 #if HAVE_SYSV_COMPAT
1497 if (getpid_cached() == 1)
1500 if (!invoked_as(argv
, "init"))
1503 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1504 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1509 static int become_shutdown(int objective
, int retval
) {
1511 static const char* const table
[_MANAGER_OBJECTIVE_MAX
] = {
1512 [MANAGER_EXIT
] = "exit",
1513 [MANAGER_REBOOT
] = "reboot",
1514 [MANAGER_POWEROFF
] = "poweroff",
1515 [MANAGER_HALT
] = "halt",
1516 [MANAGER_KEXEC
] = "kexec",
1519 char log_level
[DECIMAL_STR_MAX(int) + 1],
1520 exit_code
[DECIMAL_STR_MAX(uint8_t) + 1],
1521 timeout
[DECIMAL_STR_MAX(usec_t
) + 1];
1523 const char* command_line
[13] = {
1524 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1526 "--timeout", timeout
,
1527 "--log-level", log_level
,
1531 _cleanup_strv_free_
char **env_block
= NULL
;
1532 usec_t watchdog_timer
= 0;
1536 assert(objective
>= 0 && objective
< _MANAGER_OBJECTIVE_MAX
);
1537 assert(table
[objective
]);
1538 assert(!command_line
[pos
]);
1539 env_block
= strv_copy(environ
);
1541 xsprintf(log_level
, "%d", log_get_max_level());
1542 xsprintf(timeout
, "%" PRI_USEC
"us", arg_default_timeout_stop_usec
);
1544 switch (log_get_target()) {
1546 case LOG_TARGET_KMSG
:
1547 case LOG_TARGET_JOURNAL_OR_KMSG
:
1548 case LOG_TARGET_SYSLOG_OR_KMSG
:
1549 command_line
[pos
++] = "kmsg";
1552 case LOG_TARGET_NULL
:
1553 command_line
[pos
++] = "null";
1556 case LOG_TARGET_CONSOLE
:
1558 command_line
[pos
++] = "console";
1562 if (log_get_show_color())
1563 command_line
[pos
++] = "--log-color";
1565 if (log_get_show_location())
1566 command_line
[pos
++] = "--log-location";
1568 if (log_get_show_time())
1569 command_line
[pos
++] = "--log-time";
1571 if (objective
== MANAGER_EXIT
) {
1572 command_line
[pos
++] = "--exit-code";
1573 command_line
[pos
++] = exit_code
;
1574 xsprintf(exit_code
, "%d", retval
);
1577 assert(pos
< ELEMENTSOF(command_line
));
1579 if (objective
== MANAGER_REBOOT
)
1580 watchdog_timer
= arg_reboot_watchdog
;
1581 else if (objective
== MANAGER_KEXEC
)
1582 watchdog_timer
= arg_kexec_watchdog
;
1584 /* If we reboot or kexec let's set the shutdown watchdog and tell the
1585 * shutdown binary to repeatedly ping it.
1586 * Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
1587 (void) watchdog_setup_pretimeout(0);
1588 (void) watchdog_setup_pretimeout_governor(NULL
);
1589 r
= watchdog_setup(watchdog_timer
);
1590 watchdog_close(r
< 0);
1592 /* Tell the binary how often to ping, ignore failure */
1593 (void) strv_extendf(&env_block
, "WATCHDOG_USEC="USEC_FMT
, watchdog_timer
);
1595 if (arg_watchdog_device
)
1596 (void) strv_extendf(&env_block
, "WATCHDOG_DEVICE=%s", arg_watchdog_device
);
1598 /* Avoid the creation of new processes forked by the kernel; at this
1599 * point, we will not listen to the signals anyway */
1600 if (detect_container() <= 0)
1601 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1603 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1607 static void initialize_clock(void) {
1610 /* This is called very early on, before we parse the kernel command line or otherwise figure out why
1611 * we are running, but only once. */
1613 if (clock_is_localtime(NULL
) > 0) {
1616 /* The very first call of settimeofday() also does a time warp in the kernel.
1618 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
1619 * take care of maintaining the RTC and do all adjustments. This matches the behavior of
1620 * Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
1622 r
= clock_set_timezone(&min
);
1624 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1626 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1628 } else if (!in_initrd())
1630 * Do a dummy very first call to seal the kernel's time warp magic.
1632 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
1633 * LOCAL, but the real system could be set up that way. In such case, we need to delay the
1634 * time-warp or the sealing until we reach the real system.
1636 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
1637 * the time will jump or be incorrect at every daylight saving time change. All kernel local
1638 * time concepts will be treated as UTC that way.
1640 (void) clock_reset_timewarp();
1642 ClockChangeDirection change_dir
;
1643 r
= clock_apply_epoch(&change_dir
);
1644 if (r
> 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1645 log_info("System time before build time, advancing clock.");
1646 else if (r
> 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1647 log_info("System time is further ahead than %s after build time, resetting clock to build time.",
1648 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1649 else if (r
< 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1650 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1651 else if (r
< 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1652 log_error_errno(r
, "Current system time is further ahead %s after build time, but cannot correct: %m",
1653 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1656 static void apply_clock_update(void) {
1657 /* This is called later than initialize_clock(), i.e. after we parsed configuration files/kernel
1658 * command line and such. */
1660 if (arg_clock_usec
== 0)
1663 if (getpid_cached() != 1)
1666 if (clock_settime(CLOCK_REALTIME
, TIMESPEC_STORE(arg_clock_usec
)) < 0)
1667 log_error_errno(errno
, "Failed to set system clock to time specified on kernel command line: %m");
1669 log_info("Set system clock to %s, as specified on the kernel command line.",
1670 FORMAT_TIMESTAMP(arg_clock_usec
));
1673 static void cmdline_take_random_seed(void) {
1677 if (arg_random_seed_size
== 0)
1680 if (getpid_cached() != 1)
1683 assert(arg_random_seed
);
1684 suggested
= random_pool_size();
1686 if (arg_random_seed_size
< suggested
)
1687 log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
1688 arg_random_seed_size
, suggested
);
1690 r
= random_write_entropy(-1, arg_random_seed
, arg_random_seed_size
, true);
1692 log_warning_errno(r
, "Failed to credit entropy specified on kernel command line, ignoring: %m");
1696 log_notice("Successfully credited entropy passed on kernel command line.\n"
1697 "Note that the seed provided this way is accessible to unprivileged programs. "
1698 "This functionality should not be used outside of testing environments.");
1701 static void initialize_coredump(bool skip_setup
) {
1703 if (getpid_cached() != 1)
1706 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
1707 * the limit) will process core dumps for system services by default. */
1708 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1709 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1711 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1712 * until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
1713 * command line later so core dumps can still be generated during early startup and in initrd. */
1715 disable_coredumps();
1719 static void initialize_core_pattern(bool skip_setup
) {
1722 if (skip_setup
|| !arg_early_core_pattern
)
1725 if (getpid_cached() != 1)
1728 r
= write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1730 log_warning_errno(r
, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1731 arg_early_core_pattern
);
1734 static void update_cpu_affinity(bool skip_setup
) {
1735 _cleanup_free_
char *mask
= NULL
;
1737 if (skip_setup
|| !arg_cpu_affinity
.set
)
1740 assert(arg_cpu_affinity
.allocated
> 0);
1742 mask
= cpu_set_to_range_string(&arg_cpu_affinity
);
1743 log_debug("Setting CPU affinity to {%s}.", strnull(mask
));
1745 if (sched_setaffinity(0, arg_cpu_affinity
.allocated
, arg_cpu_affinity
.set
) < 0)
1746 log_warning_errno(errno
, "Failed to set CPU affinity, ignoring: %m");
1749 static void update_numa_policy(bool skip_setup
) {
1751 _cleanup_free_
char *nodes
= NULL
;
1752 const char * policy
= NULL
;
1754 if (skip_setup
|| !mpol_is_valid(numa_policy_get_type(&arg_numa_policy
)))
1757 if (DEBUG_LOGGING
) {
1758 policy
= mpol_to_string(numa_policy_get_type(&arg_numa_policy
));
1759 nodes
= cpu_set_to_range_string(&arg_numa_policy
.nodes
);
1760 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy
), strnull(nodes
));
1763 r
= apply_numa_policy(&arg_numa_policy
);
1764 if (r
== -EOPNOTSUPP
)
1765 log_debug_errno(r
, "NUMA support not available, ignoring.");
1767 log_warning_errno(r
, "Failed to set NUMA memory policy, ignoring: %m");
1770 static void filter_args(
1779 /* Copy some filtered arguments into the dst array from src. */
1780 for (int i
= 1; i
< argc
; i
++) {
1781 if (STR_IN_SET(src
[i
],
1787 if (startswith(src
[i
], "--deserialize="))
1789 if (streq(src
[i
], "--deserialize")) {
1790 i
++; /* Skip the argument too */
1794 /* Skip target unit designators. We already acted upon this information and have queued
1795 * appropriate jobs. We don't want to redo all this after reexecution. */
1796 if (startswith(src
[i
], "--unit="))
1798 if (streq(src
[i
], "--unit")) {
1799 i
++; /* Skip the argument too */
1803 /* Seems we have a good old option. Let's pass it over to the new instance. */
1804 dst
[(*dst_index
)++] = src
[i
];
1808 static int do_reexecute(
1809 ManagerObjective objective
,
1812 const struct rlimit
*saved_rlimit_nofile
,
1813 const struct rlimit
*saved_rlimit_memlock
,
1815 const char *switch_root_dir
,
1816 const char *switch_root_init
,
1817 const char **ret_error_message
) {
1819 size_t i
, args_size
;
1823 assert(IN_SET(objective
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
));
1825 assert(saved_rlimit_nofile
);
1826 assert(saved_rlimit_memlock
);
1827 assert(ret_error_message
);
1829 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1830 * rebooted while we do that */
1831 watchdog_close(true);
1833 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1834 * the kernel default to its child processes */
1835 if (saved_rlimit_nofile
->rlim_cur
!= 0)
1836 (void) setrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
);
1837 if (saved_rlimit_memlock
->rlim_cur
!= RLIM_INFINITY
)
1838 (void) setrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
);
1840 if (switch_root_dir
) {
1841 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can
1842 * handle the SIGCHLD for them after deserializing. */
1843 broadcast_signal(SIGTERM
, false, true, arg_default_timeout_stop_usec
);
1845 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1846 r
= switch_root(switch_root_dir
, "/mnt", true, MS_MOVE
);
1848 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
1851 args_size
= argc
+ 6;
1852 args
= newa(const char*, args_size
);
1854 if (!switch_root_init
) {
1855 char sfd
[DECIMAL_STR_MAX(int)];
1857 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1858 * only if the user didn't specify an explicit init to spawn. */
1860 assert(arg_serialization
);
1863 xsprintf(sfd
, "%i", fileno(arg_serialization
));
1865 i
= 1; /* Leave args[0] empty for now. */
1866 filter_args(args
, &i
, argv
, argc
);
1868 if (switch_root_dir
)
1869 args
[i
++] = "--switched-root";
1870 args
[i
++] = runtime_scope_cmdline_option_to_string(arg_runtime_scope
);
1871 args
[i
++] = "--deserialize";
1875 assert(i
<= args_size
);
1878 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
1879 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
1880 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
1881 * and wait() for it in the parent, before proceeding into the exec().
1883 valgrind_summary_hack();
1885 args
[0] = SYSTEMD_BINARY_PATH
;
1886 (void) execv(args
[0], (char* const*) args
);
1888 if (objective
== MANAGER_REEXECUTE
) {
1889 *ret_error_message
= "Failed to execute our own binary";
1890 return log_error_errno(errno
, "Failed to execute our own binary %s: %m", args
[0]);
1893 log_debug_errno(errno
, "Failed to execute our own binary %s, trying fallback: %m", args
[0]);
1896 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
1897 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
1898 * but let's hope that doesn't matter.) */
1900 arg_serialization
= safe_fclose(arg_serialization
);
1901 fds
= fdset_free(fds
);
1903 /* Reopen the console */
1904 (void) make_console_stdio();
1906 i
= 1; /* Leave args[0] empty for now. */
1907 for (int j
= 1; j
<= argc
; j
++)
1908 args
[i
++] = argv
[j
];
1909 assert(i
<= args_size
);
1911 /* Re-enable any blocked signals, especially important if we switch from initrd to init=... */
1912 (void) reset_all_signal_handlers();
1913 (void) reset_signal_mask();
1914 (void) rlimit_nofile_safe();
1916 if (switch_root_init
) {
1917 args
[0] = switch_root_init
;
1918 (void) execve(args
[0], (char* const*) args
, saved_env
);
1919 log_warning_errno(errno
, "Failed to execute configured init %s, trying fallback: %m", args
[0]);
1922 args
[0] = "/sbin/init";
1923 (void) execv(args
[0], (char* const*) args
);
1926 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
1927 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
1928 "Failed to execute /sbin/init");
1930 *ret_error_message
= "Failed to execute fallback shell";
1932 log_warning("No /sbin/init, trying fallback");
1934 args
[0] = "/bin/sh";
1936 (void) execve(args
[0], (char* const*) args
, saved_env
);
1937 return log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
1939 return log_error_errno(r
, "Failed to execute /sbin/init, giving up: %m");
1942 static int invoke_main_loop(
1944 const struct rlimit
*saved_rlimit_nofile
,
1945 const struct rlimit
*saved_rlimit_memlock
,
1946 int *ret_retval
, /* Return parameters relevant for shutting down */
1947 FDSet
**ret_fds
, /* Return parameters for reexecuting */
1948 char **ret_switch_root_dir
, /* … */
1949 char **ret_switch_root_init
, /* … */
1950 const char **ret_error_message
) {
1955 assert(saved_rlimit_nofile
);
1956 assert(saved_rlimit_memlock
);
1959 assert(ret_switch_root_dir
);
1960 assert(ret_switch_root_init
);
1961 assert(ret_error_message
);
1964 int objective
= manager_loop(m
);
1965 if (objective
< 0) {
1966 *ret_error_message
= "Failed to run main loop";
1967 return log_emergency_errno(objective
, "Failed to run main loop: %m");
1970 switch (objective
) {
1972 case MANAGER_RELOAD
: {
1973 LogTarget saved_log_target
;
1974 int saved_log_level
;
1976 manager_send_reloading(m
);
1978 log_info("Reloading...");
1980 /* First, save any overridden log level/target, then parse the configuration file,
1981 * which might change the log level to new settings. */
1983 saved_log_level
= m
->log_level_overridden
? log_get_max_level() : -1;
1984 saved_log_target
= m
->log_target_overridden
? log_get_target() : _LOG_TARGET_INVALID
;
1986 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
1988 set_manager_defaults(m
);
1989 set_manager_settings(m
);
1991 update_cpu_affinity(false);
1992 update_numa_policy(false);
1994 if (saved_log_level
>= 0)
1995 manager_override_log_level(m
, saved_log_level
);
1996 if (saved_log_target
>= 0)
1997 manager_override_log_target(m
, saved_log_target
);
1999 if (manager_reload(m
) < 0)
2000 /* Reloading failed before the point of no return.
2001 * Let's continue running as if nothing happened. */
2002 m
->objective
= MANAGER_OK
;
2004 log_info("Reloading finished in " USEC_FMT
" ms.",
2005 usec_sub_unsigned(now(CLOCK_MONOTONIC
), m
->timestamps
[MANAGER_TIMESTAMP_UNITS_LOAD
].monotonic
) / USEC_PER_MSEC
);
2010 case MANAGER_REEXECUTE
:
2012 manager_send_reloading(m
); /* From the perspective of the manager calling us this is
2013 * pretty much the same as a reload */
2015 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, false);
2017 *ret_error_message
= "Failed to prepare for reexecution";
2021 log_notice("Reexecuting.");
2023 *ret_retval
= EXIT_SUCCESS
;
2024 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2028 case MANAGER_SWITCH_ROOT
:
2030 manager_send_reloading(m
); /* From the perspective of the manager calling us this is
2031 * pretty much the same as a reload */
2033 manager_set_switching_root(m
, true);
2035 if (!m
->switch_root_init
) {
2036 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, true);
2038 *ret_error_message
= "Failed to prepare for reexecution";
2044 log_notice("Switching root.");
2046 *ret_retval
= EXIT_SUCCESS
;
2048 /* Steal the switch root parameters */
2049 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
2050 *ret_switch_root_init
= TAKE_PTR(m
->switch_root_init
);
2055 if (MANAGER_IS_USER(m
)) {
2058 *ret_retval
= m
->return_value
;
2060 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2066 case MANAGER_REBOOT
:
2067 case MANAGER_POWEROFF
:
2069 case MANAGER_KEXEC
: {
2070 log_notice("Shutting down.");
2072 *ret_retval
= m
->return_value
;
2074 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2080 assert_not_reached();
2085 static void log_execution_mode(bool *ret_first_boot
) {
2086 bool first_boot
= false;
2089 assert(ret_first_boot
);
2091 switch (arg_runtime_scope
) {
2093 case RUNTIME_SCOPE_SYSTEM
: {
2097 log_info("systemd " GIT_VERSION
" running in %ssystem mode (%s)",
2098 arg_action
== ACTION_TEST
? "test " : "",
2101 v
= detect_virtualization();
2103 log_info("Detected virtualization %s.", virtualization_to_string(v
));
2105 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2108 log_info("Running in initrd.");
2110 _cleanup_free_
char *id_text
= NULL
;
2112 /* Let's check whether we are in first boot. First, check if an override was
2113 * specified on the kernel commandline. If yes, we honour that. */
2115 r
= proc_cmdline_get_bool("systemd.condition-first-boot", &first_boot
);
2117 log_debug_errno(r
, "Failed to parse systemd.condition-first-boot= kernel commandline argument, ignoring: %m");
2120 log_full(first_boot
? LOG_INFO
: LOG_DEBUG
,
2121 "Kernel commandline argument says we are %s first boot.",
2122 first_boot
? "in" : "not in");
2124 /* Second, perform autodetection. We use /etc/machine-id as flag file for
2125 * this: If it is missing or contains the value "uninitialized", this is the
2126 * first boot. In other cases, it is not. This allows container managers and
2127 * installers to provision a couple of files in /etc but still permit the
2128 * first-boot initialization to occur. If the container manager wants to
2129 * provision the machine ID it should pass $container_uuid to PID 1. */
2131 r
= read_one_line_file("/etc/machine-id", &id_text
);
2132 if (r
< 0 || streq(id_text
, "uninitialized")) {
2133 if (r
< 0 && r
!= -ENOENT
)
2134 log_warning_errno(r
, "Unexpected error while reading /etc/machine-id, ignoring: %m");
2137 log_info("Detected first boot.");
2139 log_debug("Detected initialized system, this is not the first boot.");
2143 assert_se(uname(&uts
) >= 0);
2145 if (strverscmp_improved(uts
.release
, KERNEL_BASELINE_VERSION
) < 0)
2146 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2147 "Your mileage may vary.", uts
.release
, KERNEL_BASELINE_VERSION
);
2149 log_debug("Kernel version %s, our baseline is %s", uts
.release
, KERNEL_BASELINE_VERSION
);
2154 case RUNTIME_SCOPE_USER
:
2155 if (DEBUG_LOGGING
) {
2156 _cleanup_free_
char *t
= NULL
;
2158 t
= uid_to_name(getuid());
2159 log_debug("systemd " GIT_VERSION
" running in %suser mode for user " UID_FMT
"/%s. (%s)",
2160 arg_action
== ACTION_TEST
? " test" : "",
2161 getuid(), strna(t
), systemd_features
);
2167 assert_not_reached();
2170 *ret_first_boot
= first_boot
;
2173 static int initialize_runtime(
2176 struct rlimit
*saved_rlimit_nofile
,
2177 struct rlimit
*saved_rlimit_memlock
,
2178 const char **ret_error_message
) {
2181 assert(ret_error_message
);
2183 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2185 * - Some only apply to --system instances
2186 * - Some only apply to --user instances
2187 * - Some only apply when we first start up, but not when we reexecute
2190 if (arg_action
!= ACTION_RUN
)
2193 update_cpu_affinity(skip_setup
);
2194 update_numa_policy(skip_setup
);
2196 switch (arg_runtime_scope
) {
2198 case RUNTIME_SCOPE_SYSTEM
:
2199 /* Make sure we leave a core dump without panicking the kernel. */
2200 install_crash_handler();
2203 r
= mount_cgroup_controllers();
2205 *ret_error_message
= "Failed to mount cgroup hierarchies";
2209 (void) os_release_status();
2210 (void) hostname_setup(true);
2211 /* Force transient machine-id on first boot. */
2212 machine_id_setup(NULL
, /* force_transient= */ first_boot
, arg_machine_id
, NULL
);
2213 (void) loopback_setup();
2214 bump_unix_max_dgram_qlen();
2215 bump_file_max_and_nr_open();
2217 write_container_id();
2220 r
= watchdog_set_device(arg_watchdog_device
);
2222 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device
);
2226 case RUNTIME_SCOPE_USER
: {
2227 _cleanup_free_
char *p
= NULL
;
2229 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2230 * user mode. In system mode mount_setup() already did that. */
2232 r
= xdg_user_runtime_dir(&p
, "/systemd");
2234 *ret_error_message
= "$XDG_RUNTIME_DIR is not set";
2235 return log_emergency_errno(r
, "Failed to determine $XDG_RUNTIME_DIR path: %m");
2238 (void) mkdir_p_label(p
, 0755);
2239 (void) make_inaccessible_nodes(p
, UID_INVALID
, GID_INVALID
);
2244 assert_not_reached();
2247 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
2248 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
2249 log_warning_errno(errno
, "Failed to adjust timer slack, ignoring: %m");
2251 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2253 if (!cap_test_all(arg_capability_bounding_set
)) {
2254 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
2256 *ret_error_message
= "Failed to drop capability bounding set of usermode helpers";
2257 return log_emergency_errno(r
, "Failed to drop capability bounding set of usermode helpers: %m");
2260 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
2262 *ret_error_message
= "Failed to drop capability bounding set";
2263 return log_emergency_errno(r
, "Failed to drop capability bounding set: %m");
2267 if (arg_no_new_privs
) {
2268 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2269 *ret_error_message
= "Failed to disable new privileges";
2270 return log_emergency_errno(errno
, "Failed to disable new privileges: %m");
2275 if (arg_syscall_archs
) {
2276 r
= enforce_syscall_archs(arg_syscall_archs
);
2278 *ret_error_message
= "Failed to set syscall architectures";
2283 if (arg_runtime_scope
== RUNTIME_SCOPE_USER
)
2284 /* Become reaper of our children */
2285 if (prctl(PR_SET_CHILD_SUBREAPER
, 1) < 0)
2286 log_warning_errno(errno
, "Failed to make us a subreaper, ignoring: %m");
2288 /* Bump up RLIMIT_NOFILE for systemd itself */
2289 (void) bump_rlimit_nofile(saved_rlimit_nofile
);
2290 (void) bump_rlimit_memlock(saved_rlimit_memlock
);
2292 /* Pull credentials from various sources into a common credential directory */
2293 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
&& !skip_setup
)
2294 (void) import_credentials();
2299 static int do_queue_default_job(
2301 const char **ret_error_message
) {
2303 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2309 if (arg_default_unit
)
2310 unit
= arg_default_unit
;
2311 else if (in_initrd())
2312 unit
= SPECIAL_INITRD_TARGET
;
2314 unit
= SPECIAL_DEFAULT_TARGET
;
2316 log_debug("Activating default unit: %s", unit
);
2318 r
= manager_load_startable_unit_or_warn(m
, unit
, NULL
, &target
);
2319 if (r
< 0 && in_initrd() && !arg_default_unit
) {
2320 /* Fall back to default.target, which we used to always use by default. Only do this if no
2321 * explicit configuration was given. */
2323 log_info("Falling back to " SPECIAL_DEFAULT_TARGET
".");
2325 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_DEFAULT_TARGET
, NULL
, &target
);
2328 log_info("Falling back to " SPECIAL_RESCUE_TARGET
".");
2330 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_RESCUE_TARGET
, NULL
, &target
);
2332 *ret_error_message
= r
== -ERFKILL
? SPECIAL_RESCUE_TARGET
" masked"
2333 : "Failed to load " SPECIAL_RESCUE_TARGET
;
2338 assert(target
->load_state
== UNIT_LOADED
);
2340 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, NULL
, &error
, &job
);
2342 log_debug_errno(r
, "Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
2344 sd_bus_error_free(&error
);
2346 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, NULL
, &error
, &job
);
2348 *ret_error_message
= "Failed to start default target";
2349 return log_emergency_errno(r
, "Failed to start default target: %s", bus_error_message(&error
, r
));
2353 *ret_error_message
= "Failed to isolate default target";
2354 return log_emergency_errno(r
, "Failed to isolate default target: %s", bus_error_message(&error
, r
));
2356 log_info("Queued %s job for default target %s.",
2357 job_type_to_string(job
->type
),
2358 unit_status_string(job
->unit
, NULL
));
2360 m
->default_unit_job_id
= job
->id
;
2365 static void save_rlimits(struct rlimit
*saved_rlimit_nofile
,
2366 struct rlimit
*saved_rlimit_memlock
) {
2368 assert(saved_rlimit_nofile
);
2369 assert(saved_rlimit_memlock
);
2371 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
) < 0)
2372 log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2374 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
) < 0)
2375 log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2378 static void fallback_rlimit_nofile(const struct rlimit
*saved_rlimit_nofile
) {
2381 if (arg_default_rlimit
[RLIMIT_NOFILE
])
2384 /* Make sure forked processes get limits based on the original kernel setting */
2386 rl
= newdup(struct rlimit
, saved_rlimit_nofile
, 1);
2392 /* Bump the hard limit for system services to a substantially higher value. The default
2393 * hard limit current kernels set is pretty low (4K), mostly for historical
2394 * reasons. According to kernel developers, the fd handling in recent kernels has been
2395 * optimized substantially enough, so that we can bump the limit now, without paying too
2396 * high a price in memory or performance. Note however that we only bump the hard limit,
2397 * not the soft limit. That's because select() works the way it works, and chokes on fds
2398 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2399 * unexpecting programs that they get fds higher than what they can process using
2400 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2401 * this pitfall: programs that are written by folks aware of the select() problem in mind
2402 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2403 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2405 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2408 /* Get the underlying absolute limit the kernel enforces */
2409 nr
= read_nr_open();
2411 rl
->rlim_max
= MIN((rlim_t
) nr
, MAX(rl
->rlim_max
, (rlim_t
) HIGH_RLIMIT_NOFILE
));
2414 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2415 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2416 * instance), then lower what we pass on to not confuse our children */
2417 rl
->rlim_cur
= MIN(rl
->rlim_cur
, (rlim_t
) FD_SETSIZE
);
2419 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
2422 static void fallback_rlimit_memlock(const struct rlimit
*saved_rlimit_memlock
) {
2425 /* Pass the original value down to invoked processes */
2427 if (arg_default_rlimit
[RLIMIT_MEMLOCK
])
2430 rl
= newdup(struct rlimit
, saved_rlimit_memlock
, 1);
2436 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2437 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2438 * default for this since kernel 5.16) */
2439 rl
->rlim_max
= MAX(rl
->rlim_max
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2440 rl
->rlim_cur
= MAX(rl
->rlim_cur
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2443 arg_default_rlimit
[RLIMIT_MEMLOCK
] = rl
;
2446 static void setenv_manager_environment(void) {
2449 STRV_FOREACH(p
, arg_manager_environment
) {
2450 log_debug("Setting '%s' in our own environment.", *p
);
2452 r
= putenv_dup(*p
, true);
2454 log_warning_errno(errno
, "Failed to setenv \"%s\", ignoring: %m", *p
);
2458 static void reset_arguments(void) {
2459 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2461 arg_default_unit
= mfree(arg_default_unit
);
2463 /* arg_runtime_scope — ignore */
2465 arg_dump_core
= true;
2466 arg_crash_chvt
= -1;
2467 arg_crash_shell
= false;
2468 arg_crash_reboot
= false;
2469 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2470 arg_show_status
= _SHOW_STATUS_INVALID
;
2471 arg_status_unit_format
= STATUS_UNIT_FORMAT_DEFAULT
;
2472 arg_switched_root
= false;
2473 arg_pager_flags
= 0;
2474 arg_service_watchdogs
= true;
2475 arg_default_std_output
= EXEC_OUTPUT_JOURNAL
;
2476 arg_default_std_error
= EXEC_OUTPUT_INHERIT
;
2477 arg_default_restart_usec
= DEFAULT_RESTART_USEC
;
2478 arg_default_timeout_start_usec
= manager_default_timeout(arg_runtime_scope
);
2479 arg_default_timeout_stop_usec
= manager_default_timeout(arg_runtime_scope
);
2480 arg_default_timeout_abort_usec
= manager_default_timeout(arg_runtime_scope
);
2481 arg_default_timeout_abort_set
= false;
2482 arg_default_device_timeout_usec
= manager_default_timeout(arg_runtime_scope
);
2483 arg_default_start_limit_interval
= DEFAULT_START_LIMIT_INTERVAL
;
2484 arg_default_start_limit_burst
= DEFAULT_START_LIMIT_BURST
;
2485 arg_runtime_watchdog
= 0;
2486 arg_reboot_watchdog
= 10 * USEC_PER_MINUTE
;
2487 arg_kexec_watchdog
= 0;
2488 arg_pretimeout_watchdog
= 0;
2489 arg_early_core_pattern
= mfree(arg_early_core_pattern
);
2490 arg_watchdog_device
= mfree(arg_watchdog_device
);
2491 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
2493 arg_default_environment
= strv_free(arg_default_environment
);
2494 arg_manager_environment
= strv_free(arg_manager_environment
);
2495 rlimit_free_all(arg_default_rlimit
);
2497 arg_capability_bounding_set
= CAP_MASK_UNSET
;
2498 arg_no_new_privs
= false;
2499 arg_timer_slack_nsec
= NSEC_INFINITY
;
2500 arg_default_timer_accuracy_usec
= 1 * USEC_PER_MINUTE
;
2502 arg_syscall_archs
= set_free(arg_syscall_archs
);
2504 /* arg_serialization — ignore */
2506 arg_default_cpu_accounting
= -1;
2507 arg_default_io_accounting
= false;
2508 arg_default_ip_accounting
= false;
2509 arg_default_blockio_accounting
= false;
2510 arg_default_memory_accounting
= MEMORY_ACCOUNTING_DEFAULT
;
2511 arg_default_tasks_accounting
= true;
2512 arg_default_tasks_max
= DEFAULT_TASKS_MAX
;
2513 arg_default_memory_pressure_threshold_usec
= MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC
;
2514 arg_default_memory_pressure_watch
= CGROUP_PRESSURE_WATCH_AUTO
;
2515 arg_machine_id
= (sd_id128_t
) {};
2516 arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
2517 arg_default_oom_policy
= OOM_STOP
;
2519 cpu_set_reset(&arg_cpu_affinity
);
2520 numa_policy_reset(&arg_numa_policy
);
2522 arg_random_seed
= mfree(arg_random_seed
);
2523 arg_random_seed_size
= 0;
2526 arg_default_oom_score_adjust_set
= false;
2527 arg_default_smack_process_label
= mfree(arg_default_smack_process_label
);
2529 arg_reload_limit_interval_sec
= 0;
2530 arg_reload_limit_burst
= 0;
2533 static void determine_default_oom_score_adjust(void) {
2536 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2537 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2540 if (arg_default_oom_score_adjust_set
)
2546 r
= get_oom_score_adjust(&a
);
2548 return (void) log_warning_errno(r
, "Failed to determine current OOM score adjustment value, ignoring: %m");
2550 assert_cc(100 <= OOM_SCORE_ADJ_MAX
);
2551 b
= a
>= OOM_SCORE_ADJ_MAX
- 100 ? OOM_SCORE_ADJ_MAX
: a
+ 100;
2556 arg_default_oom_score_adjust
= b
;
2557 arg_default_oom_score_adjust_set
= true;
2560 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
2561 const struct rlimit
*saved_rlimit_memlock
) {
2564 assert(saved_rlimit_nofile
);
2565 assert(saved_rlimit_memlock
);
2567 /* Assign configuration defaults */
2570 r
= parse_config_file();
2572 log_warning_errno(r
, "Failed to parse config file, ignoring: %m");
2574 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2575 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
2577 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2580 /* Initialize some default rlimits for services if they haven't been configured */
2581 fallback_rlimit_nofile(saved_rlimit_nofile
);
2582 fallback_rlimit_memlock(saved_rlimit_memlock
);
2584 /* Note that this also parses bits from the kernel command line, including "debug". */
2585 log_parse_environment();
2587 /* Initialize the show status setting if it hasn't been set explicitly yet */
2588 if (arg_show_status
== _SHOW_STATUS_INVALID
)
2589 arg_show_status
= SHOW_STATUS_YES
;
2591 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2592 determine_default_oom_score_adjust();
2594 /* Push variables into the manager environment block */
2595 setenv_manager_environment();
2597 /* Parse log environment variables again to take into account any new environment variables. */
2598 log_parse_environment();
2603 static int safety_checks(void) {
2605 if (getpid_cached() == 1 &&
2606 arg_action
!= ACTION_RUN
)
2607 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2608 "Unsupported execution mode while PID 1.");
2610 if (getpid_cached() == 1 &&
2611 arg_runtime_scope
== RUNTIME_SCOPE_USER
)
2612 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2613 "Can't run --user mode as PID 1.");
2615 if (arg_action
== ACTION_RUN
&&
2616 arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
&&
2617 getpid_cached() != 1)
2618 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2619 "Can't run system mode unless PID 1.");
2621 if (arg_action
== ACTION_TEST
&&
2623 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2624 "Don't run test mode as root.");
2626 switch (arg_runtime_scope
) {
2628 case RUNTIME_SCOPE_USER
:
2630 if (arg_action
== ACTION_RUN
&&
2632 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2633 "Trying to run as user instance, but the system has not been booted with systemd.");
2635 if (arg_action
== ACTION_RUN
&&
2636 !getenv("XDG_RUNTIME_DIR"))
2637 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH
),
2638 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2642 case RUNTIME_SCOPE_SYSTEM
:
2643 if (arg_action
== ACTION_RUN
&&
2644 running_in_chroot() > 0)
2645 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2646 "Cannot be run in a chroot() environment.");
2650 assert_not_reached();
2656 static int initialize_security(
2657 bool *loaded_policy
,
2658 dual_timestamp
*security_start_timestamp
,
2659 dual_timestamp
*security_finish_timestamp
,
2660 const char **ret_error_message
) {
2664 assert(loaded_policy
);
2665 assert(security_start_timestamp
);
2666 assert(security_finish_timestamp
);
2667 assert(ret_error_message
);
2669 dual_timestamp_get(security_start_timestamp
);
2671 r
= mac_selinux_setup(loaded_policy
);
2673 *ret_error_message
= "Failed to load SELinux policy";
2677 r
= mac_smack_setup(loaded_policy
);
2679 *ret_error_message
= "Failed to load SMACK policy";
2683 r
= mac_apparmor_setup();
2685 *ret_error_message
= "Failed to load AppArmor policy";
2691 *ret_error_message
= "Failed to load IMA policy";
2695 dual_timestamp_get(security_finish_timestamp
);
2699 static int collect_fds(FDSet
**ret_fds
, const char **ret_error_message
) {
2703 assert(ret_error_message
);
2705 r
= fdset_new_fill(ret_fds
);
2707 *ret_error_message
= "Failed to allocate fd set";
2708 return log_emergency_errno(r
, "Failed to allocate fd set: %m");
2711 fdset_cloexec(*ret_fds
, true);
2713 if (arg_serialization
)
2714 assert_se(fdset_remove(*ret_fds
, fileno(arg_serialization
)) >= 0);
2719 static void setup_console_terminal(bool skip_setup
) {
2721 if (arg_runtime_scope
!= RUNTIME_SCOPE_SYSTEM
)
2724 /* Become a session leader if we aren't one yet. */
2727 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2728 * controlling tty. */
2729 (void) release_terminal();
2731 /* Reset the console, but only if this is really init and we are freshly booted */
2732 if (getpid_cached() == 1 && !skip_setup
)
2733 (void) console_setup();
2736 static bool early_skip_setup_check(int argc
, char *argv
[]) {
2737 bool found_deserialize
= false;
2739 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2740 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2741 * special setup things anyway, even if in that case we also do deserialization. */
2743 for (int i
= 1; i
< argc
; i
++)
2744 if (streq(argv
[i
], "--switched-root"))
2745 return false; /* If we switched root, don't skip the setup. */
2746 else if (streq(argv
[i
], "--deserialize"))
2747 found_deserialize
= true;
2749 return found_deserialize
; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2752 static int save_env(void) {
2755 l
= strv_copy(environ
);
2759 strv_free_and_replace(saved_env
, l
);
2763 int main(int argc
, char *argv
[]) {
2765 initrd_timestamp
= DUAL_TIMESTAMP_NULL
,
2766 userspace_timestamp
= DUAL_TIMESTAMP_NULL
,
2767 kernel_timestamp
= DUAL_TIMESTAMP_NULL
,
2768 security_start_timestamp
= DUAL_TIMESTAMP_NULL
,
2769 security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
2770 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0),
2771 saved_rlimit_memlock
= RLIMIT_MAKE_CONST(RLIM_INFINITY
); /* The original rlimits we passed
2772 * in. Note we use different values
2773 * for the two that indicate whether
2774 * these fields are initialized! */
2775 bool skip_setup
, loaded_policy
= false, queue_default_job
= false, first_boot
= false;
2776 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
2777 usec_t before_startup
, after_startup
;
2778 static char systemd
[] = "systemd";
2779 const char *error_message
= NULL
;
2780 int r
, retval
= EXIT_FAILURE
;
2784 assert_se(argc
> 0 && !isempty(argv
[0]));
2786 /* SysV compatibility: redirect init → telinit */
2787 redirect_telinit(argc
, argv
);
2789 /* Take timestamps early on */
2790 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
2791 dual_timestamp_get(&userspace_timestamp
);
2793 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2795 skip_setup
= early_skip_setup_check(argc
, argv
);
2797 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2798 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2800 program_invocation_short_name
= systemd
;
2801 (void) prctl(PR_SET_NAME
, systemd
);
2803 /* Save the original command line */
2804 save_argc_argv(argc
, argv
);
2806 /* Save the original environment as we might need to restore it if we're requested to execute another
2807 * system manager later. */
2810 error_message
= "Failed to copy environment block";
2814 /* Make sure that if the user says "syslog" we actually log to the journal. */
2815 log_set_upgrade_syslog_to_journal(true);
2817 if (getpid_cached() == 1) {
2818 /* When we run as PID 1 force system mode */
2819 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
2821 /* Disable the umask logic */
2824 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2825 * not be activated yet (even though the log socket for it exists). */
2826 log_set_prohibit_ipc(true);
2828 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
2829 * is important so that we never end up logging to any foreign stderr, for example if we have
2830 * to log in a child process right before execve()'ing the actual binary, at a point in time
2831 * where socket activation stderr/stdout area already set up. */
2832 log_set_always_reopen_console(true);
2834 if (detect_container() <= 0) {
2836 /* Running outside of a container as PID 1 */
2837 log_set_target_and_open(LOG_TARGET_KMSG
);
2840 initrd_timestamp
= userspace_timestamp
;
2843 r
= mount_setup_early();
2845 error_message
= "Failed to mount early API filesystems";
2849 /* Let's open the log backend a second time, in case the first time didn't
2850 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2851 * available, and it previously wasn't. */
2854 disable_printk_ratelimit();
2856 r
= initialize_security(
2858 &security_start_timestamp
,
2859 &security_finish_timestamp
,
2865 if (mac_selinux_init() < 0) {
2866 error_message
= "Failed to initialize SELinux support";
2873 /* Set the default for later on, but don't actually open the logs like this for
2874 * now. Note that if we are transitioning from the initrd there might still be
2875 * journal fd open, and we shouldn't attempt opening that before we parsed
2876 * /proc/cmdline which might redirect output elsewhere. */
2877 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
2880 /* Running inside a container, as PID 1 */
2881 log_set_target_and_open(LOG_TARGET_CONSOLE
);
2883 /* For later on, see above... */
2884 log_set_target(LOG_TARGET_JOURNAL
);
2886 /* clear the kernel timestamp, because we are in a container */
2887 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2890 initialize_coredump(skip_setup
);
2892 r
= fixup_environment();
2894 log_emergency_errno(r
, "Failed to fix up PID 1 environment: %m");
2895 error_message
= "Failed to fix up PID1 environment";
2899 /* Try to figure out if we can use colors with the console. No need to do that for user
2900 * instances since they never log into the console. */
2901 log_show_color(colors_enabled());
2903 r
= make_null_stdio();
2905 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2907 /* Load the kernel modules early. */
2909 (void) kmod_setup();
2911 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
2912 r
= mount_setup(loaded_policy
, skip_setup
);
2914 error_message
= "Failed to mount API filesystems";
2918 /* The efivarfs is now mounted, let's lock down the system token. */
2919 lock_down_efi_variables();
2921 /* Cache command-line options passed from EFI variables */
2923 (void) cache_efi_options_variable();
2925 /* Running as user instance */
2926 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
2927 log_set_always_reopen_console(true);
2928 log_set_target_and_open(LOG_TARGET_AUTO
);
2930 /* clear the kernel timestamp, because we are not PID 1 */
2931 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2933 /* Clear ambient capabilities, so services do not inherit them implicitly. Dropping them does
2934 * not affect the permitted and effective sets which are important for the manager itself to
2936 capability_ambient_set_apply(0, /* also_inherit= */ false);
2938 if (mac_selinux_init() < 0) {
2939 error_message
= "Failed to initialize SELinux support";
2944 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2945 * transitioning from the initrd to the main systemd or suchlike. */
2946 save_rlimits(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2948 /* Reset all signal handlers. */
2949 (void) reset_all_signal_handlers();
2950 (void) ignore_signals(SIGNALS_IGNORE
);
2952 (void) parse_configuration(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2954 r
= parse_argv(argc
, argv
);
2956 error_message
= "Failed to parse commandline arguments";
2960 r
= safety_checks();
2964 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
, ACTION_DUMP_CONFIGURATION_ITEMS
, ACTION_DUMP_BUS_PROPERTIES
, ACTION_BUS_INTROSPECT
))
2965 pager_open(arg_pager_flags
);
2967 if (arg_action
!= ACTION_RUN
)
2970 if (arg_action
== ACTION_HELP
) {
2971 retval
= help() < 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2973 } else if (arg_action
== ACTION_VERSION
) {
2976 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
2977 unit_dump_config_items(stdout
);
2978 retval
= EXIT_SUCCESS
;
2980 } else if (arg_action
== ACTION_DUMP_BUS_PROPERTIES
) {
2981 dump_bus_properties(stdout
);
2982 retval
= EXIT_SUCCESS
;
2984 } else if (arg_action
== ACTION_BUS_INTROSPECT
) {
2985 r
= bus_manager_introspect_implementations(stdout
, arg_bus_introspect
);
2986 retval
= r
>= 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
2990 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
2992 /* Move out of the way, so that we won't block unmounts */
2993 assert_se(chdir("/") == 0);
2995 if (arg_action
== ACTION_RUN
) {
2997 /* Apply the systemd.clock_usec= kernel command line switch */
2998 apply_clock_update();
3000 /* Apply random seed from kernel command line */
3001 cmdline_take_random_seed();
3004 /* A core pattern might have been specified via the cmdline. */
3005 initialize_core_pattern(skip_setup
);
3007 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
3010 /* Remember open file descriptors for later deserialization */
3011 r
= collect_fds(&fds
, &error_message
);
3015 /* Give up any control of the console, but make sure its initialized. */
3016 setup_console_terminal(skip_setup
);
3018 /* Open the logging devices, if possible and necessary */
3022 log_execution_mode(&first_boot
);
3024 r
= initialize_runtime(skip_setup
,
3026 &saved_rlimit_nofile
,
3027 &saved_rlimit_memlock
,
3032 r
= manager_new(arg_runtime_scope
,
3033 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
3036 log_emergency_errno(r
, "Failed to allocate manager object: %m");
3037 error_message
= "Failed to allocate manager object";
3041 m
->timestamps
[MANAGER_TIMESTAMP_KERNEL
] = kernel_timestamp
;
3042 m
->timestamps
[MANAGER_TIMESTAMP_INITRD
] = initrd_timestamp
;
3043 m
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
] = userspace_timestamp
;
3044 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START
)] = security_start_timestamp
;
3045 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH
)] = security_finish_timestamp
;
3047 set_manager_defaults(m
);
3048 set_manager_settings(m
);
3049 manager_set_first_boot(m
, first_boot
);
3050 manager_set_switching_root(m
, arg_switched_root
);
3052 /* Remember whether we should queue the default job */
3053 queue_default_job
= !arg_serialization
|| arg_switched_root
;
3055 before_startup
= now(CLOCK_MONOTONIC
);
3057 r
= manager_startup(m
, arg_serialization
, fds
, /* root= */ NULL
);
3059 error_message
= "Failed to start up manager";
3063 /* This will close all file descriptors that were opened, but not claimed by any unit. */
3064 fds
= fdset_free(fds
);
3065 arg_serialization
= safe_fclose(arg_serialization
);
3067 if (queue_default_job
) {
3068 r
= do_queue_default_job(m
, &error_message
);
3073 after_startup
= now(CLOCK_MONOTONIC
);
3075 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
3076 "Loaded units and determined initial transaction in %s.",
3077 FORMAT_TIMESPAN(after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
3079 if (arg_action
== ACTION_TEST
) {
3080 manager_test_summary(m
);
3081 retval
= EXIT_SUCCESS
;
3085 r
= invoke_main_loop(m
,
3086 &saved_rlimit_nofile
,
3087 &saved_rlimit_memlock
,
3093 assert(r
< 0 || IN_SET(r
, MANAGER_EXIT
, /* MANAGER_OK is not expected here. */
3100 MANAGER_SWITCH_ROOT
));
3106 arg_reboot_watchdog
= manager_get_watchdog(m
, WATCHDOG_REBOOT
);
3107 arg_kexec_watchdog
= manager_get_watchdog(m
, WATCHDOG_KEXEC
);
3108 m
= manager_free(m
);
3111 mac_selinux_finish();
3113 if (IN_SET(r
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
))
3116 &saved_rlimit_nofile
,
3117 &saved_rlimit_memlock
,
3121 &error_message
); /* This only returns if reexecution failed */
3123 arg_serialization
= safe_fclose(arg_serialization
);
3124 fds
= fdset_free(fds
);
3126 saved_env
= strv_free(saved_env
);
3128 #if HAVE_VALGRIND_VALGRIND_H
3129 /* If we are PID 1 and running under valgrind, then let's exit
3130 * here explicitly. valgrind will only generate nice output on
3131 * exit(), not on exec(), hence let's do the former not the
3133 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
3134 /* Cleanup watchdog_device strings for valgrind. We need them
3135 * in become_shutdown() so normally we cannot free them yet. */
3136 watchdog_free_device();
3142 #if HAS_FEATURE_ADDRESS_SANITIZER
3143 __lsan_do_leak_check();
3146 /* Try to invoke the shutdown binary unless we already failed.
3147 * If we failed above, we want to freeze after finishing cleanup. */
3148 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
&&
3149 IN_SET(r
, MANAGER_EXIT
, MANAGER_REBOOT
, MANAGER_POWEROFF
, MANAGER_HALT
, MANAGER_KEXEC
)) {
3150 r
= become_shutdown(r
, retval
);
3151 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3152 error_message
= "Failed to execute shutdown binary";
3155 watchdog_free_device();
3156 arg_watchdog_device
= mfree(arg_watchdog_device
);
3158 if (getpid_cached() == 1) {
3160 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
3161 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
3162 "%s.", error_message
);
3163 freeze_or_exit_or_reboot();