1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/prctl.h>
11 #include <sys/reboot.h>
17 #if HAVE_VALGRIND_VALGRIND_H
18 #include <valgrind/valgrind.h>
22 #include "sd-daemon.h"
23 #include "sd-messages.h"
25 #include "alloc-util.h"
26 #include "architecture.h"
28 #include "bus-error.h"
30 #include "capability-util.h"
31 #include "cgroup-util.h"
32 #include "clock-util.h"
33 #include "conf-parser.h"
34 #include "cpu-set-util.h"
35 #include "dbus-manager.h"
38 #include "efi-random.h"
39 #include "emergency-action.h"
41 #include "exit-status.h"
45 #include "format-util.h"
47 #include "hostname-setup.h"
48 #include "ima-setup.h"
50 #include "kmod-setup.h"
51 #include "limits-util.h"
52 #include "load-fragment.h"
54 #include "loopback-setup.h"
55 #include "machine-id-setup.h"
58 #include "mount-setup.h"
61 #include "parse-util.h"
62 #include "path-util.h"
63 #include "pretty-print.h"
64 #include "proc-cmdline.h"
65 #include "process-util.h"
66 #include "raw-clone.h"
67 #include "rlimit-util.h"
69 #include "seccomp-util.h"
71 #include "selinux-setup.h"
72 #include "selinux-util.h"
73 #include "signal-util.h"
74 #include "smack-setup.h"
76 #include "stat-util.h"
77 #include "stdio-util.h"
79 #include "switch-root.h"
80 #include "sysctl-util.h"
81 #include "terminal-util.h"
82 #include "umask-util.h"
83 #include "user-util.h"
88 #if HAS_FEATURE_ADDRESS_SANITIZER
89 #include <sanitizer/lsan_interface.h>
97 ACTION_DUMP_CONFIGURATION_ITEMS
,
98 ACTION_DUMP_BUS_PROPERTIES
,
99 } arg_action
= ACTION_RUN
;
101 /* Those variables are initalized to 0 automatically, so we avoid uninitialized memory access.
102 * Real defaults are assigned in reset_arguments() below. */
103 static char *arg_default_unit
;
104 static bool arg_system
;
105 static bool arg_dump_core
;
106 static int arg_crash_chvt
;
107 static bool arg_crash_shell
;
108 static bool arg_crash_reboot
;
109 static char *arg_confirm_spawn
;
110 static ShowStatus arg_show_status
;
111 static StatusUnitFormat arg_status_unit_format
;
112 static bool arg_switched_root
;
113 static PagerFlags arg_pager_flags
;
114 static bool arg_service_watchdogs
;
115 static ExecOutput arg_default_std_output
;
116 static ExecOutput arg_default_std_error
;
117 static usec_t arg_default_restart_usec
;
118 static usec_t arg_default_timeout_start_usec
;
119 static usec_t arg_default_timeout_stop_usec
;
120 static usec_t arg_default_timeout_abort_usec
;
121 static bool arg_default_timeout_abort_set
;
122 static usec_t arg_default_start_limit_interval
;
123 static unsigned arg_default_start_limit_burst
;
124 static usec_t arg_runtime_watchdog
;
125 static usec_t arg_reboot_watchdog
;
126 static usec_t arg_kexec_watchdog
;
127 static char *arg_early_core_pattern
;
128 static char *arg_watchdog_device
;
129 static char **arg_default_environment
;
130 static struct rlimit
*arg_default_rlimit
[_RLIMIT_MAX
];
131 static uint64_t arg_capability_bounding_set
;
132 static bool arg_no_new_privs
;
133 static nsec_t arg_timer_slack_nsec
;
134 static usec_t arg_default_timer_accuracy_usec
;
135 static Set
* arg_syscall_archs
;
136 static FILE* arg_serialization
;
137 static int arg_default_cpu_accounting
;
138 static bool arg_default_io_accounting
;
139 static bool arg_default_ip_accounting
;
140 static bool arg_default_blockio_accounting
;
141 static bool arg_default_memory_accounting
;
142 static bool arg_default_tasks_accounting
;
143 static uint64_t arg_default_tasks_max
;
144 static sd_id128_t arg_machine_id
;
145 static EmergencyAction arg_cad_burst_action
;
146 static OOMPolicy arg_default_oom_policy
;
147 static CPUSet arg_cpu_affinity
;
148 static NUMAPolicy arg_numa_policy
;
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 log_emergency("Caught <%s>, core dump failed (child "PID_FMT
", code=%s, status=%i/%s).",
226 signal_to_string(sig
),
227 pid
, sigchld_code_to_string(status
.si_code
),
229 strna(status
.si_code
== CLD_EXITED
230 ? exit_status_to_string(status
.si_status
, EXIT_STATUS_MINIMAL
)
231 : signal_to_string(status
.si_status
)));
233 log_emergency("Caught <%s>, dumped core as pid "PID_FMT
".", signal_to_string(sig
), pid
);
237 if (arg_crash_chvt
>= 0)
238 (void) chvt(arg_crash_chvt
);
240 sa
= (struct sigaction
) {
241 .sa_handler
= SIG_IGN
,
242 .sa_flags
= SA_NOCLDSTOP
|SA_NOCLDWAIT
|SA_RESTART
,
245 /* Let the kernel reap children for us */
246 (void) sigaction(SIGCHLD
, &sa
, NULL
);
248 if (arg_crash_shell
) {
249 log_notice("Executing crash shell in 10s...");
252 pid
= raw_clone(SIGCHLD
);
254 log_emergency_errno(errno
, "Failed to fork off crash shell: %m");
257 (void) make_console_stdio();
258 (void) rlimit_nofile_safe();
259 (void) execle("/bin/sh", "/bin/sh", NULL
, environ
);
261 log_emergency_errno(errno
, "execle() failed: %m");
262 _exit(EXIT_EXCEPTION
);
264 log_info("Spawned crash shell as PID "PID_FMT
".", pid
);
265 (void) wait_for_terminate(pid
, NULL
);
269 freeze_or_exit_or_reboot();
272 static void install_crash_handler(void) {
273 static const struct sigaction sa
= {
275 .sa_flags
= SA_NODEFER
, /* So that we can raise the signal again from the signal handler */
279 /* We ignore the return value here, since, we don't mind if we
280 * cannot set up a crash handler */
281 r
= sigaction_many(&sa
, SIGNALS_CRASH_HANDLER
, -1);
283 log_debug_errno(r
, "I had trouble setting up the crash handler, ignoring: %m");
286 static int console_setup(void) {
287 _cleanup_close_
int tty_fd
= -1;
290 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
292 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
294 /* We don't want to force text mode. plymouth may be showing
295 * pictures already from initrd. */
296 r
= reset_terminal_fd(tty_fd
, false);
298 return log_error_errno(r
, "Failed to reset /dev/console: %m");
303 static int set_machine_id(const char *m
) {
307 if (sd_id128_from_string(m
, &t
) < 0)
310 if (sd_id128_is_null(t
))
317 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
323 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
325 if (proc_cmdline_value_missing(key
, value
))
328 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
329 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
330 else if (in_initrd() == !!startswith(key
, "rd.")) {
331 if (free_and_strdup(&arg_default_unit
, value
) < 0)
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.watchdog_device")) {
477 if (proc_cmdline_value_missing(key
, value
))
480 (void) parse_path_argument_and_warn(value
, false, &arg_watchdog_device
);
482 } else if (streq(key
, "quiet") && !value
) {
484 if (arg_show_status
== _SHOW_STATUS_INVALID
)
485 arg_show_status
= SHOW_STATUS_AUTO
;
487 } else if (streq(key
, "debug") && !value
) {
489 /* Note that log_parse_environment() handles 'debug'
490 * too, and sets the log level to LOG_DEBUG. */
492 if (detect_container() > 0)
493 log_set_target(LOG_TARGET_CONSOLE
);
498 /* SysV compatibility */
499 target
= runlevel_to_target(key
);
501 return free_and_strdup(&arg_default_unit
, target
);
507 #define DEFINE_SETTER(name, func, descr) \
508 static int name(const char *unit, \
509 const char *filename, \
511 const char *section, \
512 unsigned section_line, \
513 const char *lvalue, \
515 const char *rvalue, \
527 log_syntax(unit, LOG_ERR, filename, line, r, \
528 "Invalid " descr "'%s': %m", \
534 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level");
535 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target");
536 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color" );
537 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location");
538 DEFINE_SETTER(config_parse_status_unit_format
, status_unit_format_from_string
, "value");
540 static int parse_config_file(void) {
542 const ConfigTableItem items
[] = {
543 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
544 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
545 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
546 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
547 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
548 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, &arg_crash_chvt
},
549 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, &arg_crash_chvt
},
550 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
551 { "Manager", "CrashReboot", config_parse_bool
, 0, &arg_crash_reboot
},
552 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
553 { "Manager", "StatusUnitFormat", config_parse_status_unit_format
, 0, &arg_status_unit_format
},
554 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, &arg_cpu_affinity
},
555 { "Manager", "NUMAPolicy", config_parse_numa_policy
, 0, &arg_numa_policy
.type
},
556 { "Manager", "NUMAMask", config_parse_numa_mask
, 0, &arg_numa_policy
},
557 { "Manager", "JoinControllers", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
558 { "Manager", "RuntimeWatchdogSec", config_parse_sec
, 0, &arg_runtime_watchdog
},
559 { "Manager", "RebootWatchdogSec", config_parse_sec
, 0, &arg_reboot_watchdog
},
560 { "Manager", "ShutdownWatchdogSec", config_parse_sec
, 0, &arg_reboot_watchdog
}, /* obsolete alias */
561 { "Manager", "KExecWatchdogSec", config_parse_sec
, 0, &arg_kexec_watchdog
},
562 { "Manager", "WatchdogDevice", config_parse_path
, 0, &arg_watchdog_device
},
563 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
564 { "Manager", "NoNewPrivileges", config_parse_bool
, 0, &arg_no_new_privs
},
566 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
568 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
569 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_default_timer_accuracy_usec
},
570 { "Manager", "DefaultStandardOutput", config_parse_output_restricted
, 0, &arg_default_std_output
},
571 { "Manager", "DefaultStandardError", config_parse_output_restricted
, 0, &arg_default_std_error
},
572 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_default_timeout_start_usec
},
573 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_default_timeout_stop_usec
},
574 { "Manager", "DefaultTimeoutAbortSec", config_parse_timeout_abort
, 0, &arg_default_timeout_abort_set
},
575 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_default_restart_usec
},
576 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_default_start_limit_interval
}, /* obsolete alias */
577 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec
, 0, &arg_default_start_limit_interval
},
578 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_default_start_limit_burst
},
579 { "Manager", "DefaultEnvironment", config_parse_environ
, 0, &arg_default_environment
},
580 { "Manager", "DefaultLimitCPU", config_parse_rlimit
, RLIMIT_CPU
, arg_default_rlimit
},
581 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit
, RLIMIT_FSIZE
, arg_default_rlimit
},
582 { "Manager", "DefaultLimitDATA", config_parse_rlimit
, RLIMIT_DATA
, arg_default_rlimit
},
583 { "Manager", "DefaultLimitSTACK", config_parse_rlimit
, RLIMIT_STACK
, arg_default_rlimit
},
584 { "Manager", "DefaultLimitCORE", config_parse_rlimit
, RLIMIT_CORE
, arg_default_rlimit
},
585 { "Manager", "DefaultLimitRSS", config_parse_rlimit
, RLIMIT_RSS
, arg_default_rlimit
},
586 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit
, RLIMIT_NOFILE
, arg_default_rlimit
},
587 { "Manager", "DefaultLimitAS", config_parse_rlimit
, RLIMIT_AS
, arg_default_rlimit
},
588 { "Manager", "DefaultLimitNPROC", config_parse_rlimit
, RLIMIT_NPROC
, arg_default_rlimit
},
589 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit
, RLIMIT_MEMLOCK
, arg_default_rlimit
},
590 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit
, RLIMIT_LOCKS
, arg_default_rlimit
},
591 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit
, RLIMIT_SIGPENDING
, arg_default_rlimit
},
592 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit
, RLIMIT_MSGQUEUE
, arg_default_rlimit
},
593 { "Manager", "DefaultLimitNICE", config_parse_rlimit
, RLIMIT_NICE
, arg_default_rlimit
},
594 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit
, RLIMIT_RTPRIO
, arg_default_rlimit
},
595 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit
, RLIMIT_RTTIME
, arg_default_rlimit
},
596 { "Manager", "DefaultCPUAccounting", config_parse_tristate
, 0, &arg_default_cpu_accounting
},
597 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_default_io_accounting
},
598 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_default_ip_accounting
},
599 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_default_blockio_accounting
},
600 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_default_memory_accounting
},
601 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_default_tasks_accounting
},
602 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_default_tasks_max
},
603 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, 0, &arg_cad_burst_action
},
604 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy
, 0, &arg_default_oom_policy
},
608 const char *fn
, *conf_dirs_nulstr
;
611 PKGSYSCONFDIR
"/system.conf" :
612 PKGSYSCONFDIR
"/user.conf";
614 conf_dirs_nulstr
= arg_system
?
615 CONF_PATHS_NULSTR("systemd/system.conf.d") :
616 CONF_PATHS_NULSTR("systemd/user.conf.d");
618 (void) config_parse_many_nulstr(fn
, conf_dirs_nulstr
, "Manager\0", config_item_table_lookup
, items
, CONFIG_PARSE_WARN
, NULL
);
620 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we used USEC_INFINITY
621 * like everywhere else. */
622 if (arg_default_timeout_start_usec
<= 0)
623 arg_default_timeout_start_usec
= USEC_INFINITY
;
624 if (arg_default_timeout_stop_usec
<= 0)
625 arg_default_timeout_stop_usec
= USEC_INFINITY
;
630 static void set_manager_defaults(Manager
*m
) {
634 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
635 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
636 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
638 m
->default_timer_accuracy_usec
= arg_default_timer_accuracy_usec
;
639 m
->default_std_output
= arg_default_std_output
;
640 m
->default_std_error
= arg_default_std_error
;
641 m
->default_timeout_start_usec
= arg_default_timeout_start_usec
;
642 m
->default_timeout_stop_usec
= arg_default_timeout_stop_usec
;
643 m
->default_timeout_abort_usec
= arg_default_timeout_abort_usec
;
644 m
->default_timeout_abort_set
= arg_default_timeout_abort_set
;
645 m
->default_restart_usec
= arg_default_restart_usec
;
646 m
->default_start_limit_interval
= arg_default_start_limit_interval
;
647 m
->default_start_limit_burst
= arg_default_start_limit_burst
;
649 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
650 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
651 if (arg_default_cpu_accounting
>= 0)
652 m
->default_cpu_accounting
= arg_default_cpu_accounting
;
654 m
->default_cpu_accounting
= cpu_accounting_is_cheap();
656 m
->default_io_accounting
= arg_default_io_accounting
;
657 m
->default_ip_accounting
= arg_default_ip_accounting
;
658 m
->default_blockio_accounting
= arg_default_blockio_accounting
;
659 m
->default_memory_accounting
= arg_default_memory_accounting
;
660 m
->default_tasks_accounting
= arg_default_tasks_accounting
;
661 m
->default_tasks_max
= arg_default_tasks_max
;
662 m
->default_oom_policy
= arg_default_oom_policy
;
664 (void) manager_set_default_rlimits(m
, arg_default_rlimit
);
666 (void) manager_default_environment(m
);
667 (void) manager_transient_environment_add(m
, arg_default_environment
);
670 static void set_manager_settings(Manager
*m
) {
674 /* Propagates the various manager settings into the manager object, i.e. properties that effect the manager
675 * itself (as opposed to just being inherited into newly allocated units, see set_manager_defaults() above). */
677 m
->confirm_spawn
= arg_confirm_spawn
;
678 m
->service_watchdogs
= arg_service_watchdogs
;
679 m
->runtime_watchdog
= arg_runtime_watchdog
;
680 m
->reboot_watchdog
= arg_reboot_watchdog
;
681 m
->kexec_watchdog
= arg_kexec_watchdog
;
682 m
->cad_burst_action
= arg_cad_burst_action
;
684 manager_set_show_status(m
, arg_show_status
);
685 m
->status_unit_format
= arg_status_unit_format
;
688 static int parse_argv(int argc
, char *argv
[]) {
690 ARG_LOG_LEVEL
= 0x100,
700 ARG_DUMP_CONFIGURATION_ITEMS
,
701 ARG_DUMP_BUS_PROPERTIES
,
710 ARG_DEFAULT_STD_OUTPUT
,
711 ARG_DEFAULT_STD_ERROR
,
713 ARG_SERVICE_WATCHDOGS
,
716 static const struct option options
[] = {
717 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
718 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
719 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
720 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
721 { "unit", required_argument
, NULL
, ARG_UNIT
},
722 { "system", no_argument
, NULL
, ARG_SYSTEM
},
723 { "user", no_argument
, NULL
, ARG_USER
},
724 { "test", no_argument
, NULL
, ARG_TEST
},
725 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
726 { "help", no_argument
, NULL
, 'h' },
727 { "version", no_argument
, NULL
, ARG_VERSION
},
728 { "dump-configuration-items", no_argument
, NULL
, ARG_DUMP_CONFIGURATION_ITEMS
},
729 { "dump-bus-properties", no_argument
, NULL
, ARG_DUMP_BUS_PROPERTIES
},
730 { "dump-core", optional_argument
, NULL
, ARG_DUMP_CORE
},
731 { "crash-chvt", required_argument
, NULL
, ARG_CRASH_CHVT
},
732 { "crash-shell", optional_argument
, NULL
, ARG_CRASH_SHELL
},
733 { "crash-reboot", optional_argument
, NULL
, ARG_CRASH_REBOOT
},
734 { "confirm-spawn", optional_argument
, NULL
, ARG_CONFIRM_SPAWN
},
735 { "show-status", optional_argument
, NULL
, ARG_SHOW_STATUS
},
736 { "deserialize", required_argument
, NULL
, ARG_DESERIALIZE
},
737 { "switched-root", no_argument
, NULL
, ARG_SWITCHED_ROOT
},
738 { "default-standard-output", required_argument
, NULL
, ARG_DEFAULT_STD_OUTPUT
, },
739 { "default-standard-error", required_argument
, NULL
, ARG_DEFAULT_STD_ERROR
, },
740 { "machine-id", required_argument
, NULL
, ARG_MACHINE_ID
},
741 { "service-watchdogs", required_argument
, NULL
, ARG_SERVICE_WATCHDOGS
},
750 if (getpid_cached() == 1)
753 while ((c
= getopt_long(argc
, argv
, "hDbsz:", options
, NULL
)) >= 0)
758 r
= log_set_max_level_from_string(optarg
);
760 return log_error_errno(r
, "Failed to parse log level \"%s\": %m", optarg
);
765 r
= log_set_target_from_string(optarg
);
767 return log_error_errno(r
, "Failed to parse log target \"%s\": %m", optarg
);
774 r
= log_show_color_from_string(optarg
);
776 return log_error_errno(r
, "Failed to parse log color setting \"%s\": %m",
779 log_show_color(true);
783 case ARG_LOG_LOCATION
:
785 r
= log_show_location_from_string(optarg
);
787 return log_error_errno(r
, "Failed to parse log location setting \"%s\": %m",
790 log_show_location(true);
794 case ARG_DEFAULT_STD_OUTPUT
:
795 r
= exec_output_from_string(optarg
);
797 return log_error_errno(r
, "Failed to parse default standard output setting \"%s\": %m",
799 arg_default_std_output
= r
;
802 case ARG_DEFAULT_STD_ERROR
:
803 r
= exec_output_from_string(optarg
);
805 return log_error_errno(r
, "Failed to parse default standard error output setting \"%s\": %m",
807 arg_default_std_error
= r
;
811 r
= free_and_strdup(&arg_default_unit
, optarg
);
813 return log_error_errno(r
, "Failed to set default unit \"%s\": %m", optarg
);
826 arg_action
= ACTION_TEST
;
830 arg_pager_flags
|= PAGER_DISABLE
;
834 arg_action
= ACTION_VERSION
;
837 case ARG_DUMP_CONFIGURATION_ITEMS
:
838 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
841 case ARG_DUMP_BUS_PROPERTIES
:
842 arg_action
= ACTION_DUMP_BUS_PROPERTIES
;
847 arg_dump_core
= true;
849 r
= parse_boolean(optarg
);
851 return log_error_errno(r
, "Failed to parse dump core boolean: \"%s\": %m",
858 r
= parse_crash_chvt(optarg
, &arg_crash_chvt
);
860 return log_error_errno(r
, "Failed to parse crash virtual terminal index: \"%s\": %m",
864 case ARG_CRASH_SHELL
:
866 arg_crash_shell
= true;
868 r
= parse_boolean(optarg
);
870 return log_error_errno(r
, "Failed to parse crash shell boolean: \"%s\": %m",
876 case ARG_CRASH_REBOOT
:
878 arg_crash_reboot
= true;
880 r
= parse_boolean(optarg
);
882 return log_error_errno(r
, "Failed to parse crash shell boolean: \"%s\": %m",
884 arg_crash_reboot
= r
;
888 case ARG_CONFIRM_SPAWN
:
889 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
891 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
893 return log_error_errno(r
, "Failed to parse confirm spawn option: \"%s\": %m",
897 case ARG_SERVICE_WATCHDOGS
:
898 r
= parse_boolean(optarg
);
900 return log_error_errno(r
, "Failed to parse service watchdogs boolean: \"%s\": %m",
902 arg_service_watchdogs
= r
;
905 case ARG_SHOW_STATUS
:
907 r
= parse_show_status(optarg
, &arg_show_status
);
909 return log_error_errno(r
, "Failed to parse show status boolean: \"%s\": %m",
912 arg_show_status
= SHOW_STATUS_YES
;
915 case ARG_DESERIALIZE
: {
919 r
= safe_atoi(optarg
, &fd
);
921 log_error_errno(r
, "Failed to parse deserialize option \"%s\": %m", optarg
);
923 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
924 "Invalid deserialize fd: %d",
927 (void) fd_cloexec(fd
, true);
931 return log_error_errno(errno
, "Failed to open serialization fd %d: %m", fd
);
933 safe_fclose(arg_serialization
);
934 arg_serialization
= f
;
939 case ARG_SWITCHED_ROOT
:
940 arg_switched_root
= true;
944 r
= set_machine_id(optarg
);
946 return log_error_errno(r
, "MachineID '%s' is not valid: %m", optarg
);
950 arg_action
= ACTION_HELP
;
954 log_set_max_level(LOG_DEBUG
);
960 /* Just to eat away the sysvinit kernel
961 * cmdline args without getopt() error
962 * messages that we'll parse in
963 * parse_proc_cmdline_word() or ignore. */
966 if (getpid_cached() != 1)
972 assert_not_reached("Unhandled option code.");
975 if (optind
< argc
&& getpid_cached() != 1) {
976 /* Hmm, when we aren't run as init system
977 * let's complain about excess arguments */
979 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
980 "Excess arguments.");
986 static int help(void) {
987 _cleanup_free_
char *link
= NULL
;
990 r
= terminal_urlify_man("systemd", "1", &link
);
994 printf("%s [OPTIONS...]\n\n"
995 "Starts up and maintains the system or user services.\n\n"
996 " -h --help Show this help\n"
997 " --version Show version\n"
998 " --test Determine initial transaction, dump it and exit\n"
999 " --system In combination with --test: operate as system service manager\n"
1000 " --user In combination with --test: operate as per-user service manager\n"
1001 " --no-pager Do not pipe output into a pager\n"
1002 " --dump-configuration-items Dump understood unit configuration items\n"
1003 " --dump-bus-properties Dump exposed bus properties\n"
1004 " --unit=UNIT Set default unit\n"
1005 " --dump-core[=BOOL] Dump core on crash\n"
1006 " --crash-vt=NR Change to specified VT on crash\n"
1007 " --crash-reboot[=BOOL] Reboot on crash\n"
1008 " --crash-shell[=BOOL] Run shell on crash\n"
1009 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1010 " --show-status[=BOOL] Show status updates on the console during bootup\n"
1011 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
1012 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1013 " --log-color[=BOOL] Highlight important log messages\n"
1014 " --log-location[=BOOL] Include code location in log messages\n"
1015 " --default-standard-output= Set default standard output for services\n"
1016 " --default-standard-error= Set default standard error output for services\n"
1017 "\nSee the %s for details.\n"
1018 , program_invocation_short_name
1025 static int prepare_reexecute(
1029 bool switching_root
) {
1031 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1032 _cleanup_fclose_
FILE *f
= NULL
;
1039 r
= manager_open_serialization(m
, &f
);
1041 return log_error_errno(r
, "Failed to create serialization file: %m");
1043 /* Make sure nothing is really destructed when we shut down */
1045 bus_manager_send_reloading(m
, true);
1051 r
= manager_serialize(m
, f
, fds
, switching_root
);
1055 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1056 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1058 r
= fd_cloexec(fileno(f
), false);
1060 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1062 r
= fdset_cloexec(fds
, false);
1064 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1066 *ret_f
= TAKE_PTR(f
);
1067 *ret_fds
= TAKE_PTR(fds
);
1072 static void bump_file_max_and_nr_open(void) {
1074 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large numbers of file
1075 * descriptors are no longer a performance problem and their memory is properly tracked by memcg, thus counting
1076 * them and limiting them in another two layers of limits is unnecessary and just complicates things. This
1077 * function hence turns off 2 of the 4 levels of limits on file descriptors, and makes RLIMIT_NOLIMIT (soft +
1078 * hard) the only ones that really matter. */
1080 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1084 #if BUMP_PROC_SYS_FS_FILE_MAX
1085 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously thing where
1086 * different but the operation would fail silently.) */
1087 r
= sysctl_writef("fs/file-max", "%li\n", LONG_MAX
);
1089 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.file-max, ignoring: %m");
1092 #if BUMP_PROC_SYS_FS_NR_OPEN
1095 /* Arg! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know what they
1096 * are. The expression by which the maximum is determined is dependent on the architecture, and is something we
1097 * don't really want to copy to userspace, as it is dependent on implementation details of the kernel. Since
1098 * the kernel doesn't expose the maximum value to us, we can only try and hope. Hence, let's start with
1099 * INT_MAX, and then keep halving the value until we find one that works. Ugly? Yes, absolutely, but kernel
1100 * APIs are kernel APIs, so what do can we do... 🤯 */
1105 v
&= ~(__SIZEOF_POINTER__
- 1); /* Round down to next multiple of the pointer size */
1107 log_warning("Can't bump fs.nr_open, value too small.");
1113 log_error_errno(k
, "Failed to read fs.nr_open: %m");
1116 if (k
>= v
) { /* Already larger */
1117 log_debug("Skipping bump, value is already larger.");
1121 r
= sysctl_writef("fs/nr_open", "%i\n", v
);
1123 log_debug("Couldn't write fs.nr_open as %i, halving it.", v
);
1128 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.nr_open, ignoring: %m");
1132 log_debug("Successfully bumped fs.nr_open to %i", v
);
1138 static int bump_rlimit_nofile(struct rlimit
*saved_rlimit
) {
1139 struct rlimit new_rlimit
;
1142 /* Get the underlying absolute limit the kernel enforces */
1143 nr
= read_nr_open();
1145 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1146 new_rlimit
= (struct rlimit
) {
1147 .rlim_cur
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_cur
),
1148 .rlim_max
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_max
),
1151 /* Shortcut if nothing changes. */
1152 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_max
&&
1153 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_cur
) {
1154 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1158 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1159 * both hard and soft. */
1160 r
= setrlimit_closest(RLIMIT_NOFILE
, &new_rlimit
);
1162 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1167 static int bump_rlimit_memlock(struct rlimit
*saved_rlimit
) {
1168 struct rlimit new_rlimit
;
1171 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK which should
1172 * normally disable such checks. We need them to implement IPAccessAllow= and IPAccessDeny=, hence let's bump
1173 * the value high enough for our user. */
1175 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1176 * must be unsigned, hence this is a given, but let's make this clear here. */
1177 assert_cc(RLIM_INFINITY
> 0);
1179 new_rlimit
= (struct rlimit
) {
1180 .rlim_cur
= MAX(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_cur
),
1181 .rlim_max
= MAX(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_max
),
1184 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_cur
&&
1185 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_max
) {
1186 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1190 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &new_rlimit
);
1192 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1197 static void test_usr(void) {
1199 /* Check that /usr is either on the same file system as / or mounted already. */
1201 if (dir_is_empty("/usr") <= 0)
1204 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1205 "Some things will probably break (sometimes even silently) in mysterious ways. "
1206 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1209 static int enforce_syscall_archs(Set
*archs
) {
1213 if (!is_seccomp_available())
1216 r
= seccomp_restrict_archs(arg_syscall_archs
);
1218 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1223 static int status_welcome(void) {
1224 _cleanup_free_
char *pretty_name
= NULL
, *ansi_color
= NULL
;
1227 if (IN_SET(arg_show_status
, SHOW_STATUS_NO
, SHOW_STATUS_AUTO
))
1230 r
= parse_os_release(NULL
,
1231 "PRETTY_NAME", &pretty_name
,
1232 "ANSI_COLOR", &ansi_color
,
1235 log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1236 "Failed to read os-release file, ignoring: %m");
1238 if (log_get_show_color())
1239 return status_printf(NULL
, 0,
1240 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1241 isempty(ansi_color
) ? "1" : ansi_color
,
1242 isempty(pretty_name
) ? "Linux" : pretty_name
);
1244 return status_printf(NULL
, 0,
1245 "\nWelcome to %s!\n",
1246 isempty(pretty_name
) ? "Linux" : pretty_name
);
1249 static int write_container_id(void) {
1253 c
= getenv("container");
1257 RUN_WITH_UMASK(0022)
1258 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1260 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1265 static int bump_unix_max_dgram_qlen(void) {
1266 _cleanup_free_
char *qlen
= NULL
;
1270 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set the value
1271 * really really early during boot, so that it is actually applied to all our sockets, including the
1272 * $NOTIFY_SOCKET one. */
1274 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1276 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1278 r
= safe_atolu(qlen
, &v
);
1280 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen
);
1282 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1285 r
= write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER
, "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN
);
1287 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1288 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1293 static int fixup_environment(void) {
1294 _cleanup_free_
char *term
= NULL
;
1298 /* Only fix up the environment when we are started as PID 1 */
1299 if (getpid_cached() != 1)
1302 /* We expect the environment to be set correctly if run inside a container. */
1303 if (detect_container() > 0)
1306 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the backend
1307 * device used by the console. We try to make a better guess here since some consoles might not have support
1308 * for color mode for example.
1310 * However if TERM was configured through the kernel command line then leave it alone. */
1311 r
= proc_cmdline_get_key("TERM", 0, &term
);
1315 t
= term
?: default_term_for_tty("/dev/console");
1317 if (setenv("TERM", t
, 1) < 0)
1320 /* The kernels sets HOME=/ for init. Let's undo this. */
1321 if (path_equal_ptr(getenv("HOME"), "/") &&
1322 unsetenv("HOME") < 0)
1323 log_warning_errno(errno
, "Failed to unset $HOME: %m");
1328 static void redirect_telinit(int argc
, char *argv
[]) {
1330 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1332 #if HAVE_SYSV_COMPAT
1333 if (getpid_cached() == 1)
1336 if (!strstr(program_invocation_short_name
, "init"))
1339 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1340 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1345 static int become_shutdown(
1346 const char *shutdown_verb
,
1349 char log_level
[DECIMAL_STR_MAX(int) + 1],
1350 exit_code
[DECIMAL_STR_MAX(uint8_t) + 1],
1351 timeout
[DECIMAL_STR_MAX(usec_t
) + 1];
1353 const char* command_line
[13] = {
1354 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1356 "--timeout", timeout
,
1357 "--log-level", log_level
,
1361 _cleanup_strv_free_
char **env_block
= NULL
;
1364 usec_t watchdog_timer
= 0;
1366 assert(shutdown_verb
);
1367 assert(!command_line
[pos
]);
1368 env_block
= strv_copy(environ
);
1370 xsprintf(log_level
, "%d", log_get_max_level());
1371 xsprintf(timeout
, "%" PRI_USEC
"us", arg_default_timeout_stop_usec
);
1373 switch (log_get_target()) {
1375 case LOG_TARGET_KMSG
:
1376 case LOG_TARGET_JOURNAL_OR_KMSG
:
1377 case LOG_TARGET_SYSLOG_OR_KMSG
:
1378 command_line
[pos
++] = "kmsg";
1381 case LOG_TARGET_NULL
:
1382 command_line
[pos
++] = "null";
1385 case LOG_TARGET_CONSOLE
:
1387 command_line
[pos
++] = "console";
1391 if (log_get_show_color())
1392 command_line
[pos
++] = "--log-color";
1394 if (log_get_show_location())
1395 command_line
[pos
++] = "--log-location";
1397 if (streq(shutdown_verb
, "exit")) {
1398 command_line
[pos
++] = "--exit-code";
1399 command_line
[pos
++] = exit_code
;
1400 xsprintf(exit_code
, "%d", retval
);
1403 assert(pos
< ELEMENTSOF(command_line
));
1405 if (streq(shutdown_verb
, "reboot"))
1406 watchdog_timer
= arg_reboot_watchdog
;
1407 else if (streq(shutdown_verb
, "kexec"))
1408 watchdog_timer
= arg_kexec_watchdog
;
1410 if (watchdog_timer
> 0 && watchdog_timer
!= USEC_INFINITY
) {
1414 /* If we reboot or kexec let's set the shutdown
1415 * watchdog and tell the shutdown binary to
1416 * repeatedly ping it */
1417 r
= watchdog_set_timeout(&watchdog_timer
);
1418 watchdog_close(r
< 0);
1420 /* Tell the binary how often to ping, ignore failure */
1421 if (asprintf(&e
, "WATCHDOG_USEC="USEC_FMT
, watchdog_timer
) > 0)
1422 (void) strv_consume(&env_block
, e
);
1424 if (arg_watchdog_device
&&
1425 asprintf(&e
, "WATCHDOG_DEVICE=%s", arg_watchdog_device
) > 0)
1426 (void) strv_consume(&env_block
, e
);
1428 watchdog_close(true);
1430 /* Avoid the creation of new processes forked by the
1431 * kernel; at this point, we will not listen to the
1433 if (detect_container() <= 0)
1434 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1436 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1440 static void initialize_clock(void) {
1443 if (clock_is_localtime(NULL
) > 0) {
1447 * The very first call of settimeofday() also does a time warp in the kernel.
1449 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to take care
1450 * of maintaining the RTC and do all adjustments. This matches the behavior of Windows, which leaves
1451 * the RTC alone if the registry tells that the RTC runs in UTC.
1453 r
= clock_set_timezone(&min
);
1455 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1457 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1459 } else if (!in_initrd()) {
1461 * Do a dummy very first call to seal the kernel's time warp magic.
1463 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with LOCAL, but the
1464 * real system could be set up that way. In such case, we need to delay the time-warp or the sealing
1465 * until we reach the real system.
1467 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably, the time
1468 * will jump or be incorrect at every daylight saving time change. All kernel local time concepts will
1469 * be treated as UTC that way.
1471 (void) clock_reset_timewarp();
1474 r
= clock_apply_epoch();
1476 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1478 log_info("System time before build time, advancing clock.");
1481 static void initialize_coredump(bool skip_setup
) {
1483 if (getpid_cached() != 1)
1486 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1487 * will process core dumps for system services by default. */
1488 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1489 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1491 /* But at the same time, turn off the core_pattern logic by default, so that no
1492 * coredumps are stored until the systemd-coredump tool is enabled via
1493 * sysctl. However it can be changed via the kernel command line later so core
1494 * dumps can still be generated during early startup and in initramfs. */
1496 disable_coredumps();
1500 static void initialize_core_pattern(bool skip_setup
) {
1503 if (skip_setup
|| !arg_early_core_pattern
)
1506 if (getpid_cached() != 1)
1509 r
= write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1511 log_warning_errno(r
, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m", arg_early_core_pattern
);
1514 static void update_cpu_affinity(bool skip_setup
) {
1515 _cleanup_free_
char *mask
= NULL
;
1517 if (skip_setup
|| !arg_cpu_affinity
.set
)
1520 assert(arg_cpu_affinity
.allocated
> 0);
1522 mask
= cpu_set_to_string(&arg_cpu_affinity
);
1523 log_debug("Setting CPU affinity to %s.", strnull(mask
));
1525 if (sched_setaffinity(0, arg_cpu_affinity
.allocated
, arg_cpu_affinity
.set
) < 0)
1526 log_warning_errno(errno
, "Failed to set CPU affinity: %m");
1529 static void update_numa_policy(bool skip_setup
) {
1531 _cleanup_free_
char *nodes
= NULL
;
1532 const char * policy
= NULL
;
1534 if (skip_setup
|| !mpol_is_valid(numa_policy_get_type(&arg_numa_policy
)))
1537 if (DEBUG_LOGGING
) {
1538 policy
= mpol_to_string(numa_policy_get_type(&arg_numa_policy
));
1539 nodes
= cpu_set_to_range_string(&arg_numa_policy
.nodes
);
1540 log_debug("Setting NUMA policy to %s, with nodes %s.", strnull(policy
), strnull(nodes
));
1543 r
= apply_numa_policy(&arg_numa_policy
);
1544 if (r
== -EOPNOTSUPP
)
1545 log_debug_errno(r
, "NUMA support not available, ignoring.");
1547 log_warning_errno(r
, "Failed to set NUMA memory policy: %m");
1550 static void do_reexecute(
1553 const struct rlimit
*saved_rlimit_nofile
,
1554 const struct rlimit
*saved_rlimit_memlock
,
1556 const char *switch_root_dir
,
1557 const char *switch_root_init
,
1558 const char **ret_error_message
) {
1560 unsigned i
, j
, args_size
;
1564 assert(saved_rlimit_nofile
);
1565 assert(saved_rlimit_memlock
);
1566 assert(ret_error_message
);
1568 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get rebooted while
1570 watchdog_close(true);
1572 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1573 * the kernel default to its child processes */
1574 if (saved_rlimit_nofile
->rlim_cur
!= 0)
1575 (void) setrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
);
1576 if (saved_rlimit_memlock
->rlim_cur
!= RLIM_INFINITY
)
1577 (void) setrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
);
1579 if (switch_root_dir
) {
1580 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
1581 * SIGCHLD for them after deserializing. */
1582 broadcast_signal(SIGTERM
, false, true, arg_default_timeout_stop_usec
);
1584 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1585 r
= switch_root(switch_root_dir
, "/mnt", true, MS_MOVE
);
1587 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
1590 args_size
= MAX(6, argc
+1);
1591 args
= newa(const char*, args_size
);
1593 if (!switch_root_init
) {
1594 char sfd
[DECIMAL_STR_MAX(int) + 1];
1596 /* First try to spawn ourselves with the right path, and with full serialization. We do this only if
1597 * the user didn't specify an explicit init to spawn. */
1599 assert(arg_serialization
);
1602 xsprintf(sfd
, "%i", fileno(arg_serialization
));
1605 args
[i
++] = SYSTEMD_BINARY_PATH
;
1606 if (switch_root_dir
)
1607 args
[i
++] = "--switched-root";
1608 args
[i
++] = arg_system
? "--system" : "--user";
1609 args
[i
++] = "--deserialize";
1613 assert(i
<= args_size
);
1616 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do this is on
1617 * its own on exec(), but it will do it on exit(). Hence, to ensure we get a summary here, fork() off
1618 * a child, let it exit() cleanly, so that it prints the summary, and wait() for it in the parent,
1619 * before proceeding into the exec().
1621 valgrind_summary_hack();
1623 (void) execv(args
[0], (char* const*) args
);
1624 log_debug_errno(errno
, "Failed to execute our own binary, trying fallback: %m");
1627 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and envp[]. (Well,
1628 * modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[], but let's hope that
1629 * doesn't matter.) */
1631 arg_serialization
= safe_fclose(arg_serialization
);
1632 fds
= fdset_free(fds
);
1634 /* Reopen the console */
1635 (void) make_console_stdio();
1637 for (j
= 1, i
= 1; j
< (unsigned) argc
; j
++)
1638 args
[i
++] = argv
[j
];
1640 assert(i
<= args_size
);
1642 /* Re-enable any blocked signals, especially important if we switch from initial ramdisk to init=... */
1643 (void) reset_all_signal_handlers();
1644 (void) reset_signal_mask();
1645 (void) rlimit_nofile_safe();
1647 if (switch_root_init
) {
1648 args
[0] = switch_root_init
;
1649 (void) execv(args
[0], (char* const*) args
);
1650 log_warning_errno(errno
, "Failed to execute configured init, trying fallback: %m");
1653 args
[0] = "/sbin/init";
1654 (void) execv(args
[0], (char* const*) args
);
1657 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
1658 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
1659 "Failed to execute /sbin/init");
1662 log_warning("No /sbin/init, trying fallback");
1664 args
[0] = "/bin/sh";
1666 (void) execv(args
[0], (char* const*) args
);
1667 log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
1669 log_warning_errno(r
, "Failed to execute /sbin/init, giving up: %m");
1671 *ret_error_message
= "Failed to execute fallback shell";
1674 static int invoke_main_loop(
1676 const struct rlimit
*saved_rlimit_nofile
,
1677 const struct rlimit
*saved_rlimit_memlock
,
1678 bool *ret_reexecute
,
1679 int *ret_retval
, /* Return parameters relevant for shutting down */
1680 const char **ret_shutdown_verb
, /* … */
1681 FDSet
**ret_fds
, /* Return parameters for reexecuting */
1682 char **ret_switch_root_dir
, /* … */
1683 char **ret_switch_root_init
, /* … */
1684 const char **ret_error_message
) {
1689 assert(saved_rlimit_nofile
);
1690 assert(saved_rlimit_memlock
);
1691 assert(ret_reexecute
);
1693 assert(ret_shutdown_verb
);
1695 assert(ret_switch_root_dir
);
1696 assert(ret_switch_root_init
);
1697 assert(ret_error_message
);
1700 r
= manager_loop(m
);
1702 *ret_error_message
= "Failed to run main loop";
1703 return log_emergency_errno(r
, "Failed to run main loop: %m");
1706 switch ((ManagerObjective
) r
) {
1708 case MANAGER_RELOAD
: {
1709 LogTarget saved_log_target
;
1710 int saved_log_level
;
1712 log_info("Reloading.");
1714 /* First, save any overridden log level/target, then parse the configuration file, which might
1715 * change the log level to new settings. */
1717 saved_log_level
= m
->log_level_overridden
? log_get_max_level() : -1;
1718 saved_log_target
= m
->log_target_overridden
? log_get_target() : _LOG_TARGET_INVALID
;
1720 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
1722 set_manager_defaults(m
);
1724 update_cpu_affinity(false);
1725 update_numa_policy(false);
1727 if (saved_log_level
>= 0)
1728 manager_override_log_level(m
, saved_log_level
);
1729 if (saved_log_target
>= 0)
1730 manager_override_log_target(m
, saved_log_target
);
1732 r
= manager_reload(m
);
1734 /* Reloading failed before the point of no return. Let's continue running as if nothing happened. */
1735 m
->objective
= MANAGER_OK
;
1740 case MANAGER_REEXECUTE
:
1742 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, false);
1744 *ret_error_message
= "Failed to prepare for reexecution";
1748 log_notice("Reexecuting.");
1750 *ret_reexecute
= true;
1751 *ret_retval
= EXIT_SUCCESS
;
1752 *ret_shutdown_verb
= NULL
;
1753 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1757 case MANAGER_SWITCH_ROOT
:
1758 if (!m
->switch_root_init
) {
1759 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, true);
1761 *ret_error_message
= "Failed to prepare for reexecution";
1767 log_notice("Switching root.");
1769 *ret_reexecute
= true;
1770 *ret_retval
= EXIT_SUCCESS
;
1771 *ret_shutdown_verb
= NULL
;
1773 /* Steal the switch root parameters */
1774 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
1775 *ret_switch_root_init
= TAKE_PTR(m
->switch_root_init
);
1781 if (MANAGER_IS_USER(m
)) {
1784 *ret_reexecute
= false;
1785 *ret_retval
= m
->return_value
;
1786 *ret_shutdown_verb
= NULL
;
1788 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1794 case MANAGER_REBOOT
:
1795 case MANAGER_POWEROFF
:
1797 case MANAGER_KEXEC
: {
1798 static const char * const table
[_MANAGER_OBJECTIVE_MAX
] = {
1799 [MANAGER_EXIT
] = "exit",
1800 [MANAGER_REBOOT
] = "reboot",
1801 [MANAGER_POWEROFF
] = "poweroff",
1802 [MANAGER_HALT
] = "halt",
1803 [MANAGER_KEXEC
] = "kexec",
1806 log_notice("Shutting down.");
1808 *ret_reexecute
= false;
1809 *ret_retval
= m
->return_value
;
1810 assert_se(*ret_shutdown_verb
= table
[m
->objective
]);
1812 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
1818 assert_not_reached("Unknown or unexpected manager objective.");
1823 static void log_execution_mode(bool *ret_first_boot
) {
1824 assert(ret_first_boot
);
1829 log_info("systemd " GIT_VERSION
" running in %ssystem mode. (" SYSTEMD_FEATURES
")",
1830 arg_action
== ACTION_TEST
? "test " : "" );
1832 v
= detect_virtualization();
1834 log_info("Detected virtualization %s.", virtualization_to_string(v
));
1836 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
1839 *ret_first_boot
= false;
1840 log_info("Running in initial RAM disk.");
1842 /* Let's check whether we are in first boot, i.e. whether /etc is still unpopulated. We use
1843 * /etc/machine-id as flag file, for this: if it exists we assume /etc is populated, if it
1844 * doesn't it's unpopulated. This allows container managers and installers to provision a
1845 * couple of files already. If the container manager wants to provision the machine ID itself
1846 * it should pass $container_uuid to PID 1. */
1848 *ret_first_boot
= access("/etc/machine-id", F_OK
) < 0;
1849 if (*ret_first_boot
)
1850 log_info("Running with unpopulated /etc.");
1853 if (DEBUG_LOGGING
) {
1854 _cleanup_free_
char *t
;
1856 t
= uid_to_name(getuid());
1857 log_debug("systemd " GIT_VERSION
" running in %suser mode for user " UID_FMT
"/%s. (" SYSTEMD_FEATURES
")",
1858 arg_action
== ACTION_TEST
? " test" : "", getuid(), strna(t
));
1861 *ret_first_boot
= false;
1865 static int initialize_runtime(
1867 struct rlimit
*saved_rlimit_nofile
,
1868 struct rlimit
*saved_rlimit_memlock
,
1869 const char **ret_error_message
) {
1872 assert(ret_error_message
);
1874 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
1876 * - Some only apply to --system instances
1877 * - Some only apply to --user instances
1878 * - Some only apply when we first start up, but not when we reexecute
1881 if (arg_action
!= ACTION_RUN
)
1884 update_cpu_affinity(skip_setup
);
1885 update_numa_policy(skip_setup
);
1888 /* Make sure we leave a core dump without panicking the kernel. */
1889 install_crash_handler();
1892 r
= mount_cgroup_controllers();
1894 *ret_error_message
= "Failed to mount cgroup hierarchies";
1900 machine_id_setup(NULL
, arg_machine_id
, NULL
);
1902 bump_unix_max_dgram_qlen();
1903 bump_file_max_and_nr_open();
1905 write_container_id();
1908 if (arg_watchdog_device
) {
1909 r
= watchdog_set_device(arg_watchdog_device
);
1911 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device
);
1914 if (timestamp_is_set(arg_runtime_watchdog
))
1915 watchdog_set_timeout(&arg_runtime_watchdog
);
1918 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
1919 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
1920 log_warning_errno(errno
, "Failed to adjust timer slack, ignoring: %m");
1922 if (arg_system
&& !cap_test_all(arg_capability_bounding_set
)) {
1923 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
1925 *ret_error_message
= "Failed to drop capability bounding set of usermode helpers";
1926 return log_emergency_errno(r
, "Failed to drop capability bounding set of usermode helpers: %m");
1929 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
1931 *ret_error_message
= "Failed to drop capability bounding set";
1932 return log_emergency_errno(r
, "Failed to drop capability bounding set: %m");
1936 if (arg_system
&& arg_no_new_privs
) {
1937 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
1938 *ret_error_message
= "Failed to disable new privileges";
1939 return log_emergency_errno(errno
, "Failed to disable new privileges: %m");
1943 if (arg_syscall_archs
) {
1944 r
= enforce_syscall_archs(arg_syscall_archs
);
1946 *ret_error_message
= "Failed to set syscall architectures";
1952 /* Become reaper of our children */
1953 if (prctl(PR_SET_CHILD_SUBREAPER
, 1) < 0)
1954 log_warning_errno(errno
, "Failed to make us a subreaper: %m");
1956 /* Bump up RLIMIT_NOFILE for systemd itself */
1957 (void) bump_rlimit_nofile(saved_rlimit_nofile
);
1958 (void) bump_rlimit_memlock(saved_rlimit_memlock
);
1963 static int do_queue_default_job(
1965 const char **ret_error_message
) {
1967 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1968 Job
*default_unit_job
;
1969 Unit
*target
= NULL
;
1972 log_debug("Activating default unit: %s", arg_default_unit
);
1974 r
= manager_load_startable_unit_or_warn(m
, arg_default_unit
, NULL
, &target
);
1976 log_info("Falling back to rescue target: " SPECIAL_RESCUE_TARGET
);
1978 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_RESCUE_TARGET
, NULL
, &target
);
1980 *ret_error_message
= r
== -ERFKILL
? "Rescue target masked"
1981 : "Failed to load rescue target";
1986 assert(target
->load_state
== UNIT_LOADED
);
1988 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, NULL
, &error
, &default_unit_job
);
1990 log_debug_errno(r
, "Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
1992 sd_bus_error_free(&error
);
1994 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, NULL
, &error
, &default_unit_job
);
1996 *ret_error_message
= "Failed to start default target";
1997 return log_emergency_errno(r
, "Failed to start default target: %s", bus_error_message(&error
, r
));
2001 *ret_error_message
= "Failed to isolate default target";
2002 return log_emergency_errno(r
, "Failed to isolate default target: %s", bus_error_message(&error
, r
));
2005 m
->default_unit_job_id
= default_unit_job
->id
;
2010 static void save_rlimits(struct rlimit
*saved_rlimit_nofile
,
2011 struct rlimit
*saved_rlimit_memlock
) {
2013 assert(saved_rlimit_nofile
);
2014 assert(saved_rlimit_memlock
);
2016 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
) < 0)
2017 log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2019 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
) < 0)
2020 log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2023 static void fallback_rlimit_nofile(const struct rlimit
*saved_rlimit_nofile
) {
2026 if (arg_default_rlimit
[RLIMIT_NOFILE
])
2029 /* Make sure forked processes get limits based on the original kernel setting */
2031 rl
= newdup(struct rlimit
, saved_rlimit_nofile
, 1);
2037 /* Bump the hard limit for system services to a substantially higher value. The default
2038 * hard limit current kernels set is pretty low (4K), mostly for historical
2039 * reasons. According to kernel developers, the fd handling in recent kernels has been
2040 * optimized substantially enough, so that we can bump the limit now, without paying too
2041 * high a price in memory or performance. Note however that we only bump the hard limit,
2042 * not the soft limit. That's because select() works the way it works, and chokes on fds
2043 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2044 * unexpecting programs that they get fds higher than what they can process using
2045 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2046 * this pitfall: programs that are written by folks aware of the select() problem in mind
2047 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2048 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2053 /* Get the underlying absolute limit the kernel enforces */
2054 nr
= read_nr_open();
2056 rl
->rlim_max
= MIN((rlim_t
) nr
, MAX(rl
->rlim_max
, (rlim_t
) HIGH_RLIMIT_NOFILE
));
2059 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2060 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2061 * instance), then lower what we pass on to not confuse our children */
2062 rl
->rlim_cur
= MIN(rl
->rlim_cur
, (rlim_t
) FD_SETSIZE
);
2064 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
2067 static void fallback_rlimit_memlock(const struct rlimit
*saved_rlimit_memlock
) {
2070 /* Pass the original value down to invoked processes */
2072 if (arg_default_rlimit
[RLIMIT_MEMLOCK
])
2075 rl
= newdup(struct rlimit
, saved_rlimit_memlock
, 1);
2081 arg_default_rlimit
[RLIMIT_MEMLOCK
] = rl
;
2084 static void reset_arguments(void) {
2085 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2087 arg_default_unit
= mfree(arg_default_unit
);
2089 /* arg_system — ignore */
2091 arg_dump_core
= true;
2092 arg_crash_chvt
= -1;
2093 arg_crash_shell
= false;
2094 arg_crash_reboot
= false;
2095 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2096 arg_show_status
= _SHOW_STATUS_INVALID
;
2097 arg_status_unit_format
= STATUS_UNIT_FORMAT_DEFAULT
;
2098 arg_switched_root
= false;
2099 arg_pager_flags
= 0;
2100 arg_service_watchdogs
= true;
2101 arg_default_std_output
= EXEC_OUTPUT_JOURNAL
;
2102 arg_default_std_error
= EXEC_OUTPUT_INHERIT
;
2103 arg_default_restart_usec
= DEFAULT_RESTART_USEC
;
2104 arg_default_timeout_start_usec
= DEFAULT_TIMEOUT_USEC
;
2105 arg_default_timeout_stop_usec
= DEFAULT_TIMEOUT_USEC
;
2106 arg_default_timeout_abort_usec
= DEFAULT_TIMEOUT_USEC
;
2107 arg_default_timeout_abort_set
= false;
2108 arg_default_start_limit_interval
= DEFAULT_START_LIMIT_INTERVAL
;
2109 arg_default_start_limit_burst
= DEFAULT_START_LIMIT_BURST
;
2110 arg_runtime_watchdog
= 0;
2111 arg_reboot_watchdog
= 10 * USEC_PER_MINUTE
;
2112 arg_kexec_watchdog
= 0;
2113 arg_early_core_pattern
= NULL
;
2114 arg_watchdog_device
= NULL
;
2116 arg_default_environment
= strv_free(arg_default_environment
);
2117 rlimit_free_all(arg_default_rlimit
);
2119 arg_capability_bounding_set
= CAP_ALL
;
2120 arg_no_new_privs
= false;
2121 arg_timer_slack_nsec
= NSEC_INFINITY
;
2122 arg_default_timer_accuracy_usec
= 1 * USEC_PER_MINUTE
;
2124 arg_syscall_archs
= set_free(arg_syscall_archs
);
2126 /* arg_serialization — ignore */
2128 arg_default_cpu_accounting
= -1;
2129 arg_default_io_accounting
= false;
2130 arg_default_ip_accounting
= false;
2131 arg_default_blockio_accounting
= false;
2132 arg_default_memory_accounting
= MEMORY_ACCOUNTING_DEFAULT
;
2133 arg_default_tasks_accounting
= true;
2134 arg_default_tasks_max
= UINT64_MAX
;
2135 arg_machine_id
= (sd_id128_t
) {};
2136 arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
2137 arg_default_oom_policy
= OOM_STOP
;
2139 cpu_set_reset(&arg_cpu_affinity
);
2140 numa_policy_reset(&arg_numa_policy
);
2143 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
2144 const struct rlimit
*saved_rlimit_memlock
) {
2147 assert(saved_rlimit_nofile
);
2148 assert(saved_rlimit_memlock
);
2150 arg_default_tasks_max
= system_tasks_max_scale(DEFAULT_TASKS_MAX_PERCENTAGE
, 100U);
2152 /* Assign configuration defaults */
2155 r
= parse_config_file();
2157 log_warning_errno(r
, "Failed to parse config file, ignoring: %m");
2160 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
2162 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2165 /* Initialize some default rlimits for services if they haven't been configured */
2166 fallback_rlimit_nofile(saved_rlimit_nofile
);
2167 fallback_rlimit_memlock(saved_rlimit_memlock
);
2169 /* Note that this also parses bits from the kernel command line, including "debug". */
2170 log_parse_environment();
2175 static int load_configuration(
2178 const struct rlimit
*saved_rlimit_nofile
,
2179 const struct rlimit
*saved_rlimit_memlock
,
2180 const char **ret_error_message
) {
2183 assert(saved_rlimit_nofile
);
2184 assert(saved_rlimit_memlock
);
2185 assert(ret_error_message
);
2187 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
2189 r
= parse_argv(argc
, argv
);
2191 *ret_error_message
= "Failed to parse commandline arguments";
2195 /* Initialize default unit */
2196 if (!arg_default_unit
) {
2197 arg_default_unit
= strdup(SPECIAL_DEFAULT_TARGET
);
2198 if (!arg_default_unit
) {
2199 *ret_error_message
= "Failed to set default unit";
2204 /* Initialize the show status setting if it hasn't been set explicitly yet */
2205 if (arg_show_status
== _SHOW_STATUS_INVALID
)
2206 arg_show_status
= SHOW_STATUS_YES
;
2211 static int safety_checks(void) {
2213 if (getpid_cached() == 1 &&
2214 arg_action
!= ACTION_RUN
)
2215 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2216 "Unsupported execution mode while PID 1.");
2218 if (getpid_cached() == 1 &&
2220 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2221 "Can't run --user mode as PID 1.");
2223 if (arg_action
== ACTION_RUN
&&
2225 getpid_cached() != 1)
2226 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2227 "Can't run system mode unless PID 1.");
2229 if (arg_action
== ACTION_TEST
&&
2231 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2232 "Don't run test mode as root.");
2235 arg_action
== ACTION_RUN
&&
2237 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2238 "Trying to run as user instance, but the system has not been booted with systemd.");
2241 arg_action
== ACTION_RUN
&&
2242 !getenv("XDG_RUNTIME_DIR"))
2243 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH
),
2244 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2247 arg_action
== ACTION_RUN
&&
2248 running_in_chroot() > 0)
2249 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2250 "Cannot be run in a chroot() environment.");
2255 static int initialize_security(
2256 bool *loaded_policy
,
2257 dual_timestamp
*security_start_timestamp
,
2258 dual_timestamp
*security_finish_timestamp
,
2259 const char **ret_error_message
) {
2263 assert(loaded_policy
);
2264 assert(security_start_timestamp
);
2265 assert(security_finish_timestamp
);
2266 assert(ret_error_message
);
2268 dual_timestamp_get(security_start_timestamp
);
2270 r
= mac_selinux_setup(loaded_policy
);
2272 *ret_error_message
= "Failed to load SELinux policy";
2276 r
= mac_smack_setup(loaded_policy
);
2278 *ret_error_message
= "Failed to load SMACK policy";
2284 *ret_error_message
= "Failed to load IMA policy";
2288 dual_timestamp_get(security_finish_timestamp
);
2292 static void test_summary(Manager
*m
) {
2295 printf("-> By units:\n");
2296 manager_dump_units(m
, stdout
, "\t");
2298 printf("-> By jobs:\n");
2299 manager_dump_jobs(m
, stdout
, "\t");
2302 static int collect_fds(FDSet
**ret_fds
, const char **ret_error_message
) {
2306 assert(ret_error_message
);
2308 r
= fdset_new_fill(ret_fds
);
2310 *ret_error_message
= "Failed to allocate fd set";
2311 return log_emergency_errno(r
, "Failed to allocate fd set: %m");
2314 fdset_cloexec(*ret_fds
, true);
2316 if (arg_serialization
)
2317 assert_se(fdset_remove(*ret_fds
, fileno(arg_serialization
)) >= 0);
2322 static void setup_console_terminal(bool skip_setup
) {
2327 /* Become a session leader if we aren't one yet. */
2330 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a controlling
2332 (void) release_terminal();
2334 /* Reset the console, but only if this is really init and we are freshly booted */
2335 if (getpid_cached() == 1 && !skip_setup
)
2336 (void) console_setup();
2339 static bool early_skip_setup_check(int argc
, char *argv
[]) {
2340 bool found_deserialize
= false;
2343 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much later, so
2344 * let's just have a quick peek here. Note that if we have switched root, do all the special setup things
2345 * anyway, even if in that case we also do deserialization. */
2347 for (i
= 1; i
< argc
; i
++) {
2348 if (streq(argv
[i
], "--switched-root"))
2349 return false; /* If we switched root, don't skip the setup. */
2350 else if (streq(argv
[i
], "--deserialize"))
2351 found_deserialize
= true;
2354 return found_deserialize
; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2357 int main(int argc
, char *argv
[]) {
2359 dual_timestamp initrd_timestamp
= DUAL_TIMESTAMP_NULL
, userspace_timestamp
= DUAL_TIMESTAMP_NULL
, kernel_timestamp
= DUAL_TIMESTAMP_NULL
,
2360 security_start_timestamp
= DUAL_TIMESTAMP_NULL
, security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
2361 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0),
2362 saved_rlimit_memlock
= RLIMIT_MAKE_CONST(RLIM_INFINITY
); /* The original rlimits we passed
2363 * in. Note we use different values
2364 * for the two that indicate whether
2365 * these fields are initialized! */
2366 bool skip_setup
, loaded_policy
= false, queue_default_job
= false, first_boot
= false, reexecute
= false;
2367 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
2368 usec_t before_startup
, after_startup
;
2369 static char systemd
[] = "systemd";
2370 char timespan
[FORMAT_TIMESPAN_MAX
];
2371 const char *shutdown_verb
= NULL
, *error_message
= NULL
;
2372 int r
, retval
= EXIT_FAILURE
;
2376 /* SysV compatibility: redirect init → telinit */
2377 redirect_telinit(argc
, argv
);
2379 /* Take timestamps early on */
2380 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
2381 dual_timestamp_get(&userspace_timestamp
);
2383 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2385 skip_setup
= early_skip_setup_check(argc
, argv
);
2387 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent reexecution we
2388 * are then called 'systemd'. That is confusing, hence let's call us systemd right-away. */
2389 program_invocation_short_name
= systemd
;
2390 (void) prctl(PR_SET_NAME
, systemd
);
2392 /* Save the original command line */
2393 save_argc_argv(argc
, argv
);
2395 /* Make sure that if the user says "syslog" we actually log to the journal. */
2396 log_set_upgrade_syslog_to_journal(true);
2398 if (getpid_cached() == 1) {
2399 /* When we run as PID 1 force system mode */
2402 /* Disable the umask logic */
2405 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might not be
2406 * activated yet (even though the log socket for it exists). */
2407 log_set_prohibit_ipc(true);
2409 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
2410 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
2411 * child process right before execve()'ing the actual binary, at a point in time where socket
2412 * activation stderr/stdout area already set up. */
2413 log_set_always_reopen_console(true);
2415 if (detect_container() <= 0) {
2417 /* Running outside of a container as PID 1 */
2418 log_set_target(LOG_TARGET_KMSG
);
2422 initrd_timestamp
= userspace_timestamp
;
2425 r
= mount_setup_early();
2427 error_message
= "Failed to mount early API filesystems";
2431 /* Let's open the log backend a second time, in case the first time didn't
2432 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2433 * available, and it previously wasn't. */
2436 r
= initialize_security(
2438 &security_start_timestamp
,
2439 &security_finish_timestamp
,
2445 if (mac_selinux_init() < 0) {
2446 error_message
= "Failed to initialize SELinux policy";
2453 /* Set the default for later on, but don't actually open the logs like this for now. Note that
2454 * if we are transitioning from the initrd there might still be journal fd open, and we
2455 * shouldn't attempt opening that before we parsed /proc/cmdline which might redirect output
2457 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
2460 /* Running inside a container, as PID 1 */
2461 log_set_target(LOG_TARGET_CONSOLE
);
2464 /* For later on, see above... */
2465 log_set_target(LOG_TARGET_JOURNAL
);
2467 /* clear the kernel timestamp,
2468 * because we are in a container */
2469 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2472 initialize_coredump(skip_setup
);
2474 r
= fixup_environment();
2476 log_emergency_errno(r
, "Failed to fix up PID 1 environment: %m");
2477 error_message
= "Failed to fix up PID1 environment";
2482 /* Running as user instance */
2484 log_set_target(LOG_TARGET_AUTO
);
2487 /* clear the kernel timestamp,
2488 * because we are not PID 1 */
2489 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
2493 /* Try to figure out if we can use colors with the console. No need to do that for user instances since
2494 * they never log into the console. */
2495 log_show_color(colors_enabled());
2497 r
= make_null_stdio();
2499 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2502 /* Mount /proc, /sys and friends, so that /proc/cmdline and
2503 * /proc/$PID/fd is available. */
2504 if (getpid_cached() == 1) {
2506 /* Load the kernel modules early. */
2510 r
= mount_setup(loaded_policy
);
2512 error_message
= "Failed to mount API filesystems";
2516 /* The efivarfs is now mounted, let's read the random seed off it */
2517 (void) efi_take_random_seed();
2520 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2521 * transitioning from the initrd to the main systemd or suchlike. */
2522 save_rlimits(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
2524 /* Reset all signal handlers. */
2525 (void) reset_all_signal_handlers();
2526 (void) ignore_signals(SIGNALS_IGNORE
, -1);
2528 r
= load_configuration(argc
, argv
, &saved_rlimit_nofile
, &saved_rlimit_memlock
, &error_message
);
2532 r
= safety_checks();
2536 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
, ACTION_DUMP_CONFIGURATION_ITEMS
, ACTION_DUMP_BUS_PROPERTIES
))
2537 (void) pager_open(arg_pager_flags
);
2539 if (arg_action
!= ACTION_RUN
)
2542 if (arg_action
== ACTION_HELP
) {
2543 retval
= help() < 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
2545 } else if (arg_action
== ACTION_VERSION
) {
2548 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
2549 unit_dump_config_items(stdout
);
2550 retval
= EXIT_SUCCESS
;
2552 } else if (arg_action
== ACTION_DUMP_BUS_PROPERTIES
) {
2553 dump_bus_properties(stdout
);
2554 retval
= EXIT_SUCCESS
;
2558 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
2560 /* Move out of the way, so that we won't block unmounts */
2561 assert_se(chdir("/") == 0);
2563 if (arg_action
== ACTION_RUN
) {
2565 /* A core pattern might have been specified via the cmdline. */
2566 initialize_core_pattern(skip_setup
);
2568 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
2571 /* Remember open file descriptors for later deserialization */
2572 r
= collect_fds(&fds
, &error_message
);
2576 /* Give up any control of the console, but make sure its initialized. */
2577 setup_console_terminal(skip_setup
);
2579 /* Open the logging devices, if possible and necessary */
2583 log_execution_mode(&first_boot
);
2585 r
= initialize_runtime(skip_setup
,
2586 &saved_rlimit_nofile
,
2587 &saved_rlimit_memlock
,
2592 r
= manager_new(arg_system
? UNIT_FILE_SYSTEM
: UNIT_FILE_USER
,
2593 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
2596 log_emergency_errno(r
, "Failed to allocate manager object: %m");
2597 error_message
= "Failed to allocate manager object";
2601 m
->timestamps
[MANAGER_TIMESTAMP_KERNEL
] = kernel_timestamp
;
2602 m
->timestamps
[MANAGER_TIMESTAMP_INITRD
] = initrd_timestamp
;
2603 m
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
] = userspace_timestamp
;
2604 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START
)] = security_start_timestamp
;
2605 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH
)] = security_finish_timestamp
;
2607 set_manager_defaults(m
);
2608 set_manager_settings(m
);
2609 manager_set_first_boot(m
, first_boot
);
2611 /* Remember whether we should queue the default job */
2612 queue_default_job
= !arg_serialization
|| arg_switched_root
;
2614 before_startup
= now(CLOCK_MONOTONIC
);
2616 r
= manager_startup(m
, arg_serialization
, fds
);
2618 error_message
= "Failed to start up manager";
2622 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2623 fds
= fdset_free(fds
);
2624 arg_serialization
= safe_fclose(arg_serialization
);
2626 if (queue_default_job
) {
2627 r
= do_queue_default_job(m
, &error_message
);
2632 after_startup
= now(CLOCK_MONOTONIC
);
2634 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
2635 "Loaded units and determined initial transaction in %s.",
2636 format_timespan(timespan
, sizeof(timespan
), after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
2638 if (arg_action
== ACTION_TEST
) {
2640 retval
= EXIT_SUCCESS
;
2644 (void) invoke_main_loop(m
,
2645 &saved_rlimit_nofile
,
2646 &saved_rlimit_memlock
,
2659 arg_reboot_watchdog
= m
->reboot_watchdog
;
2660 arg_kexec_watchdog
= m
->kexec_watchdog
;
2661 m
= manager_free(m
);
2665 mac_selinux_finish();
2668 do_reexecute(argc
, argv
,
2669 &saved_rlimit_nofile
,
2670 &saved_rlimit_memlock
,
2674 &error_message
); /* This only returns if reexecution failed */
2676 arg_serialization
= safe_fclose(arg_serialization
);
2677 fds
= fdset_free(fds
);
2679 #if HAVE_VALGRIND_VALGRIND_H
2680 /* If we are PID 1 and running under valgrind, then let's exit
2681 * here explicitly. valgrind will only generate nice output on
2682 * exit(), not on exec(), hence let's do the former not the
2684 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
2685 /* Cleanup watchdog_device strings for valgrind. We need them
2686 * in become_shutdown() so normally we cannot free them yet. */
2687 watchdog_free_device();
2688 arg_watchdog_device
= mfree(arg_watchdog_device
);
2693 #if HAS_FEATURE_ADDRESS_SANITIZER
2694 __lsan_do_leak_check();
2697 if (shutdown_verb
) {
2698 r
= become_shutdown(shutdown_verb
, retval
);
2699 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
2700 error_message
= "Failed to execute shutdown binary";
2703 watchdog_free_device();
2704 arg_watchdog_device
= mfree(arg_watchdog_device
);
2706 if (getpid_cached() == 1) {
2708 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
2709 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
2710 "%s.", error_message
);
2711 freeze_or_exit_or_reboot();