2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
26 #include <sys/mount.h>
27 #include <sys/prctl.h>
28 #include <sys/reboot.h>
34 #if HAVE_VALGRIND_VALGRIND_H
35 #include <valgrind/valgrind.h>
39 #include "sd-daemon.h"
41 #include "alloc-util.h"
42 #include "architecture.h"
44 #include "bus-error.h"
46 #include "capability-util.h"
47 #include "clock-util.h"
48 #include "conf-parser.h"
49 #include "cpu-set-util.h"
50 #include "dbus-manager.h"
52 #include "emergency-action.h"
57 #include "format-util.h"
59 #include "hostname-setup.h"
60 #include "ima-setup.h"
62 #include "kmod-setup.h"
63 #include "load-fragment.h"
65 #include "loopback-setup.h"
66 #include "machine-id-setup.h"
69 #include "mount-setup.h"
71 #include "parse-util.h"
72 #include "path-util.h"
73 #include "proc-cmdline.h"
74 #include "process-util.h"
75 #include "raw-clone.h"
76 #include "rlimit-util.h"
78 #include "seccomp-util.h"
80 #include "selinux-setup.h"
81 #include "selinux-util.h"
82 #include "signal-util.h"
83 #include "smack-setup.h"
85 #include "stat-util.h"
86 #include "stdio-util.h"
88 #include "switch-root.h"
89 #include "terminal-util.h"
90 #include "umask-util.h"
91 #include "user-util.h"
100 ACTION_DUMP_CONFIGURATION_ITEMS
101 } arg_action
= ACTION_RUN
;
102 static char *arg_default_unit
= NULL
;
103 static bool arg_system
= false;
104 static bool arg_dump_core
= true;
105 static int arg_crash_chvt
= -1;
106 static bool arg_crash_shell
= false;
107 static bool arg_crash_reboot
= false;
108 static char *arg_confirm_spawn
= NULL
;
109 static ShowStatus arg_show_status
= _SHOW_STATUS_UNSET
;
110 static bool arg_switched_root
= false;
111 static bool arg_no_pager
= false;
112 static char ***arg_join_controllers
= NULL
;
113 static ExecOutput arg_default_std_output
= EXEC_OUTPUT_JOURNAL
;
114 static ExecOutput arg_default_std_error
= EXEC_OUTPUT_INHERIT
;
115 static usec_t arg_default_restart_usec
= DEFAULT_RESTART_USEC
;
116 static usec_t arg_default_timeout_start_usec
= DEFAULT_TIMEOUT_USEC
;
117 static usec_t arg_default_timeout_stop_usec
= DEFAULT_TIMEOUT_USEC
;
118 static usec_t arg_default_start_limit_interval
= DEFAULT_START_LIMIT_INTERVAL
;
119 static unsigned arg_default_start_limit_burst
= DEFAULT_START_LIMIT_BURST
;
120 static usec_t arg_runtime_watchdog
= 0;
121 static usec_t arg_shutdown_watchdog
= 10 * USEC_PER_MINUTE
;
122 static char **arg_default_environment
= NULL
;
123 static struct rlimit
*arg_default_rlimit
[_RLIMIT_MAX
] = {};
124 static uint64_t arg_capability_bounding_set
= CAP_ALL
;
125 static nsec_t arg_timer_slack_nsec
= NSEC_INFINITY
;
126 static usec_t arg_default_timer_accuracy_usec
= 1 * USEC_PER_MINUTE
;
127 static Set
* arg_syscall_archs
= NULL
;
128 static FILE* arg_serialization
= NULL
;
129 static bool arg_default_cpu_accounting
= false;
130 static bool arg_default_io_accounting
= false;
131 static bool arg_default_ip_accounting
= false;
132 static bool arg_default_blockio_accounting
= false;
133 static bool arg_default_memory_accounting
= false;
134 static bool arg_default_tasks_accounting
= true;
135 static uint64_t arg_default_tasks_max
= UINT64_MAX
;
136 static sd_id128_t arg_machine_id
= {};
137 static EmergencyAction arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
139 noreturn
static void freeze_or_reboot(void) {
141 if (arg_crash_reboot
) {
142 log_notice("Rebooting in 10s...");
145 log_notice("Rebooting now...");
146 (void) reboot(RB_AUTOBOOT
);
147 log_emergency_errno(errno
, "Failed to reboot: %m");
150 log_emergency("Freezing execution.");
154 noreturn
static void crash(int sig
) {
158 if (getpid_cached() != 1)
159 /* Pass this on immediately, if this is not PID 1 */
161 else if (!arg_dump_core
)
162 log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig
));
164 sa
= (struct sigaction
) {
165 .sa_handler
= nop_signal_handler
,
166 .sa_flags
= SA_NOCLDSTOP
|SA_RESTART
,
169 /* We want to wait for the core process, hence let's enable SIGCHLD */
170 (void) sigaction(SIGCHLD
, &sa
, NULL
);
172 pid
= raw_clone(SIGCHLD
);
174 log_emergency_errno(errno
, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig
));
176 /* Enable default signal handler for core dump */
178 sa
= (struct sigaction
) {
179 .sa_handler
= SIG_DFL
,
181 (void) sigaction(sig
, &sa
, NULL
);
183 /* Don't limit the coredump size */
184 (void) setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
));
186 /* Just to be sure... */
189 /* Raise the signal again */
191 (void) kill(pid
, sig
); /* raise() would kill the parent */
193 assert_not_reached("We shouldn't be here...");
199 /* Order things nicely. */
200 r
= wait_for_terminate(pid
, &status
);
202 log_emergency_errno(r
, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig
));
203 else if (status
.si_code
!= CLD_DUMPED
)
204 log_emergency("Caught <%s>, core dump failed (child "PID_FMT
", code=%s, status=%i/%s).",
205 signal_to_string(sig
),
206 pid
, sigchld_code_to_string(status
.si_code
),
208 strna(status
.si_code
== CLD_EXITED
209 ? exit_status_to_string(status
.si_status
, EXIT_STATUS_MINIMAL
)
210 : signal_to_string(status
.si_status
)));
212 log_emergency("Caught <%s>, dumped core as pid "PID_FMT
".", signal_to_string(sig
), pid
);
216 if (arg_crash_chvt
>= 0)
217 (void) chvt(arg_crash_chvt
);
219 sa
= (struct sigaction
) {
220 .sa_handler
= SIG_IGN
,
221 .sa_flags
= SA_NOCLDSTOP
|SA_NOCLDWAIT
|SA_RESTART
,
224 /* Let the kernel reap children for us */
225 (void) sigaction(SIGCHLD
, &sa
, NULL
);
227 if (arg_crash_shell
) {
228 log_notice("Executing crash shell in 10s...");
231 pid
= raw_clone(SIGCHLD
);
233 log_emergency_errno(errno
, "Failed to fork off crash shell: %m");
236 (void) make_console_stdio();
237 (void) execle("/bin/sh", "/bin/sh", NULL
, environ
);
239 log_emergency_errno(errno
, "execle() failed: %m");
242 log_info("Spawned crash shell as PID "PID_FMT
".", pid
);
243 (void) wait_for_terminate(pid
, NULL
);
250 static void install_crash_handler(void) {
251 static const struct sigaction sa
= {
253 .sa_flags
= SA_NODEFER
, /* So that we can raise the signal again from the signal handler */
257 /* We ignore the return value here, since, we don't mind if we
258 * cannot set up a crash handler */
259 r
= sigaction_many(&sa
, SIGNALS_CRASH_HANDLER
, -1);
261 log_debug_errno(r
, "I had trouble setting up the crash handler, ignoring: %m");
264 static int console_setup(void) {
265 _cleanup_close_
int tty_fd
= -1;
268 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
270 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
272 /* We don't want to force text mode. plymouth may be showing
273 * pictures already from initrd. */
274 r
= reset_terminal_fd(tty_fd
, false);
276 return log_error_errno(r
, "Failed to reset /dev/console: %m");
281 static int parse_crash_chvt(const char *value
) {
284 if (safe_atoi(value
, &arg_crash_chvt
) >= 0)
287 b
= parse_boolean(value
);
292 arg_crash_chvt
= 0; /* switch to where kmsg goes */
294 arg_crash_chvt
= -1; /* turn off switching */
299 static int parse_confirm_spawn(const char *value
, char **console
) {
303 r
= value
? parse_boolean(value
) : 1;
309 if (r
> 0) /* on with default tty */
310 s
= strdup("/dev/console");
311 else if (is_path(value
)) /* on with fully qualified path */
313 else /* on with only a tty file name, not a fully qualified path */
314 s
= strjoin("/dev/", value
);
321 static int set_machine_id(const char *m
) {
325 if (sd_id128_from_string(m
, &t
) < 0)
328 if (sd_id128_is_null(t
))
335 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
341 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
343 if (proc_cmdline_value_missing(key
, value
))
346 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
347 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
348 else if (in_initrd() == !!startswith(key
, "rd.")) {
349 if (free_and_strdup(&arg_default_unit
, value
) < 0)
353 } else if (proc_cmdline_key_streq(key
, "systemd.dump_core")) {
355 r
= value
? parse_boolean(value
) : true;
357 log_warning("Failed to parse dump core switch %s. Ignoring.", value
);
361 } else if (proc_cmdline_key_streq(key
, "systemd.crash_chvt")) {
364 arg_crash_chvt
= 0; /* turn on */
365 else if (parse_crash_chvt(value
) < 0)
366 log_warning("Failed to parse crash chvt switch %s. Ignoring.", value
);
368 } else if (proc_cmdline_key_streq(key
, "systemd.crash_shell")) {
370 r
= value
? parse_boolean(value
) : true;
372 log_warning("Failed to parse crash shell switch %s. Ignoring.", value
);
376 } else if (proc_cmdline_key_streq(key
, "systemd.crash_reboot")) {
378 r
= value
? parse_boolean(value
) : true;
380 log_warning("Failed to parse crash reboot switch %s. Ignoring.", value
);
382 arg_crash_reboot
= r
;
384 } else if (proc_cmdline_key_streq(key
, "systemd.confirm_spawn")) {
387 r
= parse_confirm_spawn(value
, &s
);
389 log_warning_errno(r
, "Failed to parse confirm_spawn switch %s. Ignoring.", value
);
391 free(arg_confirm_spawn
);
392 arg_confirm_spawn
= s
;
395 } else if (proc_cmdline_key_streq(key
, "systemd.show_status")) {
398 r
= parse_show_status(value
, &arg_show_status
);
400 log_warning("Failed to parse show status switch %s. Ignoring.", value
);
402 arg_show_status
= SHOW_STATUS_YES
;
404 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_output")) {
406 if (proc_cmdline_value_missing(key
, value
))
409 r
= exec_output_from_string(value
);
411 log_warning("Failed to parse default standard output switch %s. Ignoring.", value
);
413 arg_default_std_output
= r
;
415 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_error")) {
417 if (proc_cmdline_value_missing(key
, value
))
420 r
= exec_output_from_string(value
);
422 log_warning("Failed to parse default standard error switch %s. Ignoring.", value
);
424 arg_default_std_error
= r
;
426 } else if (streq(key
, "systemd.setenv")) {
428 if (proc_cmdline_value_missing(key
, value
))
431 if (env_assignment_is_valid(value
)) {
434 env
= strv_env_set(arg_default_environment
, value
);
438 arg_default_environment
= env
;
440 log_warning("Environment variable name '%s' is not valid. Ignoring.", value
);
442 } else if (proc_cmdline_key_streq(key
, "systemd.machine_id")) {
444 if (proc_cmdline_value_missing(key
, value
))
447 r
= set_machine_id(value
);
449 log_warning("MachineID '%s' is not valid. Ignoring.", value
);
451 } else if (proc_cmdline_key_streq(key
, "systemd.default_timeout_start_sec")) {
453 if (proc_cmdline_value_missing(key
, value
))
456 r
= parse_sec(value
, &arg_default_timeout_start_usec
);
458 log_warning_errno(r
, "Failed to parse default start timeout: %s, ignoring.", value
);
460 if (arg_default_timeout_start_usec
<= 0)
461 arg_default_timeout_start_usec
= USEC_INFINITY
;
463 } else if (streq(key
, "quiet") && !value
) {
465 if (arg_show_status
== _SHOW_STATUS_UNSET
)
466 arg_show_status
= SHOW_STATUS_AUTO
;
468 } else if (streq(key
, "debug") && !value
) {
470 /* Note that log_parse_environment() handles 'debug'
471 * too, and sets the log level to LOG_DEBUG. */
473 if (detect_container() > 0)
474 log_set_target(LOG_TARGET_CONSOLE
);
479 /* SysV compatibility */
480 target
= runlevel_to_target(key
);
482 return free_and_strdup(&arg_default_unit
, target
);
488 #define DEFINE_SETTER(name, func, descr) \
489 static int name(const char *unit, \
490 const char *filename, \
492 const char *section, \
493 unsigned section_line, \
494 const char *lvalue, \
496 const char *rvalue, \
508 log_syntax(unit, LOG_ERR, filename, line, r, \
509 "Invalid " descr "'%s': %m", \
515 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level")
516 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target")
517 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color" )
518 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location")
520 static int config_parse_cpu_affinity2(
522 const char *filename
,
525 unsigned section_line
,
532 _cleanup_cpu_free_ cpu_set_t
*c
= NULL
;
535 ncpus
= parse_cpu_set_and_warn(rvalue
, &c
, unit
, filename
, line
, lvalue
);
539 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus
), c
) < 0)
540 log_warning_errno(errno
, "Failed to set CPU affinity: %m");
545 static int config_parse_show_status(
547 const char *filename
,
550 unsigned section_line
,
558 ShowStatus
*b
= data
;
565 k
= parse_show_status(rvalue
, b
);
567 log_syntax(unit
, LOG_ERR
, filename
, line
, k
, "Failed to parse show status setting, ignoring: %s", rvalue
);
574 static int config_parse_crash_chvt(
576 const char *filename
,
579 unsigned section_line
,
592 r
= parse_crash_chvt(rvalue
);
594 log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Failed to parse CrashChangeVT= setting, ignoring: %s", rvalue
);
601 static int config_parse_join_controllers(const char *unit
,
602 const char *filename
,
605 unsigned section_line
,
612 const char *whole_rvalue
= rvalue
;
619 arg_join_controllers
= strv_free_free(arg_join_controllers
);
622 _cleanup_free_
char *word
= NULL
;
626 r
= extract_first_word(&rvalue
, &word
, NULL
, EXTRACT_QUOTES
);
628 log_syntax(unit
, LOG_ERR
, filename
, line
, r
, "Invalid value for %s: %s", lvalue
, whole_rvalue
);
634 l
= strv_split(word
, ",");
639 if (strv_length(l
) <= 1) {
644 if (!arg_join_controllers
) {
645 arg_join_controllers
= new(char**, 2);
646 if (!arg_join_controllers
) {
651 arg_join_controllers
[0] = l
;
652 arg_join_controllers
[1] = NULL
;
659 t
= new0(char**, n
+2);
667 for (a
= arg_join_controllers
; *a
; a
++) {
669 if (strv_overlap(*a
, l
)) {
670 if (strv_extend_strv(&l
, *a
, false) < 0) {
690 t
[n
++] = strv_uniq(l
);
692 strv_free_free(arg_join_controllers
);
693 arg_join_controllers
= t
;
696 if (!isempty(rvalue
))
697 log_syntax(unit
, LOG_ERR
, filename
, line
, 0, "Trailing garbage, ignoring.");
702 static int parse_config_file(void) {
704 const ConfigTableItem items
[] = {
705 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
706 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
707 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
708 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
709 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
710 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, NULL
},
711 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, NULL
},
712 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
713 { "Manager", "CrashReboot", config_parse_bool
, 0, &arg_crash_reboot
},
714 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
715 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, NULL
},
716 { "Manager", "JoinControllers", config_parse_join_controllers
, 0, &arg_join_controllers
},
717 { "Manager", "RuntimeWatchdogSec", config_parse_sec
, 0, &arg_runtime_watchdog
},
718 { "Manager", "ShutdownWatchdogSec", config_parse_sec
, 0, &arg_shutdown_watchdog
},
719 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
721 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
723 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
724 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_default_timer_accuracy_usec
},
725 { "Manager", "DefaultStandardOutput", config_parse_output
, 0, &arg_default_std_output
},
726 { "Manager", "DefaultStandardError", config_parse_output
, 0, &arg_default_std_error
},
727 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_default_timeout_start_usec
},
728 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_default_timeout_stop_usec
},
729 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_default_restart_usec
},
730 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_default_start_limit_interval
}, /* obsolete alias */
731 { "Manager", "DefaultStartLimitIntervalSec",config_parse_sec
, 0, &arg_default_start_limit_interval
},
732 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_default_start_limit_burst
},
733 { "Manager", "DefaultEnvironment", config_parse_environ
, 0, &arg_default_environment
},
734 { "Manager", "DefaultLimitCPU", config_parse_limit
, RLIMIT_CPU
, arg_default_rlimit
},
735 { "Manager", "DefaultLimitFSIZE", config_parse_limit
, RLIMIT_FSIZE
, arg_default_rlimit
},
736 { "Manager", "DefaultLimitDATA", config_parse_limit
, RLIMIT_DATA
, arg_default_rlimit
},
737 { "Manager", "DefaultLimitSTACK", config_parse_limit
, RLIMIT_STACK
, arg_default_rlimit
},
738 { "Manager", "DefaultLimitCORE", config_parse_limit
, RLIMIT_CORE
, arg_default_rlimit
},
739 { "Manager", "DefaultLimitRSS", config_parse_limit
, RLIMIT_RSS
, arg_default_rlimit
},
740 { "Manager", "DefaultLimitNOFILE", config_parse_limit
, RLIMIT_NOFILE
, arg_default_rlimit
},
741 { "Manager", "DefaultLimitAS", config_parse_limit
, RLIMIT_AS
, arg_default_rlimit
},
742 { "Manager", "DefaultLimitNPROC", config_parse_limit
, RLIMIT_NPROC
, arg_default_rlimit
},
743 { "Manager", "DefaultLimitMEMLOCK", config_parse_limit
, RLIMIT_MEMLOCK
, arg_default_rlimit
},
744 { "Manager", "DefaultLimitLOCKS", config_parse_limit
, RLIMIT_LOCKS
, arg_default_rlimit
},
745 { "Manager", "DefaultLimitSIGPENDING", config_parse_limit
, RLIMIT_SIGPENDING
, arg_default_rlimit
},
746 { "Manager", "DefaultLimitMSGQUEUE", config_parse_limit
, RLIMIT_MSGQUEUE
, arg_default_rlimit
},
747 { "Manager", "DefaultLimitNICE", config_parse_limit
, RLIMIT_NICE
, arg_default_rlimit
},
748 { "Manager", "DefaultLimitRTPRIO", config_parse_limit
, RLIMIT_RTPRIO
, arg_default_rlimit
},
749 { "Manager", "DefaultLimitRTTIME", config_parse_limit
, RLIMIT_RTTIME
, arg_default_rlimit
},
750 { "Manager", "DefaultCPUAccounting", config_parse_bool
, 0, &arg_default_cpu_accounting
},
751 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_default_io_accounting
},
752 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_default_ip_accounting
},
753 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_default_blockio_accounting
},
754 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_default_memory_accounting
},
755 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_default_tasks_accounting
},
756 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_default_tasks_max
},
757 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, 0, &arg_cad_burst_action
},
761 const char *fn
, *conf_dirs_nulstr
;
764 PKGSYSCONFDIR
"/system.conf" :
765 PKGSYSCONFDIR
"/user.conf";
767 conf_dirs_nulstr
= arg_system
?
768 CONF_PATHS_NULSTR("systemd/system.conf.d") :
769 CONF_PATHS_NULSTR("systemd/user.conf.d");
771 (void) config_parse_many_nulstr(fn
, conf_dirs_nulstr
, "Manager\0", config_item_table_lookup
, items
, CONFIG_PARSE_WARN
, NULL
);
773 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we used USEC_INFINITY
774 * like everywhere else. */
775 if (arg_default_timeout_start_usec
<= 0)
776 arg_default_timeout_start_usec
= USEC_INFINITY
;
777 if (arg_default_timeout_stop_usec
<= 0)
778 arg_default_timeout_stop_usec
= USEC_INFINITY
;
783 static void set_manager_defaults(Manager
*m
) {
787 m
->default_timer_accuracy_usec
= arg_default_timer_accuracy_usec
;
788 m
->default_std_output
= arg_default_std_output
;
789 m
->default_std_error
= arg_default_std_error
;
790 m
->default_timeout_start_usec
= arg_default_timeout_start_usec
;
791 m
->default_timeout_stop_usec
= arg_default_timeout_stop_usec
;
792 m
->default_restart_usec
= arg_default_restart_usec
;
793 m
->default_start_limit_interval
= arg_default_start_limit_interval
;
794 m
->default_start_limit_burst
= arg_default_start_limit_burst
;
795 m
->default_cpu_accounting
= arg_default_cpu_accounting
;
796 m
->default_io_accounting
= arg_default_io_accounting
;
797 m
->default_ip_accounting
= arg_default_ip_accounting
;
798 m
->default_blockio_accounting
= arg_default_blockio_accounting
;
799 m
->default_memory_accounting
= arg_default_memory_accounting
;
800 m
->default_tasks_accounting
= arg_default_tasks_accounting
;
801 m
->default_tasks_max
= arg_default_tasks_max
;
803 manager_set_default_rlimits(m
, arg_default_rlimit
);
804 manager_environment_add(m
, NULL
, arg_default_environment
);
807 static void set_manager_settings(Manager
*m
) {
811 m
->confirm_spawn
= arg_confirm_spawn
;
812 m
->runtime_watchdog
= arg_runtime_watchdog
;
813 m
->shutdown_watchdog
= arg_shutdown_watchdog
;
814 m
->cad_burst_action
= arg_cad_burst_action
;
816 manager_set_show_status(m
, arg_show_status
);
819 static int parse_argv(int argc
, char *argv
[]) {
822 ARG_LOG_LEVEL
= 0x100,
832 ARG_DUMP_CONFIGURATION_ITEMS
,
841 ARG_DEFAULT_STD_OUTPUT
,
842 ARG_DEFAULT_STD_ERROR
,
846 static const struct option options
[] = {
847 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
848 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
849 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
850 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
851 { "unit", required_argument
, NULL
, ARG_UNIT
},
852 { "system", no_argument
, NULL
, ARG_SYSTEM
},
853 { "user", no_argument
, NULL
, ARG_USER
},
854 { "test", no_argument
, NULL
, ARG_TEST
},
855 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
856 { "help", no_argument
, NULL
, 'h' },
857 { "version", no_argument
, NULL
, ARG_VERSION
},
858 { "dump-configuration-items", no_argument
, NULL
, ARG_DUMP_CONFIGURATION_ITEMS
},
859 { "dump-core", optional_argument
, NULL
, ARG_DUMP_CORE
},
860 { "crash-chvt", required_argument
, NULL
, ARG_CRASH_CHVT
},
861 { "crash-shell", optional_argument
, NULL
, ARG_CRASH_SHELL
},
862 { "crash-reboot", optional_argument
, NULL
, ARG_CRASH_REBOOT
},
863 { "confirm-spawn", optional_argument
, NULL
, ARG_CONFIRM_SPAWN
},
864 { "show-status", optional_argument
, NULL
, ARG_SHOW_STATUS
},
865 { "deserialize", required_argument
, NULL
, ARG_DESERIALIZE
},
866 { "switched-root", no_argument
, NULL
, ARG_SWITCHED_ROOT
},
867 { "default-standard-output", required_argument
, NULL
, ARG_DEFAULT_STD_OUTPUT
, },
868 { "default-standard-error", required_argument
, NULL
, ARG_DEFAULT_STD_ERROR
, },
869 { "machine-id", required_argument
, NULL
, ARG_MACHINE_ID
},
878 if (getpid_cached() == 1)
881 while ((c
= getopt_long(argc
, argv
, "hDbsz:", options
, NULL
)) >= 0)
886 r
= log_set_max_level_from_string(optarg
);
888 log_error("Failed to parse log level %s.", optarg
);
895 r
= log_set_target_from_string(optarg
);
897 log_error("Failed to parse log target %s.", optarg
);
906 r
= log_show_color_from_string(optarg
);
908 log_error("Failed to parse log color setting %s.", optarg
);
912 log_show_color(true);
916 case ARG_LOG_LOCATION
:
918 r
= log_show_location_from_string(optarg
);
920 log_error("Failed to parse log location setting %s.", optarg
);
924 log_show_location(true);
928 case ARG_DEFAULT_STD_OUTPUT
:
929 r
= exec_output_from_string(optarg
);
931 log_error("Failed to parse default standard output setting %s.", optarg
);
934 arg_default_std_output
= r
;
937 case ARG_DEFAULT_STD_ERROR
:
938 r
= exec_output_from_string(optarg
);
940 log_error("Failed to parse default standard error output setting %s.", optarg
);
943 arg_default_std_error
= r
;
947 r
= free_and_strdup(&arg_default_unit
, optarg
);
949 return log_error_errno(r
, "Failed to set default unit %s: %m", optarg
);
962 arg_action
= ACTION_TEST
;
970 arg_action
= ACTION_VERSION
;
973 case ARG_DUMP_CONFIGURATION_ITEMS
:
974 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
979 arg_dump_core
= true;
981 r
= parse_boolean(optarg
);
983 return log_error_errno(r
, "Failed to parse dump core boolean: %s", optarg
);
989 r
= parse_crash_chvt(optarg
);
991 return log_error_errno(r
, "Failed to parse crash virtual terminal index: %s", optarg
);
994 case ARG_CRASH_SHELL
:
996 arg_crash_shell
= true;
998 r
= parse_boolean(optarg
);
1000 return log_error_errno(r
, "Failed to parse crash shell boolean: %s", optarg
);
1001 arg_crash_shell
= r
;
1005 case ARG_CRASH_REBOOT
:
1007 arg_crash_reboot
= true;
1009 r
= parse_boolean(optarg
);
1011 return log_error_errno(r
, "Failed to parse crash shell boolean: %s", optarg
);
1012 arg_crash_reboot
= r
;
1016 case ARG_CONFIRM_SPAWN
:
1017 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
1019 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
1021 return log_error_errno(r
, "Failed to parse confirm spawn option: %m");
1024 case ARG_SHOW_STATUS
:
1026 r
= parse_show_status(optarg
, &arg_show_status
);
1028 log_error("Failed to parse show status boolean %s.", optarg
);
1032 arg_show_status
= SHOW_STATUS_YES
;
1035 case ARG_DESERIALIZE
: {
1039 r
= safe_atoi(optarg
, &fd
);
1040 if (r
< 0 || fd
< 0) {
1041 log_error("Failed to parse deserialize option %s.", optarg
);
1045 (void) fd_cloexec(fd
, true);
1047 f
= fdopen(fd
, "r");
1049 return log_error_errno(errno
, "Failed to open serialization fd: %m");
1051 safe_fclose(arg_serialization
);
1052 arg_serialization
= f
;
1057 case ARG_SWITCHED_ROOT
:
1058 arg_switched_root
= true;
1061 case ARG_MACHINE_ID
:
1062 r
= set_machine_id(optarg
);
1064 return log_error_errno(r
, "MachineID '%s' is not valid.", optarg
);
1068 arg_action
= ACTION_HELP
;
1072 log_set_max_level(LOG_DEBUG
);
1078 /* Just to eat away the sysvinit kernel
1079 * cmdline args without getopt() error
1080 * messages that we'll parse in
1081 * parse_proc_cmdline_word() or ignore. */
1084 if (getpid_cached() != 1)
1090 assert_not_reached("Unhandled option code.");
1093 if (optind
< argc
&& getpid_cached() != 1) {
1094 /* Hmm, when we aren't run as init system
1095 * let's complain about excess arguments */
1097 log_error("Excess arguments.");
1104 static int help(void) {
1106 printf("%s [OPTIONS...]\n\n"
1107 "Starts up and maintains the system or user services.\n\n"
1108 " -h --help Show this help\n"
1109 " --version Show version\n"
1110 " --test Determine startup sequence, dump it and exit\n"
1111 " --no-pager Do not pipe output into a pager\n"
1112 " --dump-configuration-items Dump understood unit configuration items\n"
1113 " --unit=UNIT Set default unit\n"
1114 " --system Run a system instance, even if PID != 1\n"
1115 " --user Run a user instance\n"
1116 " --dump-core[=BOOL] Dump core on crash\n"
1117 " --crash-vt=NR Change to specified VT on crash\n"
1118 " --crash-reboot[=BOOL] Reboot on crash\n"
1119 " --crash-shell[=BOOL] Run shell on crash\n"
1120 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1121 " --show-status[=BOOL] Show status updates on the console during bootup\n"
1122 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
1123 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1124 " --log-color[=BOOL] Highlight important log messages\n"
1125 " --log-location[=BOOL] Include code location in log messages\n"
1126 " --default-standard-output= Set default standard output for services\n"
1127 " --default-standard-error= Set default standard error output for services\n",
1128 program_invocation_short_name
);
1133 static int prepare_reexecute(Manager
*m
, FILE **_f
, FDSet
**_fds
, bool switching_root
) {
1134 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1135 _cleanup_fclose_
FILE *f
= NULL
;
1142 r
= manager_open_serialization(m
, &f
);
1144 return log_error_errno(r
, "Failed to create serialization file: %m");
1146 /* Make sure nothing is really destructed when we shut down */
1148 bus_manager_send_reloading(m
, true);
1154 r
= manager_serialize(m
, f
, fds
, switching_root
);
1156 return log_error_errno(r
, "Failed to serialize state: %m");
1158 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1159 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1161 r
= fd_cloexec(fileno(f
), false);
1163 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1165 r
= fdset_cloexec(fds
, false);
1167 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1178 static int bump_rlimit_nofile(struct rlimit
*saved_rlimit
) {
1182 _cleanup_free_
char *nr_open
= NULL
;
1184 assert(saved_rlimit
);
1186 /* Save the original RLIMIT_NOFILE so that we can reset it
1187 * later when transitioning from the initrd to the main
1188 * systemd or suchlike. */
1189 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit
) < 0)
1190 return log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
1192 /* Make sure forked processes get the default kernel setting */
1193 if (!arg_default_rlimit
[RLIMIT_NOFILE
]) {
1196 rl
= newdup(struct rlimit
, saved_rlimit
, 1);
1200 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
1203 /* Get current RLIMIT_NOFILE maximum compiled into the kernel. */
1204 r
= read_one_line_file("/proc/sys/fs/nr_open", &nr_open
);
1206 r
= safe_atoi(nr_open
, &min_max
);
1207 /* If we fail, fallback to the hard-coded kernel limit of 1024 * 1024. */
1209 min_max
= 1024 * 1024;
1211 /* Bump up the resource limit for ourselves substantially */
1212 nl
.rlim_cur
= nl
.rlim_max
= min_max
;
1213 r
= setrlimit_closest(RLIMIT_NOFILE
, &nl
);
1215 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1220 static int bump_rlimit_memlock(struct rlimit
*saved_rlimit
) {
1223 assert(saved_rlimit
);
1224 assert(getuid() == 0);
1226 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even though we have CAP_IPC_LOCK which
1227 * should normally disable such checks. We need them to implement IPAccessAllow= and IPAccessDeny=, hence let's
1228 * bump the value high enough for the root user. */
1230 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit
) < 0)
1231 return log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
1233 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &RLIMIT_MAKE_CONST(1024ULL*1024ULL*16ULL));
1235 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1240 static void test_usr(void) {
1242 /* Check that /usr is not a separate fs */
1244 if (dir_is_empty("/usr") <= 0)
1247 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1248 "Some things will probably break (sometimes even silently) in mysterious ways. "
1249 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1252 static int initialize_join_controllers(void) {
1253 /* By default, mount "cpu" + "cpuacct" together, and "net_cls"
1254 * + "net_prio". We'd like to add "cpuset" to the mix, but
1255 * "cpuset" doesn't really work for groups with no initialized
1258 arg_join_controllers
= new(char**, 3);
1259 if (!arg_join_controllers
)
1262 arg_join_controllers
[0] = strv_new("cpu", "cpuacct", NULL
);
1263 if (!arg_join_controllers
[0])
1266 arg_join_controllers
[1] = strv_new("net_cls", "net_prio", NULL
);
1267 if (!arg_join_controllers
[1])
1270 arg_join_controllers
[2] = NULL
;
1274 arg_join_controllers
= strv_free_free(arg_join_controllers
);
1278 static int enforce_syscall_archs(Set
*archs
) {
1282 if (!is_seccomp_available())
1285 r
= seccomp_restrict_archs(arg_syscall_archs
);
1287 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1292 static int status_welcome(void) {
1293 _cleanup_free_
char *pretty_name
= NULL
, *ansi_color
= NULL
;
1296 r
= parse_env_file("/etc/os-release", NEWLINE
,
1297 "PRETTY_NAME", &pretty_name
,
1298 "ANSI_COLOR", &ansi_color
,
1301 r
= parse_env_file("/usr/lib/os-release", NEWLINE
,
1302 "PRETTY_NAME", &pretty_name
,
1303 "ANSI_COLOR", &ansi_color
,
1306 if (r
< 0 && r
!= -ENOENT
)
1307 log_warning_errno(r
, "Failed to read os-release file: %m");
1309 if (log_get_show_color())
1310 return status_printf(NULL
, false, false,
1311 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1312 isempty(ansi_color
) ? "1" : ansi_color
,
1313 isempty(pretty_name
) ? "Linux" : pretty_name
);
1315 return status_printf(NULL
, false, false,
1316 "\nWelcome to %s!\n",
1317 isempty(pretty_name
) ? "Linux" : pretty_name
);
1320 static int write_container_id(void) {
1324 c
= getenv("container");
1328 RUN_WITH_UMASK(0022)
1329 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1331 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1336 static int bump_unix_max_dgram_qlen(void) {
1337 _cleanup_free_
char *qlen
= NULL
;
1341 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel
1342 * default of 16 is simply too low. We set the value really
1343 * really early during boot, so that it is actually applied to
1344 * all our sockets, including the $NOTIFY_SOCKET one. */
1346 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1348 return log_warning_errno(r
, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1350 r
= safe_atolu(qlen
, &v
);
1352 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length, ignoring: %m");
1354 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1358 if (asprintf(&qlen
, "%lu\n", DEFAULT_UNIX_MAX_DGRAM_QLEN
) < 0)
1361 r
= write_string_file("/proc/sys/net/unix/max_dgram_qlen", qlen
, 0);
1363 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1364 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1369 static int fixup_environment(void) {
1370 _cleanup_free_
char *term
= NULL
;
1373 /* We expect the environment to be set correctly
1374 * if run inside a container. */
1375 if (detect_container() > 0)
1378 /* When started as PID1, the kernel uses /dev/console
1379 * for our stdios and uses TERM=linux whatever the
1380 * backend device used by the console. We try to make
1381 * a better guess here since some consoles might not
1382 * have support for color mode for example.
1384 * However if TERM was configured through the kernel
1385 * command line then leave it alone. */
1387 r
= proc_cmdline_get_key("TERM", 0, &term
);
1391 term
= strdup(default_term_for_tty("/dev/console"));
1396 if (setenv("TERM", term
, 1) < 0)
1402 static void redirect_telinit(int argc
, char *argv
[]) {
1404 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1406 #if HAVE_SYSV_COMPAT
1407 if (getpid_cached() == 1)
1410 if (!strstr(program_invocation_short_name
, "init"))
1413 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1414 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1419 static int become_shutdown(
1420 const char *shutdown_verb
,
1422 bool arm_reboot_watchdog
) {
1424 char log_level
[DECIMAL_STR_MAX(int) + 1],
1425 exit_code
[DECIMAL_STR_MAX(uint8_t) + 1];
1427 const char* command_line
[11] = {
1428 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1430 "--log-level", log_level
,
1434 _cleanup_strv_free_
char **env_block
= NULL
;
1438 assert(command_line
[pos
] == NULL
);
1439 env_block
= strv_copy(environ
);
1441 xsprintf(log_level
, "%d", log_get_max_level());
1443 switch (log_get_target()) {
1445 case LOG_TARGET_KMSG
:
1446 case LOG_TARGET_JOURNAL_OR_KMSG
:
1447 case LOG_TARGET_SYSLOG_OR_KMSG
:
1448 command_line
[pos
++] = "kmsg";
1451 case LOG_TARGET_NULL
:
1452 command_line
[pos
++] = "null";
1455 case LOG_TARGET_CONSOLE
:
1457 command_line
[pos
++] = "console";
1461 if (log_get_show_color())
1462 command_line
[pos
++] = "--log-color";
1464 if (log_get_show_location())
1465 command_line
[pos
++] = "--log-location";
1467 if (streq(shutdown_verb
, "exit")) {
1468 command_line
[pos
++] = "--exit-code";
1469 command_line
[pos
++] = exit_code
;
1470 xsprintf(exit_code
, "%d", retval
);
1473 assert(pos
< ELEMENTSOF(command_line
));
1475 if (arm_reboot_watchdog
&& arg_shutdown_watchdog
> 0 && arg_shutdown_watchdog
!= USEC_INFINITY
) {
1478 /* If we reboot let's set the shutdown
1479 * watchdog and tell the shutdown binary to
1480 * repeatedly ping it */
1481 r
= watchdog_set_timeout(&arg_shutdown_watchdog
);
1482 watchdog_close(r
< 0);
1484 /* Tell the binary how often to ping, ignore failure */
1485 if (asprintf(&e
, "WATCHDOG_USEC="USEC_FMT
, arg_shutdown_watchdog
) > 0)
1486 (void) strv_push(&env_block
, e
);
1488 watchdog_close(true);
1490 /* Avoid the creation of new processes forked by the
1491 * kernel; at this point, we will not listen to the
1493 if (detect_container() <= 0)
1494 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1496 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1500 static void initialize_clock(void) {
1503 if (clock_is_localtime(NULL
) > 0) {
1507 * The very first call of settimeofday() also does a time warp in the kernel.
1509 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to take care
1510 * of maintaining the RTC and do all adjustments. This matches the behavior of Windows, which leaves
1511 * the RTC alone if the registry tells that the RTC runs in UTC.
1513 r
= clock_set_timezone(&min
);
1515 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1517 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1519 } else if (!in_initrd()) {
1521 * Do a dummy very first call to seal the kernel's time warp magic.
1523 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with LOCAL, but the
1524 * real system could be set up that way. In such case, we need to delay the time-warp or the sealing
1525 * until we reach the real system.
1527 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably, the time
1528 * will jump or be incorrect at every daylight saving time change. All kernel local time concepts will
1529 * be treated as UTC that way.
1531 (void) clock_reset_timewarp();
1534 r
= clock_apply_epoch();
1536 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1538 log_info("System time before build time, advancing clock.");
1541 static void initialize_coredump(bool skip_setup
) {
1543 if (getpid_cached() != 1)
1546 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1547 * will process core dumps for system services by default. */
1548 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1549 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1551 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1552 * until the systemd-coredump tool is enabled via sysctl. */
1554 (void) write_string_file("/proc/sys/kernel/core_pattern", "|/bin/false", 0);
1557 int main(int argc
, char *argv
[]) {
1559 int r
, retval
= EXIT_FAILURE
;
1560 usec_t before_startup
, after_startup
;
1561 char timespan
[FORMAT_TIMESPAN_MAX
];
1563 bool reexecute
= false;
1564 const char *shutdown_verb
= NULL
;
1565 dual_timestamp initrd_timestamp
= DUAL_TIMESTAMP_NULL
;
1566 dual_timestamp userspace_timestamp
= DUAL_TIMESTAMP_NULL
;
1567 dual_timestamp kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
1568 dual_timestamp security_start_timestamp
= DUAL_TIMESTAMP_NULL
;
1569 dual_timestamp security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
1570 static char systemd
[] = "systemd";
1571 bool skip_setup
= false;
1573 bool loaded_policy
= false;
1574 bool arm_reboot_watchdog
= false;
1575 bool queue_default_job
= false;
1576 bool first_boot
= false;
1577 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
1578 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0), saved_rlimit_memlock
= RLIMIT_MAKE_CONST((rlim_t
) -1);
1579 const char *error_message
= NULL
;
1581 redirect_telinit(argc
, argv
);
1583 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
1584 dual_timestamp_get(&userspace_timestamp
);
1586 /* Determine if this is a reexecution or normal bootup. We do
1587 * the full command line parsing much later, so let's just
1588 * have a quick peek here. */
1589 if (strv_find(argv
+1, "--deserialize"))
1592 /* If we have switched root, do all the special setup
1594 if (strv_find(argv
+1, "--switched-root"))
1597 /* If we get started via the /sbin/init symlink then we are
1598 called 'init'. After a subsequent reexecution we are then
1599 called 'systemd'. That is confusing, hence let's call us
1600 systemd right-away. */
1601 program_invocation_short_name
= systemd
;
1602 (void) prctl(PR_SET_NAME
, systemd
);
1607 log_set_upgrade_syslog_to_journal(true);
1609 if (getpid_cached() == 1) {
1610 /* Disable the umask logic */
1613 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
1614 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
1615 * child process right before execve()'ing the actual binary, at a point in time where socket
1616 * activation stderr/stdout area already set up. */
1617 log_set_always_reopen_console(true);
1620 if (getpid_cached() == 1 && detect_container() <= 0) {
1622 /* Running outside of a container as PID 1 */
1624 log_set_target(LOG_TARGET_KMSG
);
1628 initrd_timestamp
= userspace_timestamp
;
1631 r
= mount_setup_early();
1633 error_message
= "Failed to mount early API filesystems";
1637 dual_timestamp_get(&security_start_timestamp
);
1638 if (mac_selinux_setup(&loaded_policy
) < 0) {
1639 error_message
= "Failed to load SELinux policy";
1641 } else if (mac_smack_setup(&loaded_policy
) < 0) {
1642 error_message
= "Failed to load SMACK policy";
1644 } else if (ima_setup() < 0) {
1645 error_message
= "Failed to load IMA policy";
1648 dual_timestamp_get(&security_finish_timestamp
);
1651 if (mac_selinux_init() < 0) {
1652 error_message
= "Failed to initialize SELinux policy";
1659 /* Set the default for later on, but don't actually
1660 * open the logs like this for now. Note that if we
1661 * are transitioning from the initrd there might still
1662 * be journal fd open, and we shouldn't attempt
1663 * opening that before we parsed /proc/cmdline which
1664 * might redirect output elsewhere. */
1665 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
1667 } else if (getpid_cached() == 1) {
1668 /* Running inside a container, as PID 1 */
1670 log_set_target(LOG_TARGET_CONSOLE
);
1671 log_close_console(); /* force reopen of /dev/console */
1674 /* For later on, see above... */
1675 log_set_target(LOG_TARGET_JOURNAL
);
1677 /* clear the kernel timestamp,
1678 * because we are in a container */
1679 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
1681 /* Running as user instance */
1683 log_set_target(LOG_TARGET_AUTO
);
1686 /* clear the kernel timestamp,
1687 * because we are not PID 1 */
1688 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
1691 initialize_coredump(skip_setup
);
1694 if (fixup_environment() < 0) {
1695 error_message
= "Failed to fix up PID1 environment";
1699 /* Try to figure out if we can use colors with the console. No
1700 * need to do that for user instances since they never log
1701 * into the console. */
1702 log_show_color(colors_enabled());
1703 r
= make_null_stdio();
1705 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null: %m");
1708 r
= initialize_join_controllers();
1710 error_message
= "Failed to initialize cgroup controllers";
1714 /* Mount /proc, /sys and friends, so that /proc/cmdline and
1715 * /proc/$PID/fd is available. */
1716 if (getpid_cached() == 1) {
1718 /* Load the kernel modules early. */
1722 r
= mount_setup(loaded_policy
);
1724 error_message
= "Failed to mount API filesystems";
1729 /* Reset all signal handlers. */
1730 (void) reset_all_signal_handlers();
1731 (void) ignore_signals(SIGNALS_IGNORE
, -1);
1733 arg_default_tasks_max
= system_tasks_max_scale(DEFAULT_TASKS_MAX_PERCENTAGE
, 100U);
1735 if (parse_config_file() < 0) {
1736 error_message
= "Failed to parse config file";
1741 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
1743 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
1746 /* Note that this also parses bits from the kernel command
1747 * line, including "debug". */
1748 log_parse_environment();
1750 if (parse_argv(argc
, argv
) < 0) {
1751 error_message
= "Failed to parse commandline arguments";
1755 /* Initialize default unit */
1756 if (!arg_default_unit
) {
1757 arg_default_unit
= strdup(SPECIAL_DEFAULT_TARGET
);
1758 if (!arg_default_unit
) {
1760 error_message
= "Failed to set default unit";
1765 if (arg_action
== ACTION_TEST
&&
1767 log_error("Don't run test mode as root.");
1772 arg_action
== ACTION_RUN
&&
1774 log_error("Trying to run as user instance, but the system has not been booted with systemd.");
1779 arg_action
== ACTION_RUN
&&
1780 running_in_chroot() > 0) {
1781 log_error("Cannot be run in a chroot() environment.");
1785 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
)) {
1786 pager_open(arg_no_pager
, false);
1790 if (arg_action
== ACTION_HELP
) {
1793 } else if (arg_action
== ACTION_VERSION
) {
1796 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
1797 pager_open(arg_no_pager
, false);
1798 unit_dump_config_items(stdout
);
1799 retval
= EXIT_SUCCESS
;
1804 !getenv("XDG_RUNTIME_DIR")) {
1805 log_error("Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
1809 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
1811 /* Close logging fds, in order not to confuse fdset below */
1814 /* Remember open file descriptors for later deserialization */
1815 if (arg_action
== ACTION_RUN
) {
1816 r
= fdset_new_fill(&fds
);
1818 log_emergency_errno(r
, "Failed to allocate fd set: %m");
1819 error_message
= "Failed to allocate fd set";
1822 fdset_cloexec(fds
, true);
1824 if (arg_serialization
)
1825 assert_se(fdset_remove(fds
, fileno(arg_serialization
)) >= 0);
1828 /* Become a session leader if we aren't one yet. */
1832 /* Move out of the way, so that we won't block unmounts */
1833 assert_se(chdir("/") == 0);
1835 /* Reset the console, but only if this is really init and we
1836 * are freshly booted */
1837 if (arg_system
&& arg_action
== ACTION_RUN
) {
1839 /* If we are init, we connect stdin/stdout/stderr to
1840 * /dev/null and make sure we don't have a controlling
1844 if (getpid_cached() == 1 && !skip_setup
)
1848 /* Open the logging devices, if possible and necessary */
1851 if (arg_show_status
== _SHOW_STATUS_UNSET
)
1852 arg_show_status
= SHOW_STATUS_YES
;
1854 /* Make sure we leave a core dump without panicing the
1856 if (getpid_cached() == 1) {
1857 install_crash_handler();
1859 r
= mount_cgroup_controllers(arg_join_controllers
);
1867 log_info(PACKAGE_STRING
" running in %ssystem mode. (" SYSTEMD_FEATURES
")",
1868 arg_action
== ACTION_TEST
? "test " : "" );
1870 v
= detect_virtualization();
1872 log_info("Detected virtualization %s.", virtualization_to_string(v
));
1874 write_container_id();
1876 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
1879 log_info("Running in initial RAM disk.");
1881 /* Let's check whether we are in first boot, i.e. whether /etc is still unpopulated. We use
1882 * /etc/machine-id as flag file, for this: if it exists we assume /etc is populated, if it
1883 * doesn't it's unpopulated. This allows container managers and installers to provision a
1884 * couple of files already. If the container manager wants to provision the machine ID itself
1885 * it should pass $container_uuid to PID 1. */
1887 first_boot
= access("/etc/machine-id", F_OK
) < 0;
1889 log_info("Running with unpopulated /etc.");
1892 _cleanup_free_
char *t
;
1894 t
= uid_to_name(getuid());
1895 log_debug(PACKAGE_STRING
" running in %suser mode for user " UID_FMT
"/%s. (" SYSTEMD_FEATURES
")",
1896 arg_action
== ACTION_TEST
? " test" : "", getuid(), strna(t
));
1899 if (arg_action
== ACTION_RUN
) {
1900 if (arg_system
&& !skip_setup
) {
1901 if (arg_show_status
> 0)
1905 machine_id_setup(NULL
, arg_machine_id
, NULL
);
1907 bump_unix_max_dgram_qlen();
1912 if (arg_system
&& arg_runtime_watchdog
> 0 && arg_runtime_watchdog
!= USEC_INFINITY
)
1913 watchdog_set_timeout(&arg_runtime_watchdog
);
1915 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
1916 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
1917 log_error_errno(errno
, "Failed to adjust timer slack: %m");
1919 if (arg_system
&& !cap_test_all(arg_capability_bounding_set
)) {
1920 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
1922 log_emergency_errno(r
, "Failed to drop capability bounding set of usermode helpers: %m");
1923 error_message
= "Failed to drop capability bounding set of usermode helpers";
1926 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
1928 log_emergency_errno(r
, "Failed to drop capability bounding set: %m");
1929 error_message
= "Failed to drop capability bounding set";
1934 if (arg_syscall_archs
) {
1935 r
= enforce_syscall_archs(arg_syscall_archs
);
1937 error_message
= "Failed to set syscall architectures";
1943 /* Become reaper of our children */
1944 if (prctl(PR_SET_CHILD_SUBREAPER
, 1) < 0)
1945 log_warning_errno(errno
, "Failed to make us a subreaper: %m");
1948 /* Bump up RLIMIT_NOFILE for systemd itself */
1949 (void) bump_rlimit_nofile(&saved_rlimit_nofile
);
1950 (void) bump_rlimit_memlock(&saved_rlimit_memlock
);
1954 r
= manager_new(arg_system
? UNIT_FILE_SYSTEM
: UNIT_FILE_USER
,
1955 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
1958 log_emergency_errno(r
, "Failed to allocate manager object: %m");
1959 error_message
= "Failed to allocate manager object";
1963 m
->userspace_timestamp
= userspace_timestamp
;
1964 m
->kernel_timestamp
= kernel_timestamp
;
1965 m
->initrd_timestamp
= initrd_timestamp
;
1966 m
->security_start_timestamp
= security_start_timestamp
;
1967 m
->security_finish_timestamp
= security_finish_timestamp
;
1969 set_manager_defaults(m
);
1970 set_manager_settings(m
);
1971 manager_set_first_boot(m
, first_boot
);
1973 /* Remember whether we should queue the default job */
1974 queue_default_job
= !arg_serialization
|| arg_switched_root
;
1976 before_startup
= now(CLOCK_MONOTONIC
);
1978 r
= manager_startup(m
, arg_serialization
, fds
);
1980 log_error_errno(r
, "Failed to fully start up daemon: %m");
1984 /* This will close all file descriptors that were opened, but
1985 * not claimed by any unit. */
1986 fds
= fdset_free(fds
);
1988 arg_serialization
= safe_fclose(arg_serialization
);
1990 if (queue_default_job
) {
1991 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1992 Unit
*target
= NULL
;
1993 Job
*default_unit_job
;
1995 log_debug("Activating default unit: %s", arg_default_unit
);
1997 r
= manager_load_unit(m
, arg_default_unit
, NULL
, &error
, &target
);
1999 log_error("Failed to load default target: %s", bus_error_message(&error
, r
));
2000 else if (IN_SET(target
->load_state
, UNIT_ERROR
, UNIT_NOT_FOUND
))
2001 log_error_errno(target
->load_error
, "Failed to load default target: %m");
2002 else if (target
->load_state
== UNIT_MASKED
)
2003 log_error("Default target masked.");
2005 if (!target
|| target
->load_state
!= UNIT_LOADED
) {
2006 log_info("Trying to load rescue target...");
2008 r
= manager_load_unit(m
, SPECIAL_RESCUE_TARGET
, NULL
, &error
, &target
);
2010 log_emergency("Failed to load rescue target: %s", bus_error_message(&error
, r
));
2011 error_message
= "Failed to load rescue target";
2013 } else if (IN_SET(target
->load_state
, UNIT_ERROR
, UNIT_NOT_FOUND
)) {
2014 log_emergency_errno(target
->load_error
, "Failed to load rescue target: %m");
2015 error_message
= "Failed to load rescue target";
2017 } else if (target
->load_state
== UNIT_MASKED
) {
2018 log_emergency("Rescue target masked.");
2019 error_message
= "Rescue target masked";
2024 assert(target
->load_state
== UNIT_LOADED
);
2026 if (arg_action
== ACTION_TEST
) {
2027 printf("-> By units:\n");
2028 manager_dump_units(m
, stdout
, "\t");
2031 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, &error
, &default_unit_job
);
2033 log_debug("Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
2035 sd_bus_error_free(&error
);
2037 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, &error
, &default_unit_job
);
2039 log_emergency("Failed to start default target: %s", bus_error_message(&error
, r
));
2040 error_message
= "Failed to start default target";
2044 log_emergency("Failed to isolate default target: %s", bus_error_message(&error
, r
));
2045 error_message
= "Failed to isolate default target";
2049 m
->default_unit_job_id
= default_unit_job
->id
;
2051 after_startup
= now(CLOCK_MONOTONIC
);
2052 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
2053 "Loaded units and determined initial transaction in %s.",
2054 format_timespan(timespan
, sizeof(timespan
), after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
2056 if (arg_action
== ACTION_TEST
) {
2057 printf("-> By jobs:\n");
2058 manager_dump_jobs(m
, stdout
, "\t");
2059 retval
= EXIT_SUCCESS
;
2065 r
= manager_loop(m
);
2067 log_emergency_errno(r
, "Failed to run main loop: %m");
2068 error_message
= "Failed to run main loop";
2072 switch (m
->exit_code
) {
2074 case MANAGER_RELOAD
:
2075 log_info("Reloading.");
2077 r
= parse_config_file();
2079 log_error("Failed to parse config file.");
2081 set_manager_defaults(m
);
2083 r
= manager_reload(m
);
2085 log_error_errno(r
, "Failed to reload: %m");
2088 case MANAGER_REEXECUTE
:
2090 if (prepare_reexecute(m
, &arg_serialization
, &fds
, false) < 0) {
2091 error_message
= "Failed to prepare for reexecution";
2096 log_notice("Reexecuting.");
2099 case MANAGER_SWITCH_ROOT
:
2100 /* Steal the switch root parameters */
2101 switch_root_dir
= m
->switch_root
;
2102 switch_root_init
= m
->switch_root_init
;
2103 m
->switch_root
= m
->switch_root_init
= NULL
;
2105 if (!switch_root_init
)
2106 if (prepare_reexecute(m
, &arg_serialization
, &fds
, true) < 0) {
2107 error_message
= "Failed to prepare for reexecution";
2112 log_notice("Switching root.");
2116 retval
= m
->return_value
;
2118 if (MANAGER_IS_USER(m
)) {
2124 case MANAGER_REBOOT
:
2125 case MANAGER_POWEROFF
:
2127 case MANAGER_KEXEC
: {
2128 static const char * const table
[_MANAGER_EXIT_CODE_MAX
] = {
2129 [MANAGER_EXIT
] = "exit",
2130 [MANAGER_REBOOT
] = "reboot",
2131 [MANAGER_POWEROFF
] = "poweroff",
2132 [MANAGER_HALT
] = "halt",
2133 [MANAGER_KEXEC
] = "kexec"
2136 assert_se(shutdown_verb
= table
[m
->exit_code
]);
2137 arm_reboot_watchdog
= m
->exit_code
== MANAGER_REBOOT
;
2139 log_notice("Shutting down.");
2144 assert_not_reached("Unknown exit code.");
2152 arg_shutdown_watchdog
= m
->shutdown_watchdog
;
2154 m
= manager_free(m
);
2156 for (j
= 0; j
< ELEMENTSOF(arg_default_rlimit
); j
++)
2157 arg_default_rlimit
[j
] = mfree(arg_default_rlimit
[j
]);
2159 arg_default_unit
= mfree(arg_default_unit
);
2160 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2161 arg_join_controllers
= strv_free_free(arg_join_controllers
);
2162 arg_default_environment
= strv_free(arg_default_environment
);
2163 arg_syscall_archs
= set_free(arg_syscall_archs
);
2165 mac_selinux_finish();
2169 unsigned i
, args_size
;
2171 /* Close and disarm the watchdog, so that the new
2172 * instance can reinitialize it, but doesn't get
2173 * rebooted while we do that */
2174 watchdog_close(true);
2176 /* Reset the RLIMIT_NOFILE to the kernel default, so
2177 * that the new systemd can pass the kernel default to
2178 * its child processes */
2179 if (saved_rlimit_nofile
.rlim_cur
> 0)
2180 (void) setrlimit(RLIMIT_NOFILE
, &saved_rlimit_nofile
);
2181 if (saved_rlimit_memlock
.rlim_cur
!= (rlim_t
) -1)
2182 (void) setrlimit(RLIMIT_MEMLOCK
, &saved_rlimit_memlock
);
2184 if (switch_root_dir
) {
2185 /* Kill all remaining processes from the
2186 * initrd, but don't wait for them, so that we
2187 * can handle the SIGCHLD for them after
2189 broadcast_signal(SIGTERM
, false, true);
2191 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
2192 r
= switch_root(switch_root_dir
, "/mnt", true, MS_MOVE
);
2194 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
2197 args_size
= MAX(6, argc
+1);
2198 args
= newa(const char*, args_size
);
2200 if (!switch_root_init
) {
2201 char sfd
[DECIMAL_STR_MAX(int) + 1];
2203 /* First try to spawn ourselves with the right
2204 * path, and with full serialization. We do
2205 * this only if the user didn't specify an
2206 * explicit init to spawn. */
2208 assert(arg_serialization
);
2211 xsprintf(sfd
, "%i", fileno(arg_serialization
));
2214 args
[i
++] = SYSTEMD_BINARY_PATH
;
2215 if (switch_root_dir
)
2216 args
[i
++] = "--switched-root";
2217 args
[i
++] = arg_system
? "--system" : "--user";
2218 args
[i
++] = "--deserialize";
2222 assert(i
<= args_size
);
2225 * We want valgrind to print its memory usage summary before reexecution.
2226 * Valgrind won't do this is on its own on exec(), but it will do it on exit().
2227 * Hence, to ensure we get a summary here, fork() off a child, let it exit() cleanly,
2228 * so that it prints the summary, and wait() for it in the parent, before proceeding into the exec().
2230 valgrind_summary_hack();
2232 (void) execv(args
[0], (char* const*) args
);
2235 /* Try the fallback, if there is any, without any
2236 * serialization. We pass the original argv[] and
2237 * envp[]. (Well, modulo the ordering changes due to
2238 * getopt() in argv[], and some cleanups in envp[],
2239 * but let's hope that doesn't matter.) */
2241 arg_serialization
= safe_fclose(arg_serialization
);
2242 fds
= fdset_free(fds
);
2244 /* Reopen the console */
2245 (void) make_console_stdio();
2247 for (j
= 1, i
= 1; j
< (unsigned) argc
; j
++)
2248 args
[i
++] = argv
[j
];
2250 assert(i
<= args_size
);
2252 /* Reenable any blocked signals, especially important
2253 * if we switch from initial ramdisk to init=... */
2254 (void) reset_all_signal_handlers();
2255 (void) reset_signal_mask();
2257 if (switch_root_init
) {
2258 args
[0] = switch_root_init
;
2259 (void) execv(args
[0], (char* const*) args
);
2260 log_warning_errno(errno
, "Failed to execute configured init, trying fallback: %m");
2263 args
[0] = "/sbin/init";
2264 (void) execv(args
[0], (char* const*) args
);
2266 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
2267 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
2268 "Failed to execute /sbin/init");
2270 if (errno
== ENOENT
) {
2271 log_warning("No /sbin/init, trying fallback");
2273 args
[0] = "/bin/sh";
2275 (void) execv(args
[0], (char* const*) args
);
2276 log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
2278 log_warning_errno(errno
, "Failed to execute /sbin/init, giving up: %m");
2280 error_message
= "Failed to execute fallback shell";
2283 arg_serialization
= safe_fclose(arg_serialization
);
2284 fds
= fdset_free(fds
);
2286 #if HAVE_VALGRIND_VALGRIND_H
2287 /* If we are PID 1 and running under valgrind, then let's exit
2288 * here explicitly. valgrind will only generate nice output on
2289 * exit(), not on exec(), hence let's do the former not the
2291 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
)
2295 if (shutdown_verb
) {
2296 r
= become_shutdown(shutdown_verb
, retval
, arm_reboot_watchdog
);
2298 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
2299 error_message
= "Failed to execute shutdown binary";
2302 if (getpid_cached() == 1) {
2304 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
2305 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
2306 "%s, freezing.", error_message
);