1 /* SPDX-License-Identifier: LGPL-2.1+ */
8 #include <sys/reboot.h>
13 #if HAVE_VALGRIND_VALGRIND_H
14 #include <valgrind/valgrind.h>
18 #include "sd-daemon.h"
19 #include "sd-messages.h"
21 #include "alloc-util.h"
22 #include "architecture.h"
24 #include "bus-error.h"
26 #include "capability-util.h"
27 #include "cgroup-util.h"
28 #include "clock-util.h"
29 #include "conf-parser.h"
30 #include "cpu-set-util.h"
31 #include "dbus-manager.h"
34 #include "efi-random.h"
35 #include "emergency-action.h"
37 #include "exit-status.h"
41 #include "format-util.h"
43 #include "hostname-setup.h"
44 #include "ima-setup.h"
46 #include "kmod-setup.h"
47 #include "limits-util.h"
48 #include "load-fragment.h"
50 #include "loopback-setup.h"
51 #include "machine-id-setup.h"
53 #include "mount-setup.h"
56 #include "parse-util.h"
57 #include "path-util.h"
58 #include "pretty-print.h"
59 #include "proc-cmdline.h"
60 #include "process-util.h"
61 #include "raw-clone.h"
62 #include "rlimit-util.h"
64 #include "seccomp-util.h"
66 #include "selinux-setup.h"
67 #include "selinux-util.h"
68 #include "signal-util.h"
69 #include "smack-setup.h"
71 #include "stat-util.h"
72 #include "stdio-util.h"
74 #include "switch-root.h"
75 #include "sysctl-util.h"
76 #include "terminal-util.h"
77 #include "umask-util.h"
78 #include "user-util.h"
83 #if HAS_FEATURE_ADDRESS_SANITIZER
84 #include <sanitizer/lsan_interface.h>
87 #define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
94 ACTION_DUMP_CONFIGURATION_ITEMS
,
95 ACTION_DUMP_BUS_PROPERTIES
,
96 } arg_action
= ACTION_RUN
;
98 /* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access.
99 * Real defaults are assigned in reset_arguments() below. */
100 static char *arg_default_unit
;
101 static bool arg_system
;
102 static bool arg_dump_core
;
103 static int arg_crash_chvt
;
104 static bool arg_crash_shell
;
105 static bool arg_crash_reboot
;
106 static char *arg_confirm_spawn
;
107 static ShowStatus arg_show_status
;
108 static StatusUnitFormat arg_status_unit_format
;
109 static bool arg_switched_root
;
110 static PagerFlags arg_pager_flags
;
111 static bool arg_service_watchdogs
;
112 static ExecOutput arg_default_std_output
;
113 static ExecOutput arg_default_std_error
;
114 static usec_t arg_default_restart_usec
;
115 static usec_t arg_default_timeout_start_usec
;
116 static usec_t arg_default_timeout_stop_usec
;
117 static usec_t arg_default_timeout_abort_usec
;
118 static bool arg_default_timeout_abort_set
;
119 static usec_t arg_default_start_limit_interval
;
120 static unsigned arg_default_start_limit_burst
;
121 static usec_t arg_runtime_watchdog
;
122 static usec_t arg_reboot_watchdog
;
123 static usec_t arg_kexec_watchdog
;
124 static char *arg_early_core_pattern
;
125 static char *arg_watchdog_device
;
126 static char **arg_default_environment
;
127 static struct rlimit
*arg_default_rlimit
[_RLIMIT_MAX
];
128 static uint64_t arg_capability_bounding_set
;
129 static bool arg_no_new_privs
;
130 static nsec_t arg_timer_slack_nsec
;
131 static usec_t arg_default_timer_accuracy_usec
;
132 static Set
* arg_syscall_archs
;
133 static FILE* arg_serialization
;
134 static int arg_default_cpu_accounting
;
135 static bool arg_default_io_accounting
;
136 static bool arg_default_ip_accounting
;
137 static bool arg_default_blockio_accounting
;
138 static bool arg_default_memory_accounting
;
139 static bool arg_default_tasks_accounting
;
140 static TasksMax arg_default_tasks_max
;
141 static sd_id128_t arg_machine_id
;
142 static EmergencyAction arg_cad_burst_action
;
143 static OOMPolicy arg_default_oom_policy
;
144 static CPUSet arg_cpu_affinity
;
145 static NUMAPolicy arg_numa_policy
;
147 /* A copy of the original environment block */
148 static char **saved_env
= NULL
;
150 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
151 const struct rlimit
*saved_rlimit_memlock
);
153 _noreturn_
static void freeze_or_exit_or_reboot(void) {
155 /* If we are running in a container, let's prefer exiting, after all we can propagate an exit code to
156 * the container manager, and thus inform it that something went wrong. */
157 if (detect_container() > 0) {
158 log_emergency("Exiting PID 1...");
159 _exit(EXIT_EXCEPTION
);
162 if (arg_crash_reboot
) {
163 log_notice("Rebooting in 10s...");
166 log_notice("Rebooting now...");
167 (void) reboot(RB_AUTOBOOT
);
168 log_emergency_errno(errno
, "Failed to reboot: %m");
171 log_emergency("Freezing execution.");
175 _noreturn_
static void crash(int sig
) {
179 if (getpid_cached() != 1)
180 /* Pass this on immediately, if this is not PID 1 */
182 else if (!arg_dump_core
)
183 log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig
));
185 sa
= (struct sigaction
) {
186 .sa_handler
= nop_signal_handler
,
187 .sa_flags
= SA_NOCLDSTOP
|SA_RESTART
,
190 /* We want to wait for the core process, hence let's enable SIGCHLD */
191 (void) sigaction(SIGCHLD
, &sa
, NULL
);
193 pid
= raw_clone(SIGCHLD
);
195 log_emergency_errno(errno
, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig
));
197 /* Enable default signal handler for core dump */
199 sa
= (struct sigaction
) {
200 .sa_handler
= SIG_DFL
,
202 (void) sigaction(sig
, &sa
, NULL
);
204 /* Don't limit the coredump size */
205 (void) setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
));
207 /* Just to be sure... */
210 /* Raise the signal again */
212 (void) kill(pid
, sig
); /* raise() would kill the parent */
214 assert_not_reached("We shouldn't be here...");
215 _exit(EXIT_EXCEPTION
);
220 /* Order things nicely. */
221 r
= wait_for_terminate(pid
, &status
);
223 log_emergency_errno(r
, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig
));
224 else if (status
.si_code
!= CLD_DUMPED
) {
225 const char *s
= status
.si_code
== CLD_EXITED
226 ? exit_status_to_string(status
.si_status
, EXIT_STATUS_LIBC
)
227 : signal_to_string(status
.si_status
);
229 log_emergency("Caught <%s>, core dump failed (child "PID_FMT
", code=%s, status=%i/%s).",
230 signal_to_string(sig
),
232 sigchld_code_to_string(status
.si_code
),
233 status
.si_status
, strna(s
));
235 log_emergency("Caught <%s>, dumped core as pid "PID_FMT
".",
236 signal_to_string(sig
), pid
);
240 if (arg_crash_chvt
>= 0)
241 (void) chvt(arg_crash_chvt
);
243 sa
= (struct sigaction
) {
244 .sa_handler
= SIG_IGN
,
245 .sa_flags
= SA_NOCLDSTOP
|SA_NOCLDWAIT
|SA_RESTART
,
248 /* Let the kernel reap children for us */
249 (void) sigaction(SIGCHLD
, &sa
, NULL
);
251 if (arg_crash_shell
) {
252 log_notice("Executing crash shell in 10s...");
255 pid
= raw_clone(SIGCHLD
);
257 log_emergency_errno(errno
, "Failed to fork off crash shell: %m");
260 (void) make_console_stdio();
261 (void) rlimit_nofile_safe();
262 (void) execle("/bin/sh", "/bin/sh", NULL
, environ
);
264 log_emergency_errno(errno
, "execle() failed: %m");
265 _exit(EXIT_EXCEPTION
);
267 log_info("Spawned crash shell as PID "PID_FMT
".", pid
);
268 (void) wait_for_terminate(pid
, NULL
);
272 freeze_or_exit_or_reboot();
275 static void install_crash_handler(void) {
276 static const struct sigaction sa
= {
278 .sa_flags
= SA_NODEFER
, /* So that we can raise the signal again from the signal handler */
282 /* We ignore the return value here, since, we don't mind if we
283 * cannot set up a crash handler */
284 r
= sigaction_many(&sa
, SIGNALS_CRASH_HANDLER
, -1);
286 log_debug_errno(r
, "I had trouble setting up the crash handler, ignoring: %m");
289 static int console_setup(void) {
290 _cleanup_close_
int tty_fd
= -1;
293 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
295 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
297 /* We don't want to force text mode. plymouth may be showing
298 * pictures already from initrd. */
299 r
= reset_terminal_fd(tty_fd
, false);
301 return log_error_errno(r
, "Failed to reset /dev/console: %m");
306 static int set_machine_id(const char *m
) {
310 if (sd_id128_from_string(m
, &t
) < 0)
313 if (sd_id128_is_null(t
))
320 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
325 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
327 if (proc_cmdline_value_missing(key
, value
))
330 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
331 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
332 else if (in_initrd() == !!startswith(key
, "rd."))
333 return free_and_strdup_warn(&arg_default_unit
, value
);
335 } else if (proc_cmdline_key_streq(key
, "systemd.dump_core")) {
337 r
= value
? parse_boolean(value
) : true;
339 log_warning_errno(r
, "Failed to parse dump core switch %s, ignoring: %m", value
);
343 } else if (proc_cmdline_key_streq(key
, "systemd.early_core_pattern")) {
345 if (proc_cmdline_value_missing(key
, value
))
348 if (path_is_absolute(value
))
349 (void) parse_path_argument_and_warn(value
, false, &arg_early_core_pattern
);
351 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value
);
353 } else if (proc_cmdline_key_streq(key
, "systemd.crash_chvt")) {
356 arg_crash_chvt
= 0; /* turn on */
358 r
= parse_crash_chvt(value
, &arg_crash_chvt
);
360 log_warning_errno(r
, "Failed to parse crash chvt switch %s, ignoring: %m", value
);
363 } else if (proc_cmdline_key_streq(key
, "systemd.crash_shell")) {
365 r
= value
? parse_boolean(value
) : true;
367 log_warning_errno(r
, "Failed to parse crash shell switch %s, ignoring: %m", value
);
371 } else if (proc_cmdline_key_streq(key
, "systemd.crash_reboot")) {
373 r
= value
? parse_boolean(value
) : true;
375 log_warning_errno(r
, "Failed to parse crash reboot switch %s, ignoring: %m", value
);
377 arg_crash_reboot
= r
;
379 } else if (proc_cmdline_key_streq(key
, "systemd.confirm_spawn")) {
382 r
= parse_confirm_spawn(value
, &s
);
384 log_warning_errno(r
, "Failed to parse confirm_spawn switch %s, ignoring: %m", value
);
386 free_and_replace(arg_confirm_spawn
, s
);
388 } else if (proc_cmdline_key_streq(key
, "systemd.service_watchdogs")) {
390 r
= value
? parse_boolean(value
) : true;
392 log_warning_errno(r
, "Failed to parse service watchdog switch %s, ignoring: %m", value
);
394 arg_service_watchdogs
= r
;
396 } else if (proc_cmdline_key_streq(key
, "systemd.show_status")) {
399 r
= parse_show_status(value
, &arg_show_status
);
401 log_warning_errno(r
, "Failed to parse show status switch %s, ignoring: %m", value
);
403 arg_show_status
= SHOW_STATUS_YES
;
405 } else if (proc_cmdline_key_streq(key
, "systemd.status_unit_format")) {
407 if (proc_cmdline_value_missing(key
, value
))
410 r
= status_unit_format_from_string(value
);
412 log_warning_errno(r
, "Failed to parse %s=%s, ignoring: %m", key
, value
);
414 arg_status_unit_format
= r
;
416 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_output")) {
418 if (proc_cmdline_value_missing(key
, value
))
421 r
= exec_output_from_string(value
);
423 log_warning_errno(r
, "Failed to parse default standard output switch %s, ignoring: %m", value
);
425 arg_default_std_output
= r
;
427 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_error")) {
429 if (proc_cmdline_value_missing(key
, value
))
432 r
= exec_output_from_string(value
);
434 log_warning_errno(r
, "Failed to parse default standard error switch %s, ignoring: %m", value
);
436 arg_default_std_error
= r
;
438 } else if (streq(key
, "systemd.setenv")) {
440 if (proc_cmdline_value_missing(key
, value
))
443 if (env_assignment_is_valid(value
)) {
446 env
= strv_env_set(arg_default_environment
, value
);
450 arg_default_environment
= env
;
452 log_warning("Environment variable name '%s' is not valid. Ignoring.", value
);
454 } else if (proc_cmdline_key_streq(key
, "systemd.machine_id")) {
456 if (proc_cmdline_value_missing(key
, value
))
459 r
= set_machine_id(value
);
461 log_warning_errno(r
, "MachineID '%s' is not valid, ignoring: %m", value
);
463 } else if (proc_cmdline_key_streq(key
, "systemd.default_timeout_start_sec")) {
465 if (proc_cmdline_value_missing(key
, value
))
468 r
= parse_sec(value
, &arg_default_timeout_start_usec
);
470 log_warning_errno(r
, "Failed to parse default start timeout '%s', ignoring: %m", value
);
472 if (arg_default_timeout_start_usec
<= 0)
473 arg_default_timeout_start_usec
= USEC_INFINITY
;
475 } else if (proc_cmdline_key_streq(key
, "systemd.cpu_affinity")) {
477 if (proc_cmdline_value_missing(key
, value
))
480 r
= parse_cpu_set(value
, &arg_cpu_affinity
);
482 log_warning_errno(r
, "Failed to parse CPU affinity mask '%s', ignoring: %m", value
);
484 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_device")) {
486 if (proc_cmdline_value_missing(key
, value
))
489 (void) parse_path_argument_and_warn(value
, false, &arg_watchdog_device
);
491 } else if (streq(key
, "quiet") && !value
) {
493 if (arg_show_status
== _SHOW_STATUS_INVALID
)
494 arg_show_status
= SHOW_STATUS_ERROR
;
496 } else if (streq(key
, "debug") && !value
) {
498 /* Note that log_parse_environment() handles 'debug'
499 * too, and sets the log level to LOG_DEBUG. */
501 if (detect_container() > 0)
502 log_set_target(LOG_TARGET_CONSOLE
);
507 /* SysV compatibility */
508 target
= runlevel_to_target(key
);
510 return free_and_strdup_warn(&arg_default_unit
, target
);
516 #define DEFINE_SETTER(name, func, descr) \
517 static int name(const char *unit, \
518 const char *filename, \
520 const char *section, \
521 unsigned section_line, \
522 const char *lvalue, \
524 const char *rvalue, \
536 log_syntax(unit, LOG_ERR, filename, line, r, \
537 "Invalid " descr "'%s': %m", \
543 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level");
544 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target");
545 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color");
546 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location");
547 DEFINE_SETTER(config_parse_time
, log_show_time_from_string
, "time");
549 static int config_parse_default_timeout_abort(
551 const char *filename
,
554 unsigned section_line
,
562 r
= config_parse_timeout_abort(unit
, filename
, line
, section
, section_line
, lvalue
, ltype
, rvalue
,
563 &arg_default_timeout_abort_usec
, userdata
);
565 arg_default_timeout_abort_set
= r
;
569 static int parse_config_file(void) {
570 const ConfigTableItem items
[] = {
571 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
572 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
573 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
574 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
575 { "Manager", "LogTime", config_parse_time
, 0, NULL
},
576 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
577 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, &arg_crash_chvt
},
578 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, &arg_crash_chvt
},
579 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
580 { "Manager", "CrashReboot", config_parse_bool
, 0, &arg_crash_reboot
},
581 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
582 { "Manager", "StatusUnitFormat", config_parse_status_unit_format
, 0, &arg_status_unit_format
},
583 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, &arg_cpu_affinity
},
584 { "Manager", "NUMAPolicy", config_parse_numa_policy
, 0, &arg_numa_policy
.type
},
585 { "Manager", "NUMAMask", config_parse_numa_mask
, 0, &arg_numa_policy
},
586 { "Manager", "JoinControllers", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
587 { "Manager", "RuntimeWatchdogSec", config_parse_sec
, 0, &arg_runtime_watchdog
},
588 { "Manager", "RebootWatchdogSec", config_parse_sec
, 0, &arg_reboot_watchdog
},
589 { "Manager", "ShutdownWatchdogSec", config_parse_sec
, 0, &arg_reboot_watchdog
}, /* obsolete alias */
590 { "Manager", "KExecWatchdogSec", config_parse_sec
, 0, &arg_kexec_watchdog
},
591 { "Manager", "WatchdogDevice", config_parse_path
, 0, &arg_watchdog_device
},
592 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
593 { "Manager", "NoNewPrivileges", config_parse_bool
, 0, &arg_no_new_privs
},
595 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
597 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
598 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_default_timer_accuracy_usec
},
599 { "Manager", "DefaultStandardOutput", config_parse_output_restricted
, 0, &arg_default_std_output
},
600 { "Manager", "DefaultStandardError", config_parse_output_restricted
, 0, &arg_default_std_error
},
601 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_default_timeout_start_usec
},
602 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_default_timeout_stop_usec
},
603 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort
, 0, NULL
},
604 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_default_restart_usec
},
605 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_default_start_limit_interval
}, /* obsolete alias */
606 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec
, 0, &arg_default_start_limit_interval
},
607 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_default_start_limit_burst
},
608 { "Manager", "DefaultEnvironment", config_parse_environ
, 0, &arg_default_environment
},
609 { "Manager", "DefaultLimitCPU", config_parse_rlimit
, RLIMIT_CPU
, arg_default_rlimit
},
610 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit
, RLIMIT_FSIZE
, arg_default_rlimit
},
611 { "Manager", "DefaultLimitDATA", config_parse_rlimit
, RLIMIT_DATA
, arg_default_rlimit
},
612 { "Manager", "DefaultLimitSTACK", config_parse_rlimit
, RLIMIT_STACK
, arg_default_rlimit
},
613 { "Manager", "DefaultLimitCORE", config_parse_rlimit
, RLIMIT_CORE
, arg_default_rlimit
},
614 { "Manager", "DefaultLimitRSS", config_parse_rlimit
, RLIMIT_RSS
, arg_default_rlimit
},
615 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit
, RLIMIT_NOFILE
, arg_default_rlimit
},
616 { "Manager", "DefaultLimitAS", config_parse_rlimit
, RLIMIT_AS
, arg_default_rlimit
},
617 { "Manager", "DefaultLimitNPROC", config_parse_rlimit
, RLIMIT_NPROC
, arg_default_rlimit
},
618 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit
, RLIMIT_MEMLOCK
, arg_default_rlimit
},
619 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit
, RLIMIT_LOCKS
, arg_default_rlimit
},
620 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit
, RLIMIT_SIGPENDING
, arg_default_rlimit
},
621 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit
, RLIMIT_MSGQUEUE
, arg_default_rlimit
},
622 { "Manager", "DefaultLimitNICE", config_parse_rlimit
, RLIMIT_NICE
, arg_default_rlimit
},
623 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit
, RLIMIT_RTPRIO
, arg_default_rlimit
},
624 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit
, RLIMIT_RTTIME
, arg_default_rlimit
},
625 { "Manager", "DefaultCPUAccounting", config_parse_tristate
, 0, &arg_default_cpu_accounting
},
626 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_default_io_accounting
},
627 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_default_ip_accounting
},
628 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_default_blockio_accounting
},
629 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_default_memory_accounting
},
630 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_default_tasks_accounting
},
631 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_default_tasks_max
},
632 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, 0, &arg_cad_burst_action
},
633 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy
, 0, &arg_default_oom_policy
},
637 const char *fn
, *conf_dirs_nulstr
;
640 PKGSYSCONFDIR
"/system.conf" :
641 PKGSYSCONFDIR
"/user.conf";
643 conf_dirs_nulstr
= arg_system
?
644 CONF_PATHS_NULSTR("systemd/system.conf.d") :
645 CONF_PATHS_NULSTR("systemd/user.conf.d");
647 (void) config_parse_many_nulstr(fn
, conf_dirs_nulstr
, "Manager\0", config_item_table_lookup
, items
, CONFIG_PARSE_WARN
, NULL
);
649 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we used USEC_INFINITY
650 * like everywhere else. */
651 if (arg_default_timeout_start_usec
<= 0)
652 arg_default_timeout_start_usec
= USEC_INFINITY
;
653 if (arg_default_timeout_stop_usec
<= 0)
654 arg_default_timeout_stop_usec
= USEC_INFINITY
;
659 static void set_manager_defaults(Manager
*m
) {
663 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
664 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
665 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
667 m
->default_timer_accuracy_usec
= arg_default_timer_accuracy_usec
;
668 m
->default_std_output
= arg_default_std_output
;
669 m
->default_std_error
= arg_default_std_error
;
670 m
->default_timeout_start_usec
= arg_default_timeout_start_usec
;
671 m
->default_timeout_stop_usec
= arg_default_timeout_stop_usec
;
672 m
->default_timeout_abort_usec
= arg_default_timeout_abort_usec
;
673 m
->default_timeout_abort_set
= arg_default_timeout_abort_set
;
674 m
->default_restart_usec
= arg_default_restart_usec
;
675 m
->default_start_limit_interval
= arg_default_start_limit_interval
;
676 m
->default_start_limit_burst
= arg_default_start_limit_burst
;
678 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
679 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
680 if (arg_default_cpu_accounting
>= 0)
681 m
->default_cpu_accounting
= arg_default_cpu_accounting
;
683 m
->default_cpu_accounting
= cpu_accounting_is_cheap();
685 m
->default_io_accounting
= arg_default_io_accounting
;
686 m
->default_ip_accounting
= arg_default_ip_accounting
;
687 m
->default_blockio_accounting
= arg_default_blockio_accounting
;
688 m
->default_memory_accounting
= arg_default_memory_accounting
;
689 m
->default_tasks_accounting
= arg_default_tasks_accounting
;
690 m
->default_tasks_max
= arg_default_tasks_max
;
691 m
->default_oom_policy
= arg_default_oom_policy
;
693 (void) manager_set_default_rlimits(m
, arg_default_rlimit
);
695 (void) manager_default_environment(m
);
696 (void) manager_transient_environment_add(m
, arg_default_environment
);
699 static void set_manager_settings(Manager
*m
) {
703 /* Propagates the various manager settings into the manager object, i.e. properties that effect the manager
704 * itself (as opposed to just being inherited into newly allocated units, see set_manager_defaults() above). */
706 m
->confirm_spawn
= arg_confirm_spawn
;
707 m
->service_watchdogs
= arg_service_watchdogs
;
708 m
->runtime_watchdog
= arg_runtime_watchdog
;
709 m
->reboot_watchdog
= arg_reboot_watchdog
;
710 m
->kexec_watchdog
= arg_kexec_watchdog
;
711 m
->cad_burst_action
= arg_cad_burst_action
;
713 manager_set_show_status(m
, arg_show_status
, "commandline");
714 m
->status_unit_format
= arg_status_unit_format
;
717 static int parse_argv(int argc
, char *argv
[]) {
719 ARG_LOG_LEVEL
= 0x100,
730 ARG_DUMP_CONFIGURATION_ITEMS
,
731 ARG_DUMP_BUS_PROPERTIES
,
740 ARG_DEFAULT_STD_OUTPUT
,
741 ARG_DEFAULT_STD_ERROR
,
743 ARG_SERVICE_WATCHDOGS
,
746 static const struct option options
[] = {
747 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
748 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
749 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
750 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
751 { "log-time", optional_argument
, NULL
, ARG_LOG_TIME
},
752 { "unit", required_argument
, NULL
, ARG_UNIT
},
753 { "system", no_argument
, NULL
, ARG_SYSTEM
},
754 { "user", no_argument
, NULL
, ARG_USER
},
755 { "test", no_argument
, NULL
, ARG_TEST
},
756 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
757 { "help", no_argument
, NULL
, 'h' },
758 { "version", no_argument
, NULL
, ARG_VERSION
},
759 { "dump-configuration-items", no_argument
, NULL
, ARG_DUMP_CONFIGURATION_ITEMS
},
760 { "dump-bus-properties", no_argument
, NULL
, ARG_DUMP_BUS_PROPERTIES
},
761 { "dump-core", optional_argument
, NULL
, ARG_DUMP_CORE
},
762 { "crash-chvt", required_argument
, NULL
, ARG_CRASH_CHVT
},
763 { "crash-shell", optional_argument
, NULL
, ARG_CRASH_SHELL
},
764 { "crash-reboot", optional_argument
, NULL
, ARG_CRASH_REBOOT
},
765 { "confirm-spawn", optional_argument
, NULL
, ARG_CONFIRM_SPAWN
},
766 { "show-status", optional_argument
, NULL
, ARG_SHOW_STATUS
},
767 { "deserialize", required_argument
, NULL
, ARG_DESERIALIZE
},
768 { "switched-root", no_argument
, NULL
, ARG_SWITCHED_ROOT
},
769 { "default-standard-output", required_argument
, NULL
, ARG_DEFAULT_STD_OUTPUT
, },
770 { "default-standard-error", required_argument
, NULL
, ARG_DEFAULT_STD_ERROR
, },
771 { "machine-id", required_argument
, NULL
, ARG_MACHINE_ID
},
772 { "service-watchdogs", required_argument
, NULL
, ARG_SERVICE_WATCHDOGS
},
781 if (getpid_cached() == 1)
784 while ((c
= getopt_long(argc
, argv
, "hDbsz:", options
, NULL
)) >= 0)
789 r
= log_set_max_level_from_string(optarg
);
791 return log_error_errno(r
, "Failed to parse log level \"%s\": %m", optarg
);
796 r
= log_set_target_from_string(optarg
);
798 return log_error_errno(r
, "Failed to parse log target \"%s\": %m", optarg
);
805 r
= log_show_color_from_string(optarg
);
807 return log_error_errno(r
, "Failed to parse log color setting \"%s\": %m",
810 log_show_color(true);
814 case ARG_LOG_LOCATION
:
816 r
= log_show_location_from_string(optarg
);
818 return log_error_errno(r
, "Failed to parse log location setting \"%s\": %m",
821 log_show_location(true);
828 r
= log_show_time_from_string(optarg
);
830 return log_error_errno(r
, "Failed to parse log time setting \"%s\": %m",
837 case ARG_DEFAULT_STD_OUTPUT
:
838 r
= exec_output_from_string(optarg
);
840 return log_error_errno(r
, "Failed to parse default standard output setting \"%s\": %m",
842 arg_default_std_output
= r
;
845 case ARG_DEFAULT_STD_ERROR
:
846 r
= exec_output_from_string(optarg
);
848 return log_error_errno(r
, "Failed to parse default standard error output setting \"%s\": %m",
850 arg_default_std_error
= r
;
854 r
= free_and_strdup(&arg_default_unit
, optarg
);
856 return log_error_errno(r
, "Failed to set default unit \"%s\": %m", optarg
);
869 arg_action
= ACTION_TEST
;
873 arg_pager_flags
|= PAGER_DISABLE
;
877 arg_action
= ACTION_VERSION
;
880 case ARG_DUMP_CONFIGURATION_ITEMS
:
881 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
884 case ARG_DUMP_BUS_PROPERTIES
:
885 arg_action
= ACTION_DUMP_BUS_PROPERTIES
;
890 arg_dump_core
= true;
892 r
= parse_boolean(optarg
);
894 return log_error_errno(r
, "Failed to parse dump core boolean: \"%s\": %m",
901 r
= parse_crash_chvt(optarg
, &arg_crash_chvt
);
903 return log_error_errno(r
, "Failed to parse crash virtual terminal index: \"%s\": %m",
907 case ARG_CRASH_SHELL
:
909 arg_crash_shell
= true;
911 r
= parse_boolean(optarg
);
913 return log_error_errno(r
, "Failed to parse crash shell boolean: \"%s\": %m",
919 case ARG_CRASH_REBOOT
:
921 arg_crash_reboot
= true;
923 r
= parse_boolean(optarg
);
925 return log_error_errno(r
, "Failed to parse crash shell boolean: \"%s\": %m",
927 arg_crash_reboot
= r
;
931 case ARG_CONFIRM_SPAWN
:
932 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
934 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
936 return log_error_errno(r
, "Failed to parse confirm spawn option: \"%s\": %m",
940 case ARG_SERVICE_WATCHDOGS
:
941 r
= parse_boolean(optarg
);
943 return log_error_errno(r
, "Failed to parse service watchdogs boolean: \"%s\": %m",
945 arg_service_watchdogs
= r
;
948 case ARG_SHOW_STATUS
:
950 r
= parse_show_status(optarg
, &arg_show_status
);
952 return log_error_errno(r
, "Failed to parse show status boolean: \"%s\": %m",
955 arg_show_status
= SHOW_STATUS_YES
;
958 case ARG_DESERIALIZE
: {
962 r
= safe_atoi(optarg
, &fd
);
964 log_error_errno(r
, "Failed to parse deserialize option \"%s\": %m", optarg
);
966 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
967 "Invalid deserialize fd: %d",
970 (void) fd_cloexec(fd
, true);
974 return log_error_errno(errno
, "Failed to open serialization fd %d: %m", fd
);
976 safe_fclose(arg_serialization
);
977 arg_serialization
= f
;
982 case ARG_SWITCHED_ROOT
:
983 arg_switched_root
= true;
987 r
= set_machine_id(optarg
);
989 return log_error_errno(r
, "MachineID '%s' is not valid: %m", optarg
);
993 arg_action
= ACTION_HELP
;
997 log_set_max_level(LOG_DEBUG
);
1003 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1004 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1007 if (getpid_cached() != 1)
1013 assert_not_reached("Unhandled option code.");
1016 if (optind
< argc
&& getpid_cached() != 1) {
1017 /* Hmm, when we aren't run as init system
1018 * let's complain about excess arguments */
1020 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1021 "Excess arguments.");
1027 static int help(void) {
1028 _cleanup_free_
char *link
= NULL
;
1031 r
= terminal_urlify_man("systemd", "1", &link
);
1035 printf("%s [OPTIONS...]\n\n"
1036 "Starts up and maintains the system or user services.\n\n"
1037 " -h --help Show this help\n"
1038 " --version Show version\n"
1039 " --test Determine initial transaction, dump it and exit\n"
1040 " --system In combination with --test: operate as system service manager\n"
1041 " --user In combination with --test: operate as per-user service manager\n"
1042 " --no-pager Do not pipe output into a pager\n"
1043 " --dump-configuration-items Dump understood unit configuration items\n"
1044 " --dump-bus-properties Dump exposed bus properties\n"
1045 " --unit=UNIT Set default unit\n"
1046 " --dump-core[=BOOL] Dump core on crash\n"
1047 " --crash-vt=NR Change to specified VT on crash\n"
1048 " --crash-reboot[=BOOL] Reboot on crash\n"
1049 " --crash-shell[=BOOL] Run shell on crash\n"
1050 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1051 " --show-status[=BOOL] Show status updates on the console during bootup\n"
1052 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
1053 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1054 " --log-color[=BOOL] Highlight important log messages\n"
1055 " --log-location[=BOOL] Include code location in log messages\n"
1056 " --log-time[=BOOL] Prefix log messages with current time\n"
1057 " --default-standard-output= Set default standard output for services\n"
1058 " --default-standard-error= Set default standard error output for services\n"
1059 "\nSee the %s for details.\n"
1060 , program_invocation_short_name
1067 static int prepare_reexecute(
1071 bool switching_root
) {
1073 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1074 _cleanup_fclose_
FILE *f
= NULL
;
1081 r
= manager_open_serialization(m
, &f
);
1083 return log_error_errno(r
, "Failed to create serialization file: %m");
1085 /* Make sure nothing is really destructed when we shut down */
1087 bus_manager_send_reloading(m
, true);
1093 r
= manager_serialize(m
, f
, fds
, switching_root
);
1097 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1098 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1100 r
= fd_cloexec(fileno(f
), false);
1102 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1104 r
= fdset_cloexec(fds
, false);
1106 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1108 *ret_f
= TAKE_PTR(f
);
1109 *ret_fds
= TAKE_PTR(fds
);
1114 static void bump_file_max_and_nr_open(void) {
1116 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large numbers of file
1117 * descriptors are no longer a performance problem and their memory is properly tracked by memcg, thus counting
1118 * them and limiting them in another two layers of limits is unnecessary and just complicates things. This
1119 * function hence turns off 2 of the 4 levels of limits on file descriptors, and makes RLIMIT_NOLIMIT (soft +
1120 * hard) the only ones that really matter. */
1122 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1126 #if BUMP_PROC_SYS_FS_FILE_MAX
1127 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously thing where
1128 * different but the operation would fail silently.) */
1129 r
= sysctl_writef("fs/file-max", "%li\n", LONG_MAX
);
1131 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.file-max, ignoring: %m");
1134 #if BUMP_PROC_SYS_FS_NR_OPEN
1137 /* Arg! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know what they
1138 * are. The expression by which the maximum is determined is dependent on the architecture, and is something we
1139 * don't really want to copy to userspace, as it is dependent on implementation details of the kernel. Since
1140 * the kernel doesn't expose the maximum value to us, we can only try and hope. Hence, let's start with
1141 * INT_MAX, and then keep halving the value until we find one that works. Ugly? Yes, absolutely, but kernel
1142 * APIs are kernel APIs, so what do can we do... 🤯 */
1147 v
&= ~(__SIZEOF_POINTER__
- 1); /* Round down to next multiple of the pointer size */
1149 log_warning("Can't bump fs.nr_open, value too small.");
1155 log_error_errno(k
, "Failed to read fs.nr_open: %m");
1158 if (k
>= v
) { /* Already larger */
1159 log_debug("Skipping bump, value is already larger.");
1163 r
= sysctl_writef("fs/nr_open", "%i\n", v
);
1165 log_debug("Couldn't write fs.nr_open as %i, halving it.", v
);
1170 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.nr_open, ignoring: %m");
1174 log_debug("Successfully bumped fs.nr_open to %i", v
);
1180 static int bump_rlimit_nofile(struct rlimit
*saved_rlimit
) {
1181 struct rlimit new_rlimit
;
1184 /* Get the underlying absolute limit the kernel enforces */
1185 nr
= read_nr_open();
1187 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1188 new_rlimit
= (struct rlimit
) {
1189 .rlim_cur
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_cur
),
1190 .rlim_max
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_max
),
1193 /* Shortcut if nothing changes. */
1194 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_max
&&
1195 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_cur
) {
1196 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1200 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1201 * both hard and soft. */
1202 r
= setrlimit_closest(RLIMIT_NOFILE
, &new_rlimit
);
1204 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1209 static int bump_rlimit_memlock(struct rlimit
*saved_rlimit
) {
1210 struct rlimit new_rlimit
;
1214 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK which should
1215 * normally disable such checks. We need them to implement IPAddressAllow= and IPAddressDeny=, hence let's bump
1216 * the value high enough for our user. */
1218 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1219 * must be unsigned, hence this is a given, but let's make this clear here. */
1220 assert_cc(RLIM_INFINITY
> 0);
1222 mm
= physical_memory() / 8; /* Let's scale how much we allow to be locked by the amount of physical
1223 * RAM. We allow an eighth to be locked by us, just to pick a value. */
1225 new_rlimit
= (struct rlimit
) {
1226 .rlim_cur
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_cur
, mm
),
1227 .rlim_max
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_max
, mm
),
1230 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_cur
&&
1231 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_max
) {
1232 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1236 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &new_rlimit
);
1238 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1243 static void test_usr(void) {
1245 /* Check that /usr is either on the same file system as / or mounted already. */
1247 if (dir_is_empty("/usr") <= 0)
1250 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1251 "Some things will probably break (sometimes even silently) in mysterious ways. "
1252 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1255 static int enforce_syscall_archs(Set
*archs
) {
1259 if (!is_seccomp_available())
1262 r
= seccomp_restrict_archs(arg_syscall_archs
);
1264 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1269 static int status_welcome(void) {
1270 _cleanup_free_
char *pretty_name
= NULL
, *ansi_color
= NULL
;
1273 if (!show_status_on(arg_show_status
))
1276 r
= parse_os_release(NULL
,
1277 "PRETTY_NAME", &pretty_name
,
1278 "ANSI_COLOR", &ansi_color
,
1281 log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1282 "Failed to read os-release file, ignoring: %m");
1284 if (log_get_show_color())
1285 return status_printf(NULL
, 0,
1286 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1287 isempty(ansi_color
) ? "1" : ansi_color
,
1288 isempty(pretty_name
) ? "Linux" : pretty_name
);
1290 return status_printf(NULL
, 0,
1291 "\nWelcome to %s!\n",
1292 isempty(pretty_name
) ? "Linux" : pretty_name
);
1295 static int write_container_id(void) {
1299 c
= getenv("container");
1303 RUN_WITH_UMASK(0022)
1304 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1306 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1311 static int bump_unix_max_dgram_qlen(void) {
1312 _cleanup_free_
char *qlen
= NULL
;
1316 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set the value
1317 * really really early during boot, so that it is actually applied to all our sockets, including the
1318 * $NOTIFY_SOCKET one. */
1320 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1322 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1324 r
= safe_atolu(qlen
, &v
);
1326 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen
);
1328 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1331 r
= write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER
, "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN
);
1333 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1334 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1339 static int fixup_environment(void) {
1340 _cleanup_free_
char *term
= NULL
;
1344 /* Only fix up the environment when we are started as PID 1 */
1345 if (getpid_cached() != 1)
1348 /* We expect the environment to be set correctly if run inside a container. */
1349 if (detect_container() > 0)
1352 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the backend
1353 * device used by the console. We try to make a better guess here since some consoles might not have support
1354 * for color mode for example.
1356 * However if TERM was configured through the kernel command line then leave it alone. */
1357 r
= proc_cmdline_get_key("TERM", 0, &term
);
1361 t
= term
?: default_term_for_tty("/dev/console");
1363 if (setenv("TERM", t
, 1) < 0)
1366 /* The kernels sets HOME=/ for init. Let's undo this. */
1367 if (path_equal_ptr(getenv("HOME"), "/") &&
1368 unsetenv("HOME") < 0)
1369 log_warning_errno(errno
, "Failed to unset $HOME: %m");
1374 static void redirect_telinit(int argc
, char *argv
[]) {
1376 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1378 #if HAVE_SYSV_COMPAT
1379 if (getpid_cached() == 1)
1382 if (!strstr(program_invocation_short_name
, "init"))
1385 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1386 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1391 static int become_shutdown(
1392 const char *shutdown_verb
,
1395 char log_level
[DECIMAL_STR_MAX(int) + 1],
1396 exit_code
[DECIMAL_STR_MAX(uint8_t) + 1],
1397 timeout
[DECIMAL_STR_MAX(usec_t
) + 1];
1399 const char* command_line
[13] = {
1400 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1402 "--timeout", timeout
,
1403 "--log-level", log_level
,
1407 _cleanup_strv_free_
char **env_block
= NULL
;
1410 usec_t watchdog_timer
= 0;
1412 assert(shutdown_verb
);
1413 assert(!command_line
[pos
]);
1414 env_block
= strv_copy(environ
);
1416 xsprintf(log_level
, "%d", log_get_max_level());
1417 xsprintf(timeout
, "%" PRI_USEC
"us", arg_default_timeout_stop_usec
);
1419 switch (log_get_target()) {
1421 case LOG_TARGET_KMSG
:
1422 case LOG_TARGET_JOURNAL_OR_KMSG
:
1423 case LOG_TARGET_SYSLOG_OR_KMSG
:
1424 command_line
[pos
++] = "kmsg";
1427 case LOG_TARGET_NULL
:
1428 command_line
[pos
++] = "null";
1431 case LOG_TARGET_CONSOLE
:
1433 command_line
[pos
++] = "console";
1437 if (log_get_show_color())
1438 command_line
[pos
++] = "--log-color";
1440 if (log_get_show_location())
1441 command_line
[pos
++] = "--log-location";
1443 if (log_get_show_time())
1444 command_line
[pos
++] = "--log-time";
1446 if (streq(shutdown_verb
, "exit")) {
1447 command_line
[pos
++] = "--exit-code";
1448 command_line
[pos
++] = exit_code
;
1449 xsprintf(exit_code
, "%d", retval
);
1452 assert(pos
< ELEMENTSOF(command_line
));
1454 if (streq(shutdown_verb
, "reboot"))
1455 watchdog_timer
= arg_reboot_watchdog
;
1456 else if (streq(shutdown_verb
, "kexec"))
1457 watchdog_timer
= arg_kexec_watchdog
;
1459 if (watchdog_timer
> 0 && watchdog_timer
!= USEC_INFINITY
) {
1463 /* If we reboot or kexec let's set the shutdown
1464 * watchdog and tell the shutdown binary to
1465 * repeatedly ping it */
1466 r
= watchdog_set_timeout(&watchdog_timer
);
1467 watchdog_close(r
< 0);
1469 /* Tell the binary how often to ping, ignore failure */
1470 if (asprintf(&e
, "WATCHDOG_USEC="USEC_FMT
, watchdog_timer
) > 0)
1471 (void) strv_consume(&env_block
, e
);
1473 if (arg_watchdog_device
&&
1474 asprintf(&e
, "WATCHDOG_DEVICE=%s", arg_watchdog_device
) > 0)
1475 (void) strv_consume(&env_block
, e
);
1477 watchdog_close(true);
1479 /* Avoid the creation of new processes forked by the
1480 * kernel; at this point, we will not listen to the
1482 if (detect_container() <= 0)
1483 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1485 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1489 static void initialize_clock(void) {
1492 if (clock_is_localtime(NULL
) > 0) {
1496 * The very first call of settimeofday() also does a time warp in the kernel.
1498 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to take care
1499 * of maintaining the RTC and do all adjustments. This matches the behavior of Windows, which leaves
1500 * the RTC alone if the registry tells that the RTC runs in UTC.
1502 r
= clock_set_timezone(&min
);
1504 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1506 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1508 } else if (!in_initrd()) {
1510 * Do a dummy very first call to seal the kernel's time warp magic.
1512 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with LOCAL, but the
1513 * real system could be set up that way. In such case, we need to delay the time-warp or the sealing
1514 * until we reach the real system.
1516 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably, the time
1517 * will jump or be incorrect at every daylight saving time change. All kernel local time concepts will
1518 * be treated as UTC that way.
1520 (void) clock_reset_timewarp();
1523 r
= clock_apply_epoch();
1525 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1527 log_info("System time before build time, advancing clock.");
1530 static void initialize_coredump(bool skip_setup
) {
1532 if (getpid_cached() != 1)
1535 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1536 * will process core dumps for system services by default. */
1537 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1538 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1540 /* But at the same time, turn off the core_pattern logic by default, so that no
1541 * coredumps are stored until the systemd-coredump tool is enabled via
1542 * sysctl. However it can be changed via the kernel command line later so core
1543 * dumps can still be generated during early startup and in initramfs. */
1545 disable_coredumps();
1549 static void initialize_core_pattern(bool skip_setup
) {
1552 if (skip_setup
|| !arg_early_core_pattern
)
1555 if (getpid_cached() != 1)
1558 r
= write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1560 log_warning_errno(r
, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m", arg_early_core_pattern
);
1563 static void update_cpu_affinity(bool skip_setup
) {
1564 _cleanup_free_
char *mask
= NULL
;
1566 if (skip_setup
|| !arg_cpu_affinity
.set
)
1569 assert(arg_cpu_affinity
.allocated
> 0);
1571 mask
= cpu_set_to_string(&arg_cpu_affinity
);
1572 log_debug("Setting CPU affinity to %s.", strnull(mask
));
1574 if (sched_setaffinity(0, arg_cpu_affinity
.allocated
, arg_cpu_affinity
.set
) < 0)
1575 log_warning_errno(errno
, "Failed to set CPU affinity: %m");
1578 static void update_numa_policy(bool skip_setup
) {
1580 _cleanup_free_
char *nodes
= NULL
;
1581 const char * policy
= NULL
;
1583 if (skip_setup
|| !mpol_is_valid(numa_policy_get_type(&arg_numa_policy
)))
1586 if (DEBUG_LOGGING
) {
1587 policy
= mpol_to_string(numa_policy_get_type(&arg_numa_policy
));
1588 nodes
= cpu_set_to_range_string(&arg_numa_policy
.nodes
);
1589 log_debug("Setting NUMA policy to %s, with nodes %s.", strnull(policy
), strnull(nodes
));
1592 r
= apply_numa_policy(&arg_numa_policy
);
1593 if (r
== -EOPNOTSUPP
)
1594 log_debug_errno(r
, "NUMA support not available, ignoring.");
1596 log_warning_errno(r
, "Failed to set NUMA memory policy: %m");
1599 static void do_reexecute(
1602 const struct rlimit
*saved_rlimit_nofile
,
1603 const struct rlimit
*saved_rlimit_memlock
,
1605 const char *switch_root_dir
,
1606 const char *switch_root_init
,
1607 const char **ret_error_message
) {
1609 unsigned i
, j
, args_size
;
1613 assert(saved_rlimit_nofile
);
1614 assert(saved_rlimit_memlock
);
1615 assert(ret_error_message
);
1617 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get rebooted while
1619 watchdog_close(true);
1621 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1622 * the kernel default to its child processes */
1623 if (saved_rlimit_nofile
->rlim_cur
!= 0)
1624 (void) setrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
);
1625 if (saved_rlimit_memlock
->rlim_cur
!= RLIM_INFINITY
)
1626 (void) setrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
);
1628 if (switch_root_dir
) {
1629 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
1630 * SIGCHLD for them after deserializing. */
1631 broadcast_signal(SIGTERM
, false, true, arg_default_timeout_stop_usec
);
1633 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1634 r
= switch_root(switch_root_dir
, "/mnt", true, MS_MOVE
);
1636 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
1639 args_size
= MAX(6, argc
+1);
1640 args
= newa(const char*, args_size
);
1642 if (!switch_root_init
) {
1643 char sfd
[DECIMAL_STR_MAX(int) + 1];
1645 /* First try to spawn ourselves with the right path, and with full serialization. We do this only if
1646 * the user didn't specify an explicit init to spawn. */
1648 assert(arg_serialization
);
1651 xsprintf(sfd
, "%i", fileno(arg_serialization
));
1654 args
[i
++] = SYSTEMD_BINARY_PATH
;
1655 if (switch_root_dir
)
1656 args
[i
++] = "--switched-root";
1657 args
[i
++] = arg_system
? "--system" : "--user";
1658 args
[i
++] = "--deserialize";
1662 assert(i
<= args_size
);
1665 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do this is on
1666 * its own on exec(), but it will do it on exit(). Hence, to ensure we get a summary here, fork() off
1667 * a child, let it exit() cleanly, so that it prints the summary, and wait() for it in the parent,
1668 * before proceeding into the exec().
1670 valgrind_summary_hack();
1672 (void) execv(args
[0], (char* const*) args
);
1673 log_debug_errno(errno
, "Failed to execute our own binary, trying fallback: %m");
1676 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and envp[]. (Well,
1677 * modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[], but let's hope that
1678 * doesn't matter.) */
1680 arg_serialization
= safe_fclose(arg_serialization
);
1681 fds
= fdset_free(fds
);
1683 /* Reopen the console */
1684 (void) make_console_stdio();
1686 for (j
= 1, i
= 1; j
< (unsigned) argc
; j
++)
1687 args
[i
++] = argv
[j
];
1689 assert(i
<= args_size
);
1691 /* Re-enable any blocked signals, especially important if we switch from initial ramdisk to init=... */
1692 (void) reset_all_signal_handlers();
1693 (void) reset_signal_mask();
1694 (void) rlimit_nofile_safe();
1696 if (switch_root_init
) {
1697 args
[0] = switch_root_init
;
1698 (void) execve(args
[0], (char* const*) args
, saved_env
);
1699 log_warning_errno(errno
, "Failed to execute configured init, trying fallback: %m");
1702 args
[0] = "/sbin/init";
1703 (void) execv(args
[0], (char* const*) args
);
1706 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
1707 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
1708 "Failed to execute /sbin/init");
1711 log_warning("No /sbin/init, trying fallback");
1713 args
[0] = "/bin/sh";
1715 (void) execve(args
[0], (char* const*) args
, saved_env
);
1716 log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
1718 log_warning_errno(r
, "Failed to execute /sbin/init, giving up: %m");
1720 *ret_error_message
= "Failed to execute fallback shell";
1723 static int invoke_main_loop(
1725 const struct rlimit
*saved_rlimit_nofile
,
1726 const struct rlimit
*saved_rlimit_memlock
,
1727 bool *ret_reexecute
,
1728 int *ret_retval
, /* Return parameters relevant for shutting down */
1729 const char **ret_shutdown_verb
, /* … */
1730 FDSet
**ret_fds
, /* Return parameters for reexecuting */
1731 char **ret_switch_root_dir
, /* … */
1732 char **ret_switch_root_init
, /* … */
1733 const char **ret_error_message
) {
1738 assert(saved_rlimit_nofile
);
1739 assert(saved_rlimit_memlock
);
1740 assert(ret_reexecute
);
1742 assert(ret_shutdown_verb
);
1744 assert(ret_switch_root_dir
);
1745 assert(ret_switch_root_init
);
1746 assert(ret_error_message
);
1749 r
= manager_loop(m
);
1751 *ret_error_message
= "Failed to run main loop";
1752 return log_emergency_errno(r
, "Failed to run main loop: %m");
1755 switch ((ManagerObjective
) r
) {
1757 case MANAGER_RELOAD
: {
1758 LogTarget saved_log_target
;
1759 int saved_log_level
;
1761 log_info("Reloading.");
1763 /* First, save any overridden log level/target, then parse the configuration file, which might
1764 * change the log level to new settings. */
1766 saved_log_level
= m
->log_level_overridden
? log_get_max_level() : -1;
1767 saved_log_target
= m
->log_target_overridden
? log_get_target() : _LOG_TARGET_INVALID
;
1769 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
1771 set_manager_defaults(m
);
1773 update_cpu_affinity(false);
1774 update_numa_policy(false);
1776 if (saved_log_level
>= 0)
1777 manager_override_log_level(m
, saved_log_level
);
1778 if (saved_log_target
>= 0)
1779 manager_override_log_target(m
, saved_log_target
);
1781 r
= manager_reload(m
);
1783 /* Reloading failed before the point of no return. Let's continue running as if nothing happened. */
1784 m
->objective
= MANAGER_OK
;
1789 case MANAGER_REEXECUTE
:
1791 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, false);
1793 *ret_error_message
= "Failed to prepare for reexecution";
1797 log_notice("Reexecuting.");
1799 *ret_reexecute
= true;
1800 *ret_retval
= EXIT_SUCCESS
;
1801 *ret_shutdown_verb
= NULL
;
1802 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1806 case MANAGER_SWITCH_ROOT
:
1807 if (!m
->switch_root_init
) {
1808 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, true);
1810 *ret_error_message
= "Failed to prepare for reexecution";
1816 log_notice("Switching root.");
1818 *ret_reexecute
= true;
1819 *ret_retval
= EXIT_SUCCESS
;
1820 *ret_shutdown_verb
= NULL
;
1822 /* Steal the switch root parameters */
1823 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
1824 *ret_switch_root_init
= TAKE_PTR(m
->switch_root_init
);
1830 if (MANAGER_IS_USER(m
)) {
1833 *ret_reexecute
= false;
1834 *ret_retval
= m
->return_value
;
1835 *ret_shutdown_verb
= NULL
;
1837 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1843 case MANAGER_REBOOT
:
1844 case MANAGER_POWEROFF
:
1846 case MANAGER_KEXEC
: {
1847 static const char * const table
[_MANAGER_OBJECTIVE_MAX
] = {
1848 [MANAGER_EXIT
] = "exit",
1849 [MANAGER_REBOOT
] = "reboot",
1850 [MANAGER_POWEROFF
] = "poweroff",
1851 [MANAGER_HALT
] = "halt",
1852 [MANAGER_KEXEC
] = "kexec",
1855 log_notice("Shutting down.");
1857 *ret_reexecute
= false;
1858 *ret_retval
= m
->return_value
;
1859 assert_se(*ret_shutdown_verb
= table
[m
->objective
]);
1861 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1867 assert_not_reached("Unknown or unexpected manager objective.");
1872 static void log_execution_mode(bool *ret_first_boot
) {
1873 assert(ret_first_boot
);
1878 log_info("systemd " GIT_VERSION
" running in %ssystem mode. (" SYSTEMD_FEATURES
")",
1879 arg_action
== ACTION_TEST
? "test " : "" );
1881 v
= detect_virtualization();
1883 log_info("Detected virtualization %s.", virtualization_to_string(v
));
1885 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
1888 *ret_first_boot
= false;
1889 log_info("Running in initial RAM disk.");
1891 /* Let's check whether we are in first boot, i.e. whether /etc is still unpopulated. We use
1892 * /etc/machine-id as flag file, for this: if it exists we assume /etc is populated, if it
1893 * doesn't it's unpopulated. This allows container managers and installers to provision a
1894 * couple of files already. If the container manager wants to provision the machine ID itself
1895 * it should pass $container_uuid to PID 1. */
1897 *ret_first_boot
= access("/etc/machine-id", F_OK
) < 0;
1898 if (*ret_first_boot
)
1899 log_info("Running with unpopulated /etc.");
1902 if (DEBUG_LOGGING
) {
1903 _cleanup_free_
char *t
;
1905 t
= uid_to_name(getuid());
1906 log_debug("systemd " GIT_VERSION
" running in %suser mode for user " UID_FMT
"/%s. (" SYSTEMD_FEATURES
")",
1907 arg_action
== ACTION_TEST
? " test" : "", getuid(), strna(t
));
1910 *ret_first_boot
= false;
1914 static int initialize_runtime(
1916 struct rlimit
*saved_rlimit_nofile
,
1917 struct rlimit
*saved_rlimit_memlock
,
1918 const char **ret_error_message
) {
1921 assert(ret_error_message
);
1923 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
1925 * - Some only apply to --system instances
1926 * - Some only apply to --user instances
1927 * - Some only apply when we first start up, but not when we reexecute
1930 if (arg_action
!= ACTION_RUN
)
1933 update_cpu_affinity(skip_setup
);
1934 update_numa_policy(skip_setup
);
1937 /* Make sure we leave a core dump without panicking the kernel. */
1938 install_crash_handler();
1941 r
= mount_cgroup_controllers();
1943 *ret_error_message
= "Failed to mount cgroup hierarchies";
1949 machine_id_setup(NULL
, arg_machine_id
, NULL
);
1950 (void) loopback_setup();
1951 bump_unix_max_dgram_qlen();
1952 bump_file_max_and_nr_open();
1954 write_container_id();
1957 if (arg_watchdog_device
) {
1958 r
= watchdog_set_device(arg_watchdog_device
);
1960 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device
);
1963 if (timestamp_is_set(arg_runtime_watchdog
))
1964 watchdog_set_timeout(&arg_runtime_watchdog
);
1967 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
1968 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
1969 log_warning_errno(errno
, "Failed to adjust timer slack, ignoring: %m");
1971 if (arg_system
&& !cap_test_all(arg_capability_bounding_set
)) {
1972 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
1974 *ret_error_message
= "Failed to drop capability bounding set of usermode helpers";
1975 return log_emergency_errno(r
, "Failed to drop capability bounding set of usermode helpers: %m");
1978 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
1980 *ret_error_message
= "Failed to drop capability bounding set";
1981 return log_emergency_errno(r
, "Failed to drop capability bounding set: %m");
1985 if (arg_system
&& arg_no_new_privs
) {
1986 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
1987 *ret_error_message
= "Failed to disable new privileges";
1988 return log_emergency_errno(errno
, "Failed to disable new privileges: %m");
1992 if (arg_syscall_archs
) {
1993 r
= enforce_syscall_archs(arg_syscall_archs
);
1995 *ret_error_message
= "Failed to set syscall architectures";
2001 /* Become reaper of our children */
2002 if (prctl(PR_SET_CHILD_SUBREAPER
, 1) < 0)
2003 log_warning_errno(errno
, "Failed to make us a subreaper: %m");
2005 /* Bump up RLIMIT_NOFILE for systemd itself */
2006 (void) bump_rlimit_nofile(saved_rlimit_nofile
);
2007 (void) bump_rlimit_memlock(saved_rlimit_memlock
);
2012 static int do_queue_default_job(
2014 const char **ret_error_message
) {
2016 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2022 if (arg_default_unit
)
2023 unit
= arg_default_unit
;
2024 else if (in_initrd())
2025 unit
= SPECIAL_INITRD_TARGET
;
2027 unit
= SPECIAL_DEFAULT_TARGET
;
2029 log_debug("Activating default unit: %s", unit
);
2031 r
= manager_load_startable_unit_or_warn(m
, unit
, NULL
, &target
);
2032 if (r
< 0 && in_initrd() && !arg_default_unit
) {
2033 /* Fall back to default.target, which we used to always use by default. Only do this if no
2034 * explicit configuration was given. */
2036 log_info("Falling back to " SPECIAL_DEFAULT_TARGET
".");
2038 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_DEFAULT_TARGET
, NULL
, &target
);
2041 log_info("Falling back to " SPECIAL_RESCUE_TARGET
".");
2043 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_RESCUE_TARGET
, NULL
, &target
);
2045 *ret_error_message
= r
== -ERFKILL
? SPECIAL_RESCUE_TARGET
" masked"
2046 : "Failed to load " SPECIAL_RESCUE_TARGET
;
2051 assert(target
->load_state
== UNIT_LOADED
);
2053 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, NULL
, &error
, &job
);
2055 log_debug_errno(r
, "Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
2057 sd_bus_error_free(&error
);
2059 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, NULL
, &error
, &job
);
2061 *ret_error_message
= "Failed to start default target";
2062 return log_emergency_errno(r
, "Failed to start default target: %s", bus_error_message(&error
, r
));
2066 *ret_error_message
= "Failed to isolate default target";
2067 return log_emergency_errno(r
, "Failed to isolate default target: %s", bus_error_message(&error
, r
));
2069 log_info("Queued %s job for default target %s.",
2070 job_type_to_string(job
->type
),
2071 unit_status_string(job
->unit
));
2073 m
->default_unit_job_id
= job
->id
;
2078 static void save_rlimits(struct rlimit
*saved_rlimit_nofile
,
2079 struct rlimit
*saved_rlimit_memlock
) {
2081 assert(saved_rlimit_nofile
);
2082 assert(saved_rlimit_memlock
);
2084 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
) < 0)
2085 log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2087 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
) < 0)
2088 log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2091 static void fallback_rlimit_nofile(const struct rlimit
*saved_rlimit_nofile
) {
2094 if (arg_default_rlimit
[RLIMIT_NOFILE
])
2097 /* Make sure forked processes get limits based on the original kernel setting */
2099 rl
= newdup(struct rlimit
, saved_rlimit_nofile
, 1);
2105 /* Bump the hard limit for system services to a substantially higher value. The default
2106 * hard limit current kernels set is pretty low (4K), mostly for historical
2107 * reasons. According to kernel developers, the fd handling in recent kernels has been
2108 * optimized substantially enough, so that we can bump the limit now, without paying too
2109 * high a price in memory or performance. Note however that we only bump the hard limit,
2110 * not the soft limit. That's because select() works the way it works, and chokes on fds
2111 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2112 * unexpecting programs that they get fds higher than what they can process using
2113 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2114 * this pitfall: programs that are written by folks aware of the select() problem in mind
2115 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2116 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2121 /* Get the underlying absolute limit the kernel enforces */
2122 nr
= read_nr_open();
2124 rl
->rlim_max
= MIN((rlim_t
) nr
, MAX(rl
->rlim_max
, (rlim_t
) HIGH_RLIMIT_NOFILE
));
2127 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2128 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2129 * instance), then lower what we pass on to not confuse our children */
2130 rl
->rlim_cur
= MIN(rl
->rlim_cur
, (rlim_t
) FD_SETSIZE
);
2132 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
2135 static void fallback_rlimit_memlock(const struct rlimit
*saved_rlimit_memlock
) {
2138 /* Pass the original value down to invoked processes */
2140 if (arg_default_rlimit
[RLIMIT_MEMLOCK
])
2143 rl
= newdup(struct rlimit
, saved_rlimit_memlock
, 1);
2149 arg_default_rlimit
[RLIMIT_MEMLOCK
] = rl
;
2152 static void reset_arguments(void) {
2153 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2155 arg_default_unit
= mfree(arg_default_unit
);
2157 /* arg_system — ignore */
2159 arg_dump_core
= true;
2160 arg_crash_chvt
= -1;
2161 arg_crash_shell
= false;
2162 arg_crash_reboot
= false;
2163 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2164 arg_show_status
= _SHOW_STATUS_INVALID
;
2165 arg_status_unit_format
= STATUS_UNIT_FORMAT_DEFAULT
;
2166 arg_switched_root
= false;
2167 arg_pager_flags
= 0;
2168 arg_service_watchdogs
= true;
2169 arg_default_std_output
= EXEC_OUTPUT_JOURNAL
;
2170 arg_default_std_error
= EXEC_OUTPUT_INHERIT
;
2171 arg_default_restart_usec
= DEFAULT_RESTART_USEC
;
2172 arg_default_timeout_start_usec
= DEFAULT_TIMEOUT_USEC
;
2173 arg_default_timeout_stop_usec
= DEFAULT_TIMEOUT_USEC
;
2174 arg_default_timeout_abort_usec
= DEFAULT_TIMEOUT_USEC
;
2175 arg_default_timeout_abort_set
= false;
2176 arg_default_start_limit_interval
= DEFAULT_START_LIMIT_INTERVAL
;
2177 arg_default_start_limit_burst
= DEFAULT_START_LIMIT_BURST
;
2178 arg_runtime_watchdog
= 0;
2179 arg_reboot_watchdog
= 10 * USEC_PER_MINUTE
;
2180 arg_kexec_watchdog
= 0;
2181 arg_early_core_pattern
= NULL
;
2182 arg_watchdog_device
= NULL
;
2184 arg_default_environment
= strv_free(arg_default_environment
);
2185 rlimit_free_all(arg_default_rlimit
);
2187 arg_capability_bounding_set
= CAP_ALL
;
2188 arg_no_new_privs
= false;
2189 arg_timer_slack_nsec
= NSEC_INFINITY
;
2190 arg_default_timer_accuracy_usec
= 1 * USEC_PER_MINUTE
;
2192 arg_syscall_archs
= set_free(arg_syscall_archs
);
2194 /* arg_serialization — ignore */
2196 arg_default_cpu_accounting
= -1;
2197 arg_default_io_accounting
= false;
2198 arg_default_ip_accounting
= false;
2199 arg_default_blockio_accounting
= false;
2200 arg_default_memory_accounting
= MEMORY_ACCOUNTING_DEFAULT
;
2201 arg_default_tasks_accounting
= true;
2202 arg_default_tasks_max
= DEFAULT_TASKS_MAX
;
2203 arg_machine_id
= (sd_id128_t
) {};
2204 arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
2205 arg_default_oom_policy
= OOM_STOP
;
2207 cpu_set_reset(&arg_cpu_affinity
);
2208 numa_policy_reset(&arg_numa_policy
);
2211 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
2212 const struct rlimit
*saved_rlimit_memlock
) {
2215 assert(saved_rlimit_nofile
);
2216 assert(saved_rlimit_memlock
);
2218 /* Assign configuration defaults */
2221 r
= parse_config_file();
2223 log_warning_errno(r
, "Failed to parse config file, ignoring: %m");
2226 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
2228 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2231 /* Initialize some default rlimits for services if they haven't been configured */
2232 fallback_rlimit_nofile(saved_rlimit_nofile
);
2233 fallback_rlimit_memlock(saved_rlimit_memlock
);
2235 /* Note that this also parses bits from the kernel command line, including "debug". */
2236 log_parse_environment();
2241 static int load_configuration(
2244 const struct rlimit
*saved_rlimit_nofile
,
2245 const struct rlimit
*saved_rlimit_memlock
,
2246 const char **ret_error_message
) {
2249 assert(saved_rlimit_nofile
);
2250 assert(saved_rlimit_memlock
);
2251 assert(ret_error_message
);
2253 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
2255 r
= parse_argv(argc
, argv
);
2257 *ret_error_message
= "Failed to parse commandline arguments";
2261 /* Initialize the show status setting if it hasn't been set explicitly yet */
2262 if (arg_show_status
== _SHOW_STATUS_INVALID
)
2263 arg_show_status
= SHOW_STATUS_YES
;
2268 static int safety_checks(void) {
2270 if (getpid_cached() == 1 &&
2271 arg_action
!= ACTION_RUN
)
2272 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2273 "Unsupported execution mode while PID 1.");
2275 if (getpid_cached() == 1 &&
2277 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2278 "Can't run --user mode as PID 1.");
2280 if (arg_action
== ACTION_RUN
&&
2282 getpid_cached() != 1)
2283 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2284 "Can't run system mode unless PID 1.");
2286 if (arg_action
== ACTION_TEST
&&
2288 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2289 "Don't run test mode as root.");
2292 arg_action
== ACTION_RUN
&&
2294 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2295 "Trying to run as user instance, but the system has not been booted with systemd.");
2298 arg_action
== ACTION_RUN
&&
2299 !getenv("XDG_RUNTIME_DIR"))
2300 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH
),
2301 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2304 arg_action
== ACTION_RUN
&&
2305 running_in_chroot() > 0)
2306 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2307 "Cannot be run in a chroot() environment.");
2312 static int initialize_security(
2313 bool *loaded_policy
,
2314 dual_timestamp
*security_start_timestamp
,
2315 dual_timestamp
*security_finish_timestamp
,
2316 const char **ret_error_message
) {
2320 assert(loaded_policy
);
2321 assert(security_start_timestamp
);
2322 assert(security_finish_timestamp
);
2323 assert(ret_error_message
);
2325 dual_timestamp_get(security_start_timestamp
);
2327 r
= mac_selinux_setup(loaded_policy
);
2329 *ret_error_message
= "Failed to load SELinux policy";
2333 r
= mac_smack_setup(loaded_policy
);
2335 *ret_error_message
= "Failed to load SMACK policy";
2341 *ret_error_message
= "Failed to load IMA policy";
2345 dual_timestamp_get(security_finish_timestamp
);
2349 static void test_summary(Manager
*m
) {
2352 printf("-> By units:\n");
2353 manager_dump_units(m
, stdout
, "\t");
2355 printf("-> By jobs:\n");
2356 manager_dump_jobs(m
, stdout
, "\t");
2359 static int collect_fds(FDSet
**ret_fds
, const char **ret_error_message
) {
2363 assert(ret_error_message
);
2365 r
= fdset_new_fill(ret_fds
);
2367 *ret_error_message
= "Failed to allocate fd set";
2368 return log_emergency_errno(r
, "Failed to allocate fd set: %m");
2371 fdset_cloexec(*ret_fds
, true);
2373 if (arg_serialization
)
2374 assert_se(fdset_remove(*ret_fds
, fileno(arg_serialization
)) >= 0);
2379 static void setup_console_terminal(bool skip_setup
) {
2384 /* Become a session leader if we aren't one yet. */
2387 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a controlling
2389 (void) release_terminal();
2391 /* Reset the console, but only if this is really init and we are freshly booted */
2392 if (getpid_cached() == 1 && !skip_setup
)
2393 (void) console_setup();
2396 static bool early_skip_setup_check(int argc
, char *argv
[]) {
2397 bool found_deserialize
= false;
2400 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much later, so
2401 * let's just have a quick peek here. Note that if we have switched root, do all the special setup things
2402 * anyway, even if in that case we also do deserialization. */
2404 for (i
= 1; i
< argc
; i
++) {
2405 if (streq(argv
[i
], "--switched-root"))
2406 return false; /* If we switched root, don't skip the setup. */
2407 else if (streq(argv
[i
], "--deserialize"))
2408 found_deserialize
= true;
2411 return found_deserialize
; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2414 static int save_env(void) {
2417 l
= strv_copy(environ
);
2421 strv_free_and_replace(saved_env
, l
);
2425 int main(int argc
, char *argv
[]) {
2427 dual_timestamp initrd_timestamp
= DUAL_TIMESTAMP_NULL
, userspace_timestamp
= DUAL_TIMESTAMP_NULL
, kernel_timestamp
= DUAL_TIMESTAMP_NULL
,
2428 security_start_timestamp
= DUAL_TIMESTAMP_NULL
, security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
2429 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0),
2430 saved_rlimit_memlock
= RLIMIT_MAKE_CONST(RLIM_INFINITY
); /* The original rlimits we passed
2431 * in. Note we use different values
2432 * for the two that indicate whether
2433 * these fields are initialized! */
2434 bool skip_setup
, loaded_policy
= false, queue_default_job
= false, first_boot
= false, reexecute
= false;
2435 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
2436 usec_t before_startup
, after_startup
;
2437 static char systemd
[] = "systemd";
2438 char timespan
[FORMAT_TIMESPAN_MAX
];
2439 const char *shutdown_verb
= NULL
, *error_message
= NULL
;
2440 int r
, retval
= EXIT_FAILURE
;
2444 /* SysV compatibility: redirect init → telinit */
2445 redirect_telinit(argc
, argv
);
2447 /* Take timestamps early on */
2448 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
2449 dual_timestamp_get(&userspace_timestamp
);
2451 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2453 skip_setup
= early_skip_setup_check(argc
, argv
);
2455 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent reexecution we
2456 * are then called 'systemd'. That is confusing, hence let's call us systemd right-away. */
2457 program_invocation_short_name
= systemd
;
2458 (void) prctl(PR_SET_NAME
, systemd
);
2460 /* Save the original command line */
2461 save_argc_argv(argc
, argv
);
2463 /* Save the original environment as we might need to restore it if we're requested to execute another
2464 * system manager later. */
2467 error_message
= "Failed to copy environment block";
2471 /* Make sure that if the user says "syslog" we actually log to the journal. */
2472 log_set_upgrade_syslog_to_journal(true);
2474 if (getpid_cached() == 1) {
2475 /* When we run as PID 1 force system mode */
2478 /* Disable the umask logic */
2481 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might not be
2482 * activated yet (even though the log socket for it exists). */
2483 log_set_prohibit_ipc(true);
2485 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
2486 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
2487 * child process right before execve()'ing the actual binary, at a point in time where socket
2488 * activation stderr/stdout area already set up. */
2489 log_set_always_reopen_console(true);
2491 if (detect_container() <= 0) {
2493 /* Running outside of a container as PID 1 */
2494 log_set_target(LOG_TARGET_KMSG
);
2498 initrd_timestamp
= userspace_timestamp
;
2501 r
= mount_setup_early();
2503 error_message
= "Failed to mount early API filesystems";
2507 /* Let's open the log backend a second time, in case the first time didn't
2508 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2509 * available, and it previously wasn't. */
2512 disable_printk_ratelimit();
2514 r
= initialize_security(
2516 &security_start_timestamp
,
2517 &security_finish_timestamp
,
2523 if (mac_selinux_init() < 0) {
2524 error_message
= "Failed to initialize SELinux policy";
2531 /* Set the default for later on, but don't actually open the logs like this for now. Note that
2532 * if we are transitioning from the initrd there might still be journal fd open, and we
2533 * shouldn't attempt opening that before we parsed /proc/cmdline which might redirect output
2535 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
2538 /* Running inside a container, as PID 1 */
2539 log_set_target(LOG_TARGET_CONSOLE
);
2542 /* For later on, see above... */
2543 log_set_target(LOG_TARGET_JOURNAL
);
2545 /* clear the kernel timestamp,
2546 * because we are in a container */
2547 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2550 initialize_coredump(skip_setup
);
2552 r
= fixup_environment();
2554 log_emergency_errno(r
, "Failed to fix up PID 1 environment: %m");
2555 error_message
= "Failed to fix up PID1 environment";
2560 /* Running as user instance */
2562 log_set_target(LOG_TARGET_AUTO
);
2565 /* clear the kernel timestamp,
2566 * because we are not PID 1 */
2567 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2571 /* Try to figure out if we can use colors with the console. No need to do that for user instances since
2572 * they never log into the console. */
2573 log_show_color(colors_enabled());
2575 r
= make_null_stdio();
2577 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2580 /* Mount /proc, /sys and friends, so that /proc/cmdline and
2581 * /proc/$PID/fd is available. */
2582 if (getpid_cached() == 1) {
2584 /* Load the kernel modules early. */
2588 r
= mount_setup(loaded_policy
, skip_setup
);
2590 error_message
= "Failed to mount API filesystems";
2594 /* The efivarfs is now mounted, let's read the random seed off it */
2595 (void) efi_take_random_seed();
2598 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2599 * transitioning from the initrd to the main systemd or suchlike. */
2600 save_rlimits(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2602 /* Reset all signal handlers. */
2603 (void) reset_all_signal_handlers();
2604 (void) ignore_signals(SIGNALS_IGNORE
, -1);
2606 r
= load_configuration(argc
, argv
, &saved_rlimit_nofile
, &saved_rlimit_memlock
, &error_message
);
2610 r
= safety_checks();
2614 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
, ACTION_DUMP_CONFIGURATION_ITEMS
, ACTION_DUMP_BUS_PROPERTIES
))
2615 (void) pager_open(arg_pager_flags
);
2617 if (arg_action
!= ACTION_RUN
)
2620 if (arg_action
== ACTION_HELP
) {
2621 retval
= help() < 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2623 } else if (arg_action
== ACTION_VERSION
) {
2626 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
2627 unit_dump_config_items(stdout
);
2628 retval
= EXIT_SUCCESS
;
2630 } else if (arg_action
== ACTION_DUMP_BUS_PROPERTIES
) {
2631 dump_bus_properties(stdout
);
2632 retval
= EXIT_SUCCESS
;
2636 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
2638 /* Move out of the way, so that we won't block unmounts */
2639 assert_se(chdir("/") == 0);
2641 if (arg_action
== ACTION_RUN
) {
2643 /* A core pattern might have been specified via the cmdline. */
2644 initialize_core_pattern(skip_setup
);
2646 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
2649 /* Remember open file descriptors for later deserialization */
2650 r
= collect_fds(&fds
, &error_message
);
2654 /* Give up any control of the console, but make sure its initialized. */
2655 setup_console_terminal(skip_setup
);
2657 /* Open the logging devices, if possible and necessary */
2661 log_execution_mode(&first_boot
);
2663 r
= initialize_runtime(skip_setup
,
2664 &saved_rlimit_nofile
,
2665 &saved_rlimit_memlock
,
2670 r
= manager_new(arg_system
? UNIT_FILE_SYSTEM
: UNIT_FILE_USER
,
2671 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
2674 log_emergency_errno(r
, "Failed to allocate manager object: %m");
2675 error_message
= "Failed to allocate manager object";
2679 m
->timestamps
[MANAGER_TIMESTAMP_KERNEL
] = kernel_timestamp
;
2680 m
->timestamps
[MANAGER_TIMESTAMP_INITRD
] = initrd_timestamp
;
2681 m
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
] = userspace_timestamp
;
2682 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START
)] = security_start_timestamp
;
2683 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH
)] = security_finish_timestamp
;
2685 set_manager_defaults(m
);
2686 set_manager_settings(m
);
2687 manager_set_first_boot(m
, first_boot
);
2689 /* Remember whether we should queue the default job */
2690 queue_default_job
= !arg_serialization
|| arg_switched_root
;
2692 before_startup
= now(CLOCK_MONOTONIC
);
2694 r
= manager_startup(m
, arg_serialization
, fds
);
2696 error_message
= "Failed to start up manager";
2700 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2701 fds
= fdset_free(fds
);
2702 arg_serialization
= safe_fclose(arg_serialization
);
2704 if (queue_default_job
) {
2705 r
= do_queue_default_job(m
, &error_message
);
2710 after_startup
= now(CLOCK_MONOTONIC
);
2712 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
2713 "Loaded units and determined initial transaction in %s.",
2714 format_timespan(timespan
, sizeof(timespan
), after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
2716 if (arg_action
== ACTION_TEST
) {
2718 retval
= EXIT_SUCCESS
;
2722 (void) invoke_main_loop(m
,
2723 &saved_rlimit_nofile
,
2724 &saved_rlimit_memlock
,
2737 arg_reboot_watchdog
= m
->reboot_watchdog
;
2738 arg_kexec_watchdog
= m
->kexec_watchdog
;
2739 m
= manager_free(m
);
2743 mac_selinux_finish();
2746 do_reexecute(argc
, argv
,
2747 &saved_rlimit_nofile
,
2748 &saved_rlimit_memlock
,
2752 &error_message
); /* This only returns if reexecution failed */
2754 arg_serialization
= safe_fclose(arg_serialization
);
2755 fds
= fdset_free(fds
);
2757 saved_env
= strv_free(saved_env
);
2759 #if HAVE_VALGRIND_VALGRIND_H
2760 /* If we are PID 1 and running under valgrind, then let's exit
2761 * here explicitly. valgrind will only generate nice output on
2762 * exit(), not on exec(), hence let's do the former not the
2764 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
2765 /* Cleanup watchdog_device strings for valgrind. We need them
2766 * in become_shutdown() so normally we cannot free them yet. */
2767 watchdog_free_device();
2768 arg_watchdog_device
= mfree(arg_watchdog_device
);
2773 #if HAS_FEATURE_ADDRESS_SANITIZER
2774 __lsan_do_leak_check();
2777 if (shutdown_verb
) {
2778 r
= become_shutdown(shutdown_verb
, retval
);
2779 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
2780 error_message
= "Failed to execute shutdown binary";
2783 watchdog_free_device();
2784 arg_watchdog_device
= mfree(arg_watchdog_device
);
2786 if (getpid_cached() == 1) {
2788 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
2789 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
2790 "%s.", error_message
);
2791 freeze_or_exit_or_reboot();