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 #ifdef 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 config_parse_many_nulstr(fn
, conf_dirs_nulstr
, "Manager\0", config_item_table_lookup
, items
, false, 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 manager_set_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 int parse_argv(int argc
, char *argv
[]) {
810 ARG_LOG_LEVEL
= 0x100,
820 ARG_DUMP_CONFIGURATION_ITEMS
,
829 ARG_DEFAULT_STD_OUTPUT
,
830 ARG_DEFAULT_STD_ERROR
,
834 static const struct option options
[] = {
835 { "log-level", required_argument
, NULL
, ARG_LOG_LEVEL
},
836 { "log-target", required_argument
, NULL
, ARG_LOG_TARGET
},
837 { "log-color", optional_argument
, NULL
, ARG_LOG_COLOR
},
838 { "log-location", optional_argument
, NULL
, ARG_LOG_LOCATION
},
839 { "unit", required_argument
, NULL
, ARG_UNIT
},
840 { "system", no_argument
, NULL
, ARG_SYSTEM
},
841 { "user", no_argument
, NULL
, ARG_USER
},
842 { "test", no_argument
, NULL
, ARG_TEST
},
843 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
844 { "help", no_argument
, NULL
, 'h' },
845 { "version", no_argument
, NULL
, ARG_VERSION
},
846 { "dump-configuration-items", no_argument
, NULL
, ARG_DUMP_CONFIGURATION_ITEMS
},
847 { "dump-core", optional_argument
, NULL
, ARG_DUMP_CORE
},
848 { "crash-chvt", required_argument
, NULL
, ARG_CRASH_CHVT
},
849 { "crash-shell", optional_argument
, NULL
, ARG_CRASH_SHELL
},
850 { "crash-reboot", optional_argument
, NULL
, ARG_CRASH_REBOOT
},
851 { "confirm-spawn", optional_argument
, NULL
, ARG_CONFIRM_SPAWN
},
852 { "show-status", optional_argument
, NULL
, ARG_SHOW_STATUS
},
853 { "deserialize", required_argument
, NULL
, ARG_DESERIALIZE
},
854 { "switched-root", no_argument
, NULL
, ARG_SWITCHED_ROOT
},
855 { "default-standard-output", required_argument
, NULL
, ARG_DEFAULT_STD_OUTPUT
, },
856 { "default-standard-error", required_argument
, NULL
, ARG_DEFAULT_STD_ERROR
, },
857 { "machine-id", required_argument
, NULL
, ARG_MACHINE_ID
},
866 if (getpid_cached() == 1)
869 while ((c
= getopt_long(argc
, argv
, "hDbsz:", options
, NULL
)) >= 0)
874 r
= log_set_max_level_from_string(optarg
);
876 log_error("Failed to parse log level %s.", optarg
);
883 r
= log_set_target_from_string(optarg
);
885 log_error("Failed to parse log target %s.", optarg
);
894 r
= log_show_color_from_string(optarg
);
896 log_error("Failed to parse log color setting %s.", optarg
);
900 log_show_color(true);
904 case ARG_LOG_LOCATION
:
906 r
= log_show_location_from_string(optarg
);
908 log_error("Failed to parse log location setting %s.", optarg
);
912 log_show_location(true);
916 case ARG_DEFAULT_STD_OUTPUT
:
917 r
= exec_output_from_string(optarg
);
919 log_error("Failed to parse default standard output setting %s.", optarg
);
922 arg_default_std_output
= r
;
925 case ARG_DEFAULT_STD_ERROR
:
926 r
= exec_output_from_string(optarg
);
928 log_error("Failed to parse default standard error output setting %s.", optarg
);
931 arg_default_std_error
= r
;
935 r
= free_and_strdup(&arg_default_unit
, optarg
);
937 return log_error_errno(r
, "Failed to set default unit %s: %m", optarg
);
950 arg_action
= ACTION_TEST
;
958 arg_action
= ACTION_VERSION
;
961 case ARG_DUMP_CONFIGURATION_ITEMS
:
962 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
967 arg_dump_core
= true;
969 r
= parse_boolean(optarg
);
971 return log_error_errno(r
, "Failed to parse dump core boolean: %s", optarg
);
977 r
= parse_crash_chvt(optarg
);
979 return log_error_errno(r
, "Failed to parse crash virtual terminal index: %s", optarg
);
982 case ARG_CRASH_SHELL
:
984 arg_crash_shell
= true;
986 r
= parse_boolean(optarg
);
988 return log_error_errno(r
, "Failed to parse crash shell boolean: %s", optarg
);
993 case ARG_CRASH_REBOOT
:
995 arg_crash_reboot
= true;
997 r
= parse_boolean(optarg
);
999 return log_error_errno(r
, "Failed to parse crash shell boolean: %s", optarg
);
1000 arg_crash_reboot
= r
;
1004 case ARG_CONFIRM_SPAWN
:
1005 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
1007 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
1009 return log_error_errno(r
, "Failed to parse confirm spawn option: %m");
1012 case ARG_SHOW_STATUS
:
1014 r
= parse_show_status(optarg
, &arg_show_status
);
1016 log_error("Failed to parse show status boolean %s.", optarg
);
1020 arg_show_status
= SHOW_STATUS_YES
;
1023 case ARG_DESERIALIZE
: {
1027 r
= safe_atoi(optarg
, &fd
);
1028 if (r
< 0 || fd
< 0) {
1029 log_error("Failed to parse deserialize option %s.", optarg
);
1033 (void) fd_cloexec(fd
, true);
1035 f
= fdopen(fd
, "r");
1037 return log_error_errno(errno
, "Failed to open serialization fd: %m");
1039 safe_fclose(arg_serialization
);
1040 arg_serialization
= f
;
1045 case ARG_SWITCHED_ROOT
:
1046 arg_switched_root
= true;
1049 case ARG_MACHINE_ID
:
1050 r
= set_machine_id(optarg
);
1052 return log_error_errno(r
, "MachineID '%s' is not valid.", optarg
);
1056 arg_action
= ACTION_HELP
;
1060 log_set_max_level(LOG_DEBUG
);
1066 /* Just to eat away the sysvinit kernel
1067 * cmdline args without getopt() error
1068 * messages that we'll parse in
1069 * parse_proc_cmdline_word() or ignore. */
1072 if (getpid_cached() != 1)
1078 assert_not_reached("Unhandled option code.");
1081 if (optind
< argc
&& getpid_cached() != 1) {
1082 /* Hmm, when we aren't run as init system
1083 * let's complain about excess arguments */
1085 log_error("Excess arguments.");
1092 static int help(void) {
1094 printf("%s [OPTIONS...]\n\n"
1095 "Starts up and maintains the system or user services.\n\n"
1096 " -h --help Show this help\n"
1097 " --version Show version\n"
1098 " --test Determine startup sequence, dump it and exit\n"
1099 " --no-pager Do not pipe output into a pager\n"
1100 " --dump-configuration-items Dump understood unit configuration items\n"
1101 " --unit=UNIT Set default unit\n"
1102 " --system Run a system instance, even if PID != 1\n"
1103 " --user Run a user instance\n"
1104 " --dump-core[=BOOL] Dump core on crash\n"
1105 " --crash-vt=NR Change to specified VT on crash\n"
1106 " --crash-reboot[=BOOL] Reboot on crash\n"
1107 " --crash-shell[=BOOL] Run shell on crash\n"
1108 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1109 " --show-status[=BOOL] Show status updates on the console during bootup\n"
1110 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
1111 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1112 " --log-color[=BOOL] Highlight important log messages\n"
1113 " --log-location[=BOOL] Include code location in log messages\n"
1114 " --default-standard-output= Set default standard output for services\n"
1115 " --default-standard-error= Set default standard error output for services\n",
1116 program_invocation_short_name
);
1121 static int prepare_reexecute(Manager
*m
, FILE **_f
, FDSet
**_fds
, bool switching_root
) {
1122 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1123 _cleanup_fclose_
FILE *f
= NULL
;
1130 r
= manager_open_serialization(m
, &f
);
1132 return log_error_errno(r
, "Failed to create serialization file: %m");
1134 /* Make sure nothing is really destructed when we shut down */
1136 bus_manager_send_reloading(m
, true);
1142 r
= manager_serialize(m
, f
, fds
, switching_root
);
1144 return log_error_errno(r
, "Failed to serialize state: %m");
1146 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1147 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1149 r
= fd_cloexec(fileno(f
), false);
1151 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1153 r
= fdset_cloexec(fds
, false);
1155 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1166 static int bump_rlimit_nofile(struct rlimit
*saved_rlimit
) {
1170 _cleanup_free_
char *nr_open
= NULL
;
1172 assert(saved_rlimit
);
1174 /* Save the original RLIMIT_NOFILE so that we can reset it
1175 * later when transitioning from the initrd to the main
1176 * systemd or suchlike. */
1177 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit
) < 0)
1178 return log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
1180 /* Make sure forked processes get the default kernel setting */
1181 if (!arg_default_rlimit
[RLIMIT_NOFILE
]) {
1184 rl
= newdup(struct rlimit
, saved_rlimit
, 1);
1188 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
1191 /* Get current RLIMIT_NOFILE maximum compiled into the kernel. */
1192 r
= read_one_line_file("/proc/sys/fs/nr_open", &nr_open
);
1194 r
= safe_atoi(nr_open
, &min_max
);
1195 /* If we fail, fallback to the hard-coded kernel limit of 1024 * 1024. */
1197 min_max
= 1024 * 1024;
1199 /* Bump up the resource limit for ourselves substantially */
1200 nl
.rlim_cur
= nl
.rlim_max
= min_max
;
1201 r
= setrlimit_closest(RLIMIT_NOFILE
, &nl
);
1203 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1208 static int bump_rlimit_memlock(struct rlimit
*saved_rlimit
) {
1211 assert(saved_rlimit
);
1212 assert(getuid() == 0);
1214 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even though we have CAP_IPC_LOCK which
1215 * should normally disable such checks. We need them to implement IPAccessAllow= and IPAccessDeny=, hence let's
1216 * bump the value high enough for the root user. */
1218 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit
) < 0)
1219 return log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
1221 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &RLIMIT_MAKE_CONST(1024ULL*1024ULL*16ULL));
1223 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1228 static void test_usr(void) {
1230 /* Check that /usr is not a separate fs */
1232 if (dir_is_empty("/usr") <= 0)
1235 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1236 "Some things will probably break (sometimes even silently) in mysterious ways. "
1237 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1240 static int initialize_join_controllers(void) {
1241 /* By default, mount "cpu" + "cpuacct" together, and "net_cls"
1242 * + "net_prio". We'd like to add "cpuset" to the mix, but
1243 * "cpuset" doesn't really work for groups with no initialized
1246 arg_join_controllers
= new(char**, 3);
1247 if (!arg_join_controllers
)
1250 arg_join_controllers
[0] = strv_new("cpu", "cpuacct", NULL
);
1251 if (!arg_join_controllers
[0])
1254 arg_join_controllers
[1] = strv_new("net_cls", "net_prio", NULL
);
1255 if (!arg_join_controllers
[1])
1258 arg_join_controllers
[2] = NULL
;
1262 arg_join_controllers
= strv_free_free(arg_join_controllers
);
1266 static int enforce_syscall_archs(Set
*archs
) {
1270 if (!is_seccomp_available())
1273 r
= seccomp_restrict_archs(arg_syscall_archs
);
1275 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1280 static int status_welcome(void) {
1281 _cleanup_free_
char *pretty_name
= NULL
, *ansi_color
= NULL
;
1284 r
= parse_env_file("/etc/os-release", NEWLINE
,
1285 "PRETTY_NAME", &pretty_name
,
1286 "ANSI_COLOR", &ansi_color
,
1289 r
= parse_env_file("/usr/lib/os-release", NEWLINE
,
1290 "PRETTY_NAME", &pretty_name
,
1291 "ANSI_COLOR", &ansi_color
,
1294 if (r
< 0 && r
!= -ENOENT
)
1295 log_warning_errno(r
, "Failed to read os-release file: %m");
1297 if (log_get_show_color())
1298 return status_printf(NULL
, false, false,
1299 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1300 isempty(ansi_color
) ? "1" : ansi_color
,
1301 isempty(pretty_name
) ? "Linux" : pretty_name
);
1303 return status_printf(NULL
, false, false,
1304 "\nWelcome to %s!\n",
1305 isempty(pretty_name
) ? "Linux" : pretty_name
);
1308 static int write_container_id(void) {
1312 c
= getenv("container");
1316 RUN_WITH_UMASK(0022)
1317 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1319 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1324 static int bump_unix_max_dgram_qlen(void) {
1325 _cleanup_free_
char *qlen
= NULL
;
1329 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel
1330 * default of 16 is simply too low. We set the value really
1331 * really early during boot, so that it is actually applied to
1332 * all our sockets, including the $NOTIFY_SOCKET one. */
1334 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1336 return log_warning_errno(r
, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1338 r
= safe_atolu(qlen
, &v
);
1340 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length, ignoring: %m");
1342 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1346 if (asprintf(&qlen
, "%lu\n", DEFAULT_UNIX_MAX_DGRAM_QLEN
) < 0)
1349 r
= write_string_file("/proc/sys/net/unix/max_dgram_qlen", qlen
, 0);
1351 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1352 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1357 static int fixup_environment(void) {
1358 _cleanup_free_
char *term
= NULL
;
1361 /* We expect the environment to be set correctly
1362 * if run inside a container. */
1363 if (detect_container() > 0)
1366 /* When started as PID1, the kernel uses /dev/console
1367 * for our stdios and uses TERM=linux whatever the
1368 * backend device used by the console. We try to make
1369 * a better guess here since some consoles might not
1370 * have support for color mode for example.
1372 * However if TERM was configured through the kernel
1373 * command line then leave it alone. */
1375 r
= proc_cmdline_get_key("TERM", 0, &term
);
1379 term
= strdup(default_term_for_tty("/dev/console"));
1384 if (setenv("TERM", term
, 1) < 0)
1390 int main(int argc
, char *argv
[]) {
1392 int r
, retval
= EXIT_FAILURE
;
1393 usec_t before_startup
, after_startup
;
1394 char timespan
[FORMAT_TIMESPAN_MAX
];
1396 bool reexecute
= false;
1397 const char *shutdown_verb
= NULL
;
1398 dual_timestamp initrd_timestamp
= DUAL_TIMESTAMP_NULL
;
1399 dual_timestamp userspace_timestamp
= DUAL_TIMESTAMP_NULL
;
1400 dual_timestamp kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
1401 dual_timestamp security_start_timestamp
= DUAL_TIMESTAMP_NULL
;
1402 dual_timestamp security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
1403 static char systemd
[] = "systemd";
1404 bool skip_setup
= false;
1406 bool loaded_policy
= false;
1407 bool arm_reboot_watchdog
= false;
1408 bool queue_default_job
= false;
1409 bool empty_etc
= false;
1410 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
1411 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0), saved_rlimit_memlock
= RLIMIT_MAKE_CONST((rlim_t
) -1);
1412 const char *error_message
= NULL
;
1414 #ifdef HAVE_SYSV_COMPAT
1415 if (getpid_cached() != 1 && strstr(program_invocation_short_name
, "init")) {
1416 /* This is compatibility support for SysV, where
1417 * calling init as a user is identical to telinit. */
1419 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1420 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1425 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
1426 dual_timestamp_get(&userspace_timestamp
);
1428 /* Determine if this is a reexecution or normal bootup. We do
1429 * the full command line parsing much later, so let's just
1430 * have a quick peek here. */
1431 if (strv_find(argv
+1, "--deserialize"))
1434 /* If we have switched root, do all the special setup
1436 if (strv_find(argv
+1, "--switched-root"))
1439 /* If we get started via the /sbin/init symlink then we are
1440 called 'init'. After a subsequent reexecution we are then
1441 called 'systemd'. That is confusing, hence let's call us
1442 systemd right-away. */
1443 program_invocation_short_name
= systemd
;
1444 (void) prctl(PR_SET_NAME
, systemd
);
1449 log_set_upgrade_syslog_to_journal(true);
1451 if (getpid_cached() == 1) {
1452 /* Disable the umask logic */
1455 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
1456 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
1457 * child process right before execve()'ing the actual binary, at a point in time where socket
1458 * activation stderr/stdout area already set up. */
1459 log_set_always_reopen_console(true);
1462 if (getpid_cached() == 1 && detect_container() <= 0) {
1464 /* Running outside of a container as PID 1 */
1466 log_set_target(LOG_TARGET_KMSG
);
1470 initrd_timestamp
= userspace_timestamp
;
1473 r
= mount_setup_early();
1475 error_message
= "Failed to mount early API filesystems";
1479 dual_timestamp_get(&security_start_timestamp
);
1480 if (mac_selinux_setup(&loaded_policy
) < 0) {
1481 error_message
= "Failed to load SELinux policy";
1483 } else if (mac_smack_setup(&loaded_policy
) < 0) {
1484 error_message
= "Failed to load SMACK policy";
1486 } else if (ima_setup() < 0) {
1487 error_message
= "Failed to load IMA policy";
1490 dual_timestamp_get(&security_finish_timestamp
);
1493 if (mac_selinux_init() < 0) {
1494 error_message
= "Failed to initialize SELinux policy";
1499 if (clock_is_localtime(NULL
) > 0) {
1503 * The very first call of settimeofday() also does a time warp in the kernel.
1505 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on
1506 * external tools to take care of maintaining the RTC and do all adjustments.
1507 * This matches the behavior of Windows, which leaves the RTC alone if the
1508 * registry tells that the RTC runs in UTC.
1510 r
= clock_set_timezone(&min
);
1512 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1514 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1515 } else if (!in_initrd()) {
1517 * Do a dummy very first call to seal the kernel's time warp magic.
1519 * Do not call this from inside the initrd. The initrd might not
1520 * carry /etc/adjtime with LOCAL, but the real system could be set up
1521 * that way. In such case, we need to delay the time-warp or the sealing
1522 * until we reach the real system.
1524 * Do no set the kernel's timezone. The concept of local time cannot
1525 * be supported reliably, the time will jump or be incorrect at every daylight
1526 * saving time change. All kernel local time concepts will be treated
1529 (void) clock_reset_timewarp();
1532 r
= clock_apply_epoch();
1534 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1536 log_info("System time before build time, advancing clock.");
1539 /* Set the default for later on, but don't actually
1540 * open the logs like this for now. Note that if we
1541 * are transitioning from the initrd there might still
1542 * be journal fd open, and we shouldn't attempt
1543 * opening that before we parsed /proc/cmdline which
1544 * might redirect output elsewhere. */
1545 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
1547 } else if (getpid_cached() == 1) {
1548 /* Running inside a container, as PID 1 */
1550 log_set_target(LOG_TARGET_CONSOLE
);
1551 log_close_console(); /* force reopen of /dev/console */
1554 /* For later on, see above... */
1555 log_set_target(LOG_TARGET_JOURNAL
);
1557 /* clear the kernel timestamp,
1558 * because we are in a container */
1559 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
1561 /* Running as user instance */
1563 log_set_target(LOG_TARGET_AUTO
);
1566 /* clear the kernel timestamp,
1567 * because we are not PID 1 */
1568 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
1571 if (getpid_cached() == 1) {
1572 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1573 * will process core dumps for system services by default. */
1574 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1575 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1577 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1578 * until the systemd-coredump tool is enabled via sysctl. */
1580 (void) write_string_file("/proc/sys/kernel/core_pattern", "|/bin/false", 0);
1584 if (fixup_environment() < 0) {
1585 error_message
= "Failed to fix up PID1 environment";
1589 /* Try to figure out if we can use colors with the console. No
1590 * need to do that for user instances since they never log
1591 * into the console. */
1592 log_show_color(colors_enabled());
1593 r
= make_null_stdio();
1595 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null: %m");
1598 r
= initialize_join_controllers();
1600 error_message
= "Failed to initialize cgroup controllers";
1604 /* Mount /proc, /sys and friends, so that /proc/cmdline and
1605 * /proc/$PID/fd is available. */
1606 if (getpid_cached() == 1) {
1608 /* Load the kernel modules early. */
1612 r
= mount_setup(loaded_policy
);
1614 error_message
= "Failed to mount API filesystems";
1619 /* Reset all signal handlers. */
1620 (void) reset_all_signal_handlers();
1621 (void) ignore_signals(SIGNALS_IGNORE
, -1);
1623 arg_default_tasks_max
= system_tasks_max_scale(DEFAULT_TASKS_MAX_PERCENTAGE
, 100U);
1625 if (parse_config_file() < 0) {
1626 error_message
= "Failed to parse config file";
1631 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
1633 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
1636 /* Note that this also parses bits from the kernel command
1637 * line, including "debug". */
1638 log_parse_environment();
1640 if (parse_argv(argc
, argv
) < 0) {
1641 error_message
= "Failed to parse commandline arguments";
1645 /* Initialize default unit */
1646 if (!arg_default_unit
) {
1647 arg_default_unit
= strdup(SPECIAL_DEFAULT_TARGET
);
1648 if (!arg_default_unit
) {
1650 error_message
= "Failed to set default unit";
1655 if (arg_action
== ACTION_TEST
&&
1657 log_error("Don't run test mode as root.");
1662 arg_action
== ACTION_RUN
&&
1664 log_error("Trying to run as user instance, but the system has not been booted with systemd.");
1669 arg_action
== ACTION_RUN
&&
1670 running_in_chroot() > 0) {
1671 log_error("Cannot be run in a chroot() environment.");
1675 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
)) {
1676 pager_open(arg_no_pager
, false);
1680 if (arg_action
== ACTION_HELP
) {
1683 } else if (arg_action
== ACTION_VERSION
) {
1686 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
1687 pager_open(arg_no_pager
, false);
1688 unit_dump_config_items(stdout
);
1689 retval
= EXIT_SUCCESS
;
1694 !getenv("XDG_RUNTIME_DIR")) {
1695 log_error("Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
1699 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
1701 /* Close logging fds, in order not to confuse fdset below */
1704 /* Remember open file descriptors for later deserialization */
1705 if (arg_action
== ACTION_RUN
) {
1706 r
= fdset_new_fill(&fds
);
1708 log_emergency_errno(r
, "Failed to allocate fd set: %m");
1709 error_message
= "Failed to allocate fd set";
1712 fdset_cloexec(fds
, true);
1714 if (arg_serialization
)
1715 assert_se(fdset_remove(fds
, fileno(arg_serialization
)) >= 0);
1718 /* Become a session leader if we aren't one yet. */
1722 /* Move out of the way, so that we won't block unmounts */
1723 assert_se(chdir("/") == 0);
1725 /* Reset the console, but only if this is really init and we
1726 * are freshly booted */
1727 if (arg_system
&& arg_action
== ACTION_RUN
) {
1729 /* If we are init, we connect stdin/stdout/stderr to
1730 * /dev/null and make sure we don't have a controlling
1734 if (getpid_cached() == 1 && !skip_setup
)
1738 /* Open the logging devices, if possible and necessary */
1741 if (arg_show_status
== _SHOW_STATUS_UNSET
)
1742 arg_show_status
= SHOW_STATUS_YES
;
1744 /* Make sure we leave a core dump without panicing the
1746 if (getpid_cached() == 1) {
1747 install_crash_handler();
1749 r
= mount_cgroup_controllers(arg_join_controllers
);
1757 log_info(PACKAGE_STRING
" running in %ssystem mode. (" SYSTEMD_FEATURES
")",
1758 arg_action
== ACTION_TEST
? "test " : "" );
1760 v
= detect_virtualization();
1762 log_info("Detected virtualization %s.", virtualization_to_string(v
));
1764 write_container_id();
1766 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
1769 log_info("Running in initial RAM disk.");
1771 /* Let's check whether /etc is already populated. We
1772 * don't actually really check for that, but use
1773 * /etc/machine-id as flag file. This allows container
1774 * managers and installers to provision a couple of
1775 * files already. If the container manager wants to
1776 * provision the machine ID itself it should pass
1777 * $container_uuid to PID 1. */
1779 empty_etc
= access("/etc/machine-id", F_OK
) < 0;
1781 log_info("Running with unpopulated /etc.");
1783 _cleanup_free_
char *t
;
1785 t
= uid_to_name(getuid());
1786 log_debug(PACKAGE_STRING
" running in %suser mode for user "UID_FMT
"/%s. (" SYSTEMD_FEATURES
")",
1787 arg_action
== ACTION_TEST
? " test" : "", getuid(), t
);
1790 if (arg_action
== ACTION_RUN
) {
1791 if (arg_system
&& !skip_setup
) {
1792 if (arg_show_status
> 0)
1796 machine_id_setup(NULL
, arg_machine_id
, NULL
);
1798 bump_unix_max_dgram_qlen();
1803 if (arg_system
&& arg_runtime_watchdog
> 0 && arg_runtime_watchdog
!= USEC_INFINITY
)
1804 watchdog_set_timeout(&arg_runtime_watchdog
);
1806 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
1807 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
1808 log_error_errno(errno
, "Failed to adjust timer slack: %m");
1810 if (arg_system
&& !cap_test_all(arg_capability_bounding_set
)) {
1811 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
1813 log_emergency_errno(r
, "Failed to drop capability bounding set of usermode helpers: %m");
1814 error_message
= "Failed to drop capability bounding set of usermode helpers";
1817 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
1819 log_emergency_errno(r
, "Failed to drop capability bounding set: %m");
1820 error_message
= "Failed to drop capability bounding set";
1825 if (arg_syscall_archs
) {
1826 r
= enforce_syscall_archs(arg_syscall_archs
);
1828 error_message
= "Failed to set syscall architectures";
1834 /* Become reaper of our children */
1835 if (prctl(PR_SET_CHILD_SUBREAPER
, 1) < 0)
1836 log_warning_errno(errno
, "Failed to make us a subreaper: %m");
1839 /* Bump up RLIMIT_NOFILE for systemd itself */
1840 (void) bump_rlimit_nofile(&saved_rlimit_nofile
);
1841 (void) bump_rlimit_memlock(&saved_rlimit_memlock
);
1845 r
= manager_new(arg_system
? UNIT_FILE_SYSTEM
: UNIT_FILE_USER
,
1846 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
1849 log_emergency_errno(r
, "Failed to allocate manager object: %m");
1850 error_message
= "Failed to allocate manager object";
1854 m
->confirm_spawn
= arg_confirm_spawn
;
1855 m
->runtime_watchdog
= arg_runtime_watchdog
;
1856 m
->shutdown_watchdog
= arg_shutdown_watchdog
;
1857 m
->userspace_timestamp
= userspace_timestamp
;
1858 m
->kernel_timestamp
= kernel_timestamp
;
1859 m
->initrd_timestamp
= initrd_timestamp
;
1860 m
->security_start_timestamp
= security_start_timestamp
;
1861 m
->security_finish_timestamp
= security_finish_timestamp
;
1862 m
->cad_burst_action
= arg_cad_burst_action
;
1864 manager_set_defaults(m
);
1865 manager_set_show_status(m
, arg_show_status
);
1866 manager_set_first_boot(m
, empty_etc
);
1868 /* Remember whether we should queue the default job */
1869 queue_default_job
= !arg_serialization
|| arg_switched_root
;
1871 before_startup
= now(CLOCK_MONOTONIC
);
1873 r
= manager_startup(m
, arg_serialization
, fds
);
1875 log_error_errno(r
, "Failed to fully start up daemon: %m");
1879 /* This will close all file descriptors that were opened, but
1880 * not claimed by any unit. */
1881 fds
= fdset_free(fds
);
1883 arg_serialization
= safe_fclose(arg_serialization
);
1885 if (queue_default_job
) {
1886 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1887 Unit
*target
= NULL
;
1888 Job
*default_unit_job
;
1890 log_debug("Activating default unit: %s", arg_default_unit
);
1892 r
= manager_load_unit(m
, arg_default_unit
, NULL
, &error
, &target
);
1894 log_error("Failed to load default target: %s", bus_error_message(&error
, r
));
1895 else if (IN_SET(target
->load_state
, UNIT_ERROR
, UNIT_NOT_FOUND
))
1896 log_error_errno(target
->load_error
, "Failed to load default target: %m");
1897 else if (target
->load_state
== UNIT_MASKED
)
1898 log_error("Default target masked.");
1900 if (!target
|| target
->load_state
!= UNIT_LOADED
) {
1901 log_info("Trying to load rescue target...");
1903 r
= manager_load_unit(m
, SPECIAL_RESCUE_TARGET
, NULL
, &error
, &target
);
1905 log_emergency("Failed to load rescue target: %s", bus_error_message(&error
, r
));
1906 error_message
= "Failed to load rescue target";
1908 } else if (IN_SET(target
->load_state
, UNIT_ERROR
, UNIT_NOT_FOUND
)) {
1909 log_emergency_errno(target
->load_error
, "Failed to load rescue target: %m");
1910 error_message
= "Failed to load rescue target";
1912 } else if (target
->load_state
== UNIT_MASKED
) {
1913 log_emergency("Rescue target masked.");
1914 error_message
= "Rescue target masked";
1919 assert(target
->load_state
== UNIT_LOADED
);
1921 if (arg_action
== ACTION_TEST
) {
1922 printf("-> By units:\n");
1923 manager_dump_units(m
, stdout
, "\t");
1926 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, &error
, &default_unit_job
);
1928 log_debug("Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
1930 sd_bus_error_free(&error
);
1932 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, &error
, &default_unit_job
);
1934 log_emergency("Failed to start default target: %s", bus_error_message(&error
, r
));
1935 error_message
= "Failed to start default target";
1939 log_emergency("Failed to isolate default target: %s", bus_error_message(&error
, r
));
1940 error_message
= "Failed to isolate default target";
1944 m
->default_unit_job_id
= default_unit_job
->id
;
1946 after_startup
= now(CLOCK_MONOTONIC
);
1947 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
1948 "Loaded units and determined initial transaction in %s.",
1949 format_timespan(timespan
, sizeof(timespan
), after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
1951 if (arg_action
== ACTION_TEST
) {
1952 printf("-> By jobs:\n");
1953 manager_dump_jobs(m
, stdout
, "\t");
1954 retval
= EXIT_SUCCESS
;
1960 r
= manager_loop(m
);
1962 log_emergency_errno(r
, "Failed to run main loop: %m");
1963 error_message
= "Failed to run main loop";
1967 switch (m
->exit_code
) {
1969 case MANAGER_RELOAD
:
1970 log_info("Reloading.");
1972 r
= parse_config_file();
1974 log_error("Failed to parse config file.");
1976 manager_set_defaults(m
);
1978 r
= manager_reload(m
);
1980 log_error_errno(r
, "Failed to reload: %m");
1983 case MANAGER_REEXECUTE
:
1985 if (prepare_reexecute(m
, &arg_serialization
, &fds
, false) < 0) {
1986 error_message
= "Failed to prepare for reexecution";
1991 log_notice("Reexecuting.");
1994 case MANAGER_SWITCH_ROOT
:
1995 /* Steal the switch root parameters */
1996 switch_root_dir
= m
->switch_root
;
1997 switch_root_init
= m
->switch_root_init
;
1998 m
->switch_root
= m
->switch_root_init
= NULL
;
2000 if (!switch_root_init
)
2001 if (prepare_reexecute(m
, &arg_serialization
, &fds
, true) < 0) {
2002 error_message
= "Failed to prepare for reexecution";
2007 log_notice("Switching root.");
2011 retval
= m
->return_value
;
2013 if (MANAGER_IS_USER(m
)) {
2019 case MANAGER_REBOOT
:
2020 case MANAGER_POWEROFF
:
2022 case MANAGER_KEXEC
: {
2023 static const char * const table
[_MANAGER_EXIT_CODE_MAX
] = {
2024 [MANAGER_EXIT
] = "exit",
2025 [MANAGER_REBOOT
] = "reboot",
2026 [MANAGER_POWEROFF
] = "poweroff",
2027 [MANAGER_HALT
] = "halt",
2028 [MANAGER_KEXEC
] = "kexec"
2031 assert_se(shutdown_verb
= table
[m
->exit_code
]);
2032 arm_reboot_watchdog
= m
->exit_code
== MANAGER_REBOOT
;
2034 log_notice("Shutting down.");
2039 assert_not_reached("Unknown exit code.");
2047 arg_shutdown_watchdog
= m
->shutdown_watchdog
;
2049 m
= manager_free(m
);
2051 for (j
= 0; j
< ELEMENTSOF(arg_default_rlimit
); j
++)
2052 arg_default_rlimit
[j
] = mfree(arg_default_rlimit
[j
]);
2054 arg_default_unit
= mfree(arg_default_unit
);
2055 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2056 arg_join_controllers
= strv_free_free(arg_join_controllers
);
2057 arg_default_environment
= strv_free(arg_default_environment
);
2058 arg_syscall_archs
= set_free(arg_syscall_archs
);
2060 mac_selinux_finish();
2064 unsigned i
, args_size
;
2066 /* Close and disarm the watchdog, so that the new
2067 * instance can reinitialize it, but doesn't get
2068 * rebooted while we do that */
2069 watchdog_close(true);
2071 /* Reset the RLIMIT_NOFILE to the kernel default, so
2072 * that the new systemd can pass the kernel default to
2073 * its child processes */
2074 if (saved_rlimit_nofile
.rlim_cur
> 0)
2075 (void) setrlimit(RLIMIT_NOFILE
, &saved_rlimit_nofile
);
2076 if (saved_rlimit_memlock
.rlim_cur
!= (rlim_t
) -1)
2077 (void) setrlimit(RLIMIT_MEMLOCK
, &saved_rlimit_memlock
);
2079 if (switch_root_dir
) {
2080 /* Kill all remaining processes from the
2081 * initrd, but don't wait for them, so that we
2082 * can handle the SIGCHLD for them after
2084 broadcast_signal(SIGTERM
, false, true);
2086 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
2087 r
= switch_root(switch_root_dir
, "/mnt", true, MS_MOVE
);
2089 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
2092 args_size
= MAX(6, argc
+1);
2093 args
= newa(const char*, args_size
);
2095 if (!switch_root_init
) {
2096 char sfd
[DECIMAL_STR_MAX(int) + 1];
2098 /* First try to spawn ourselves with the right
2099 * path, and with full serialization. We do
2100 * this only if the user didn't specify an
2101 * explicit init to spawn. */
2103 assert(arg_serialization
);
2106 xsprintf(sfd
, "%i", fileno(arg_serialization
));
2109 args
[i
++] = SYSTEMD_BINARY_PATH
;
2110 if (switch_root_dir
)
2111 args
[i
++] = "--switched-root";
2112 args
[i
++] = arg_system
? "--system" : "--user";
2113 args
[i
++] = "--deserialize";
2117 assert(i
<= args_size
);
2120 * We want valgrind to print its memory usage summary before reexecution.
2121 * Valgrind won't do this is on its own on exec(), but it will do it on exit().
2122 * Hence, to ensure we get a summary here, fork() off a child, let it exit() cleanly,
2123 * so that it prints the summary, and wait() for it in the parent, before proceeding into the exec().
2125 valgrind_summary_hack();
2127 (void) execv(args
[0], (char* const*) args
);
2130 /* Try the fallback, if there is any, without any
2131 * serialization. We pass the original argv[] and
2132 * envp[]. (Well, modulo the ordering changes due to
2133 * getopt() in argv[], and some cleanups in envp[],
2134 * but let's hope that doesn't matter.) */
2136 arg_serialization
= safe_fclose(arg_serialization
);
2137 fds
= fdset_free(fds
);
2139 /* Reopen the console */
2140 (void) make_console_stdio();
2142 for (j
= 1, i
= 1; j
< (unsigned) argc
; j
++)
2143 args
[i
++] = argv
[j
];
2145 assert(i
<= args_size
);
2147 /* Reenable any blocked signals, especially important
2148 * if we switch from initial ramdisk to init=... */
2149 (void) reset_all_signal_handlers();
2150 (void) reset_signal_mask();
2152 if (switch_root_init
) {
2153 args
[0] = switch_root_init
;
2154 (void) execv(args
[0], (char* const*) args
);
2155 log_warning_errno(errno
, "Failed to execute configured init, trying fallback: %m");
2158 args
[0] = "/sbin/init";
2159 (void) execv(args
[0], (char* const*) args
);
2161 if (errno
== ENOENT
) {
2162 log_warning("No /sbin/init, trying fallback");
2164 args
[0] = "/bin/sh";
2166 (void) execv(args
[0], (char* const*) args
);
2167 log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
2169 log_warning_errno(errno
, "Failed to execute /sbin/init, giving up: %m");
2172 arg_serialization
= safe_fclose(arg_serialization
);
2173 fds
= fdset_free(fds
);
2175 #ifdef HAVE_VALGRIND_VALGRIND_H
2176 /* If we are PID 1 and running under valgrind, then let's exit
2177 * here explicitly. valgrind will only generate nice output on
2178 * exit(), not on exec(), hence let's do the former not the
2180 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
)
2184 if (shutdown_verb
) {
2185 char log_level
[DECIMAL_STR_MAX(int) + 1];
2186 char exit_code
[DECIMAL_STR_MAX(uint8_t) + 1];
2187 const char* command_line
[11] = {
2188 SYSTEMD_SHUTDOWN_BINARY_PATH
,
2190 "--log-level", log_level
,
2194 _cleanup_strv_free_
char **env_block
= NULL
;
2196 assert(command_line
[pos
] == NULL
);
2197 env_block
= strv_copy(environ
);
2199 xsprintf(log_level
, "%d", log_get_max_level());
2201 switch (log_get_target()) {
2203 case LOG_TARGET_KMSG
:
2204 case LOG_TARGET_JOURNAL_OR_KMSG
:
2205 case LOG_TARGET_SYSLOG_OR_KMSG
:
2206 command_line
[pos
++] = "kmsg";
2209 case LOG_TARGET_NULL
:
2210 command_line
[pos
++] = "null";
2213 case LOG_TARGET_CONSOLE
:
2215 command_line
[pos
++] = "console";
2219 if (log_get_show_color())
2220 command_line
[pos
++] = "--log-color";
2222 if (log_get_show_location())
2223 command_line
[pos
++] = "--log-location";
2225 if (streq(shutdown_verb
, "exit")) {
2226 command_line
[pos
++] = "--exit-code";
2227 command_line
[pos
++] = exit_code
;
2228 xsprintf(exit_code
, "%d", retval
);
2231 assert(pos
< ELEMENTSOF(command_line
));
2233 if (arm_reboot_watchdog
&& arg_shutdown_watchdog
> 0 && arg_shutdown_watchdog
!= USEC_INFINITY
) {
2236 /* If we reboot let's set the shutdown
2237 * watchdog and tell the shutdown binary to
2238 * repeatedly ping it */
2239 r
= watchdog_set_timeout(&arg_shutdown_watchdog
);
2240 watchdog_close(r
< 0);
2242 /* Tell the binary how often to ping, ignore failure */
2243 if (asprintf(&e
, "WATCHDOG_USEC="USEC_FMT
, arg_shutdown_watchdog
) > 0)
2244 (void) strv_push(&env_block
, e
);
2246 watchdog_close(true);
2248 /* Avoid the creation of new processes forked by the
2249 * kernel; at this point, we will not listen to the
2251 if (detect_container() <= 0)
2252 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
2254 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
2255 log_error_errno(errno
, "Failed to execute shutdown binary, %s: %m",
2256 getpid_cached() == 1 ? "freezing" : "quitting");
2259 if (getpid_cached() == 1) {
2261 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
2262 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
2263 "%s, freezing.", error_message
);