1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include <sys/utsname.h>
11 #if HAVE_VALGRIND_VALGRIND_H
12 # include <valgrind/valgrind.h>
16 #include "sd-daemon.h"
17 #include "sd-messages.h"
19 #include "alloc-util.h"
20 #include "apparmor-setup.h"
21 #include "architecture.h"
22 #include "argv-util.h"
27 #include "bus-error.h"
29 #include "capability-util.h"
30 #include "cgroup-util.h"
32 #include "clock-util.h"
33 #include "conf-parser.h"
34 #include "confidential-virt.h"
36 #include "cpu-set-util.h"
37 #include "crash-handler.h"
38 #include "dbus-manager.h"
40 #include "constants.h"
41 #include "dev-setup.h"
42 #include "efi-random.h"
44 #include "emergency-action.h"
46 #include "exit-status.h"
50 #include "format-util.h"
52 #include "getopt-defs.h"
53 #include "hexdecoct.h"
54 #include "hostname-setup.h"
55 #include "ima-setup.h"
56 #include "import-creds.h"
57 #include "initrd-util.h"
59 #include "kmod-setup.h"
60 #include "limits-util.h"
61 #include "load-fragment.h"
63 #include "loopback-setup.h"
64 #include "machine-id-setup.h"
67 #include "manager-dump.h"
68 #include "manager-serialize.h"
69 #include "mkdir-label.h"
70 #include "mount-setup.h"
73 #include "parse-argument.h"
74 #include "parse-util.h"
75 #include "path-util.h"
76 #include "pretty-print.h"
77 #include "proc-cmdline.h"
78 #include "process-util.h"
80 #include "random-util.h"
81 #include "rlimit-util.h"
82 #include "seccomp-util.h"
83 #include "selinux-setup.h"
84 #include "selinux-util.h"
85 #include "signal-util.h"
86 #include "smack-setup.h"
88 #include "stat-util.h"
89 #include "stdio-util.h"
91 #include "switch-root.h"
92 #include "sysctl-util.h"
93 #include "terminal-util.h"
94 #include "time-util.h"
95 #include "umask-util.h"
96 #include "user-util.h"
101 #if HAS_FEATURE_ADDRESS_SANITIZER
102 #include <sanitizer/lsan_interface.h>
105 #define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
112 ACTION_DUMP_CONFIGURATION_ITEMS
,
113 ACTION_DUMP_BUS_PROPERTIES
,
114 ACTION_BUS_INTROSPECT
,
115 } arg_action
= ACTION_RUN
;
117 static const char *arg_bus_introspect
= NULL
;
119 /* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
120 * defaults are assigned in reset_arguments() below. */
121 static char *arg_default_unit
;
122 static RuntimeScope arg_runtime_scope
;
125 bool arg_crash_shell
;
126 bool arg_crash_reboot
;
127 static char *arg_confirm_spawn
;
128 static ShowStatus arg_show_status
;
129 static StatusUnitFormat arg_status_unit_format
;
130 static bool arg_switched_root
;
131 static PagerFlags arg_pager_flags
;
132 static bool arg_service_watchdogs
;
133 static ExecOutput arg_default_std_output
;
134 static ExecOutput arg_default_std_error
;
135 static usec_t arg_default_restart_usec
;
136 static usec_t arg_default_timeout_start_usec
;
137 static usec_t arg_default_timeout_stop_usec
;
138 static usec_t arg_default_timeout_abort_usec
;
139 static usec_t arg_default_device_timeout_usec
;
140 static bool arg_default_timeout_abort_set
;
141 static usec_t arg_default_start_limit_interval
;
142 static unsigned arg_default_start_limit_burst
;
143 static usec_t arg_runtime_watchdog
;
144 static usec_t arg_reboot_watchdog
;
145 static usec_t arg_kexec_watchdog
;
146 static usec_t arg_pretimeout_watchdog
;
147 static char *arg_early_core_pattern
;
148 static char *arg_watchdog_pretimeout_governor
;
149 static char *arg_watchdog_device
;
150 static char **arg_default_environment
;
151 static char **arg_manager_environment
;
152 static struct rlimit
*arg_default_rlimit
[_RLIMIT_MAX
];
153 static uint64_t arg_capability_bounding_set
;
154 static bool arg_no_new_privs
;
155 static nsec_t arg_timer_slack_nsec
;
156 static usec_t arg_default_timer_accuracy_usec
;
157 static Set
* arg_syscall_archs
;
158 static FILE* arg_serialization
;
159 static int arg_default_cpu_accounting
;
160 static bool arg_default_io_accounting
;
161 static bool arg_default_ip_accounting
;
162 static bool arg_default_blockio_accounting
;
163 static bool arg_default_memory_accounting
;
164 static bool arg_default_tasks_accounting
;
165 static TasksMax arg_default_tasks_max
;
166 static usec_t arg_default_memory_pressure_threshold_usec
;
167 static CGroupPressureWatch arg_default_memory_pressure_watch
;
168 static sd_id128_t arg_machine_id
;
169 static EmergencyAction arg_cad_burst_action
;
170 static OOMPolicy arg_default_oom_policy
;
171 static CPUSet arg_cpu_affinity
;
172 static NUMAPolicy arg_numa_policy
;
173 static usec_t arg_clock_usec
;
174 static void *arg_random_seed
;
175 static size_t arg_random_seed_size
;
176 static int arg_default_oom_score_adjust
;
177 static bool arg_default_oom_score_adjust_set
;
178 static char *arg_default_smack_process_label
;
179 static usec_t arg_reload_limit_interval_sec
;
180 static unsigned arg_reload_limit_burst
;
182 /* A copy of the original environment block */
183 static char **saved_env
= NULL
;
185 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
186 const struct rlimit
*saved_rlimit_memlock
);
188 static int manager_find_user_config_paths(char ***ret_files
, char ***ret_dirs
) {
189 _cleanup_free_
char *base
= NULL
;
190 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
193 r
= xdg_user_config_dir(&base
, "/systemd");
197 r
= strv_extendf(&files
, "%s/user.conf", base
);
201 r
= strv_extend(&files
, PKGSYSCONFDIR
"/user.conf");
205 r
= strv_consume(&dirs
, TAKE_PTR(base
));
209 r
= strv_extend_strv(&dirs
, CONF_PATHS_STRV("systemd"), false);
213 *ret_files
= TAKE_PTR(files
);
214 *ret_dirs
= TAKE_PTR(dirs
);
218 static int console_setup(void) {
219 _cleanup_close_
int tty_fd
= -EBADF
;
223 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
225 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
227 /* We don't want to force text mode. plymouth may be showing
228 * pictures already from initrd. */
229 r
= reset_terminal_fd(tty_fd
, false);
231 return log_error_errno(r
, "Failed to reset /dev/console: %m");
233 r
= proc_cmdline_tty_size("/dev/console", &rows
, &cols
);
235 log_warning_errno(r
, "Failed to get terminal size, ignoring: %m");
237 r
= terminal_set_size_fd(tty_fd
, NULL
, rows
, cols
);
239 log_warning_errno(r
, "Failed to set terminal size, ignoring: %m");
245 static int set_machine_id(const char *m
) {
249 if (sd_id128_from_string(m
, &t
) < 0)
252 if (sd_id128_is_null(t
))
259 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
264 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
266 if (proc_cmdline_value_missing(key
, value
))
269 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
270 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
271 else if (in_initrd() == !!startswith(key
, "rd."))
272 return free_and_strdup_warn(&arg_default_unit
, value
);
274 } else if (proc_cmdline_key_streq(key
, "systemd.dump_core")) {
276 r
= value
? parse_boolean(value
) : true;
278 log_warning_errno(r
, "Failed to parse dump core switch %s, ignoring: %m", value
);
282 } else if (proc_cmdline_key_streq(key
, "systemd.early_core_pattern")) {
284 if (proc_cmdline_value_missing(key
, value
))
287 if (path_is_absolute(value
))
288 (void) parse_path_argument(value
, false, &arg_early_core_pattern
);
290 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value
);
292 } else if (proc_cmdline_key_streq(key
, "systemd.crash_chvt")) {
295 arg_crash_chvt
= 0; /* turn on */
297 r
= parse_crash_chvt(value
, &arg_crash_chvt
);
299 log_warning_errno(r
, "Failed to parse crash chvt switch %s, ignoring: %m", value
);
302 } else if (proc_cmdline_key_streq(key
, "systemd.crash_shell")) {
304 r
= value
? parse_boolean(value
) : true;
306 log_warning_errno(r
, "Failed to parse crash shell switch %s, ignoring: %m", value
);
310 } else if (proc_cmdline_key_streq(key
, "systemd.crash_reboot")) {
312 r
= value
? parse_boolean(value
) : true;
314 log_warning_errno(r
, "Failed to parse crash reboot switch %s, ignoring: %m", value
);
316 arg_crash_reboot
= r
;
318 } else if (proc_cmdline_key_streq(key
, "systemd.confirm_spawn")) {
321 r
= parse_confirm_spawn(value
, &s
);
323 log_warning_errno(r
, "Failed to parse confirm_spawn switch %s, ignoring: %m", value
);
325 free_and_replace(arg_confirm_spawn
, s
);
327 } else if (proc_cmdline_key_streq(key
, "systemd.service_watchdogs")) {
329 r
= value
? parse_boolean(value
) : true;
331 log_warning_errno(r
, "Failed to parse service watchdog switch %s, ignoring: %m", value
);
333 arg_service_watchdogs
= r
;
335 } else if (proc_cmdline_key_streq(key
, "systemd.show_status")) {
338 r
= parse_show_status(value
, &arg_show_status
);
340 log_warning_errno(r
, "Failed to parse show status switch %s, ignoring: %m", value
);
342 arg_show_status
= SHOW_STATUS_YES
;
344 } else if (proc_cmdline_key_streq(key
, "systemd.status_unit_format")) {
346 if (proc_cmdline_value_missing(key
, value
))
349 r
= status_unit_format_from_string(value
);
351 log_warning_errno(r
, "Failed to parse %s=%s, ignoring: %m", key
, value
);
353 arg_status_unit_format
= r
;
355 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_output")) {
357 if (proc_cmdline_value_missing(key
, value
))
360 r
= exec_output_from_string(value
);
362 log_warning_errno(r
, "Failed to parse default standard output switch %s, ignoring: %m", value
);
364 arg_default_std_output
= r
;
366 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_error")) {
368 if (proc_cmdline_value_missing(key
, value
))
371 r
= exec_output_from_string(value
);
373 log_warning_errno(r
, "Failed to parse default standard error switch %s, ignoring: %m", value
);
375 arg_default_std_error
= r
;
377 } else if (streq(key
, "systemd.setenv")) {
379 if (proc_cmdline_value_missing(key
, value
))
382 if (!env_assignment_is_valid(value
))
383 log_warning("Environment variable assignment '%s' is not valid. Ignoring.", value
);
385 r
= strv_env_replace_strdup(&arg_default_environment
, value
);
390 } else if (proc_cmdline_key_streq(key
, "systemd.machine_id")) {
392 if (proc_cmdline_value_missing(key
, value
))
395 r
= set_machine_id(value
);
397 log_warning_errno(r
, "MachineID '%s' is not valid, ignoring: %m", value
);
399 } else if (proc_cmdline_key_streq(key
, "systemd.default_timeout_start_sec")) {
401 if (proc_cmdline_value_missing(key
, value
))
404 r
= parse_sec(value
, &arg_default_timeout_start_usec
);
406 log_warning_errno(r
, "Failed to parse default start timeout '%s', ignoring: %m", value
);
408 if (arg_default_timeout_start_usec
<= 0)
409 arg_default_timeout_start_usec
= USEC_INFINITY
;
411 } else if (proc_cmdline_key_streq(key
, "systemd.default_device_timeout_sec")) {
413 if (proc_cmdline_value_missing(key
, value
))
416 r
= parse_sec(value
, &arg_default_device_timeout_usec
);
418 log_warning_errno(r
, "Failed to parse default device timeout '%s', ignoring: %m", value
);
420 if (arg_default_device_timeout_usec
<= 0)
421 arg_default_device_timeout_usec
= USEC_INFINITY
;
423 } else if (proc_cmdline_key_streq(key
, "systemd.cpu_affinity")) {
425 if (proc_cmdline_value_missing(key
, value
))
428 r
= parse_cpu_set(value
, &arg_cpu_affinity
);
430 log_warning_errno(r
, "Failed to parse CPU affinity mask '%s', ignoring: %m", value
);
432 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_device")) {
434 if (proc_cmdline_value_missing(key
, value
))
437 (void) parse_path_argument(value
, false, &arg_watchdog_device
);
439 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_sec")) {
441 if (proc_cmdline_value_missing(key
, value
))
444 if (streq(value
, "default"))
445 arg_runtime_watchdog
= USEC_INFINITY
;
446 else if (streq(value
, "off"))
447 arg_runtime_watchdog
= 0;
449 r
= parse_sec(value
, &arg_runtime_watchdog
);
451 log_warning_errno(r
, "Failed to parse systemd.watchdog_sec= argument '%s', ignoring: %m", value
);
456 arg_kexec_watchdog
= arg_reboot_watchdog
= arg_runtime_watchdog
;
458 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pre_sec")) {
460 if (proc_cmdline_value_missing(key
, value
))
463 if (streq(value
, "default"))
464 arg_pretimeout_watchdog
= USEC_INFINITY
;
465 else if (streq(value
, "off"))
466 arg_pretimeout_watchdog
= 0;
468 r
= parse_sec(value
, &arg_pretimeout_watchdog
);
470 log_warning_errno(r
, "Failed to parse systemd.watchdog_pre_sec= argument '%s', ignoring: %m", value
);
475 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pretimeout_governor")) {
477 if (proc_cmdline_value_missing(key
, value
) || isempty(value
)) {
478 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
482 if (!string_is_safe(value
)) {
483 log_warning("Watchdog pretimeout governor '%s' is not valid, ignoring.", value
);
487 return free_and_strdup_warn(&arg_watchdog_pretimeout_governor
, value
);
489 } else if (proc_cmdline_key_streq(key
, "systemd.clock_usec")) {
491 if (proc_cmdline_value_missing(key
, value
))
494 r
= safe_atou64(value
, &arg_clock_usec
);
496 log_warning_errno(r
, "Failed to parse systemd.clock_usec= argument, ignoring: %s", value
);
498 } else if (proc_cmdline_key_streq(key
, "systemd.random_seed")) {
502 if (proc_cmdline_value_missing(key
, value
))
505 r
= unbase64mem(value
, SIZE_MAX
, &p
, &sz
);
507 log_warning_errno(r
, "Failed to parse systemd.random_seed= argument, ignoring: %s", value
);
509 free(arg_random_seed
);
510 arg_random_seed
= sz
> 0 ? p
: mfree(p
);
511 arg_random_seed_size
= sz
;
513 } else if (proc_cmdline_key_streq(key
, "systemd.reload_limit_interval_sec")) {
515 if (proc_cmdline_value_missing(key
, value
))
518 r
= parse_sec(value
, &arg_reload_limit_interval_sec
);
520 log_warning_errno(r
, "Failed to parse systemd.reload_limit_interval_sec= argument '%s', ignoring: %m", value
);
524 } else if (proc_cmdline_key_streq(key
, "systemd.reload_limit_burst")) {
526 if (proc_cmdline_value_missing(key
, value
))
529 r
= safe_atou(value
, &arg_reload_limit_burst
);
531 log_warning_errno(r
, "Failed to parse systemd.reload_limit_burst= argument '%s', ignoring: %m", value
);
535 } else if (streq(key
, "quiet") && !value
) {
537 if (arg_show_status
== _SHOW_STATUS_INVALID
)
538 arg_show_status
= SHOW_STATUS_ERROR
;
540 } else if (streq(key
, "debug") && !value
) {
542 /* Note that log_parse_environment() handles 'debug'
543 * too, and sets the log level to LOG_DEBUG. */
545 if (detect_container() > 0)
546 log_set_target(LOG_TARGET_CONSOLE
);
551 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
552 target
= runlevel_to_target(key
);
554 return free_and_strdup_warn(&arg_default_unit
, target
);
560 #define DEFINE_SETTER(name, func, descr) \
561 static int name(const char *unit, \
562 const char *filename, \
564 const char *section, \
565 unsigned section_line, \
566 const char *lvalue, \
568 const char *rvalue, \
580 log_syntax(unit, LOG_ERR, filename, line, r, \
581 "Invalid " descr "'%s': %m", \
587 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level");
588 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target");
589 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color");
590 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location");
591 DEFINE_SETTER(config_parse_time
, log_show_time_from_string
, "time");
593 static int config_parse_default_timeout_abort(
595 const char *filename
,
598 unsigned section_line
,
606 r
= config_parse_timeout_abort(unit
, filename
, line
, section
, section_line
, lvalue
, ltype
, rvalue
,
607 &arg_default_timeout_abort_usec
, userdata
);
609 arg_default_timeout_abort_set
= r
;
613 static int config_parse_oom_score_adjust(
615 const char *filename
,
618 unsigned section_line
,
627 if (isempty(rvalue
)) {
628 arg_default_oom_score_adjust_set
= false;
632 r
= parse_oom_score_adjust(rvalue
, &oa
);
634 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse the OOM score adjust value '%s', ignoring: %m", rvalue
);
638 arg_default_oom_score_adjust
= oa
;
639 arg_default_oom_score_adjust_set
= true;
644 static int parse_config_file(void) {
645 const ConfigTableItem items
[] = {
646 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
647 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
648 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
649 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
650 { "Manager", "LogTime", config_parse_time
, 0, NULL
},
651 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
652 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, &arg_crash_chvt
},
653 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, &arg_crash_chvt
},
654 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
655 { "Manager", "CrashReboot", config_parse_bool
, 0, &arg_crash_reboot
},
656 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
657 { "Manager", "StatusUnitFormat", config_parse_status_unit_format
, 0, &arg_status_unit_format
},
658 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, &arg_cpu_affinity
},
659 { "Manager", "NUMAPolicy", config_parse_numa_policy
, 0, &arg_numa_policy
.type
},
660 { "Manager", "NUMAMask", config_parse_numa_mask
, 0, &arg_numa_policy
},
661 { "Manager", "JoinControllers", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
662 { "Manager", "RuntimeWatchdogSec", config_parse_watchdog_sec
, 0, &arg_runtime_watchdog
},
663 { "Manager", "RuntimeWatchdogPreSec", config_parse_watchdog_sec
, 0, &arg_pretimeout_watchdog
},
664 { "Manager", "RebootWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
},
665 { "Manager", "ShutdownWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
}, /* obsolete alias */
666 { "Manager", "KExecWatchdogSec", config_parse_watchdog_sec
, 0, &arg_kexec_watchdog
},
667 { "Manager", "WatchdogDevice", config_parse_path
, 0, &arg_watchdog_device
},
668 { "Manager", "RuntimeWatchdogPreGovernor", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &arg_watchdog_pretimeout_governor
},
669 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
670 { "Manager", "NoNewPrivileges", config_parse_bool
, 0, &arg_no_new_privs
},
672 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
674 { "Manager", "SystemCallArchitectures", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
677 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
678 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_default_timer_accuracy_usec
},
679 { "Manager", "DefaultStandardOutput", config_parse_output_restricted
, 0, &arg_default_std_output
},
680 { "Manager", "DefaultStandardError", config_parse_output_restricted
, 0, &arg_default_std_error
},
681 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_default_timeout_start_usec
},
682 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_default_timeout_stop_usec
},
683 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort
, 0, NULL
},
684 { "Manager", "DefaultDeviceTimeoutSec", config_parse_sec
, 0, &arg_default_device_timeout_usec
},
685 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_default_restart_usec
},
686 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_default_start_limit_interval
}, /* obsolete alias */
687 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec
, 0, &arg_default_start_limit_interval
},
688 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_default_start_limit_burst
},
689 { "Manager", "DefaultEnvironment", config_parse_environ
, arg_runtime_scope
, &arg_default_environment
},
690 { "Manager", "ManagerEnvironment", config_parse_environ
, arg_runtime_scope
, &arg_manager_environment
},
691 { "Manager", "DefaultLimitCPU", config_parse_rlimit
, RLIMIT_CPU
, arg_default_rlimit
},
692 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit
, RLIMIT_FSIZE
, arg_default_rlimit
},
693 { "Manager", "DefaultLimitDATA", config_parse_rlimit
, RLIMIT_DATA
, arg_default_rlimit
},
694 { "Manager", "DefaultLimitSTACK", config_parse_rlimit
, RLIMIT_STACK
, arg_default_rlimit
},
695 { "Manager", "DefaultLimitCORE", config_parse_rlimit
, RLIMIT_CORE
, arg_default_rlimit
},
696 { "Manager", "DefaultLimitRSS", config_parse_rlimit
, RLIMIT_RSS
, arg_default_rlimit
},
697 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit
, RLIMIT_NOFILE
, arg_default_rlimit
},
698 { "Manager", "DefaultLimitAS", config_parse_rlimit
, RLIMIT_AS
, arg_default_rlimit
},
699 { "Manager", "DefaultLimitNPROC", config_parse_rlimit
, RLIMIT_NPROC
, arg_default_rlimit
},
700 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit
, RLIMIT_MEMLOCK
, arg_default_rlimit
},
701 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit
, RLIMIT_LOCKS
, arg_default_rlimit
},
702 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit
, RLIMIT_SIGPENDING
, arg_default_rlimit
},
703 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit
, RLIMIT_MSGQUEUE
, arg_default_rlimit
},
704 { "Manager", "DefaultLimitNICE", config_parse_rlimit
, RLIMIT_NICE
, arg_default_rlimit
},
705 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit
, RLIMIT_RTPRIO
, arg_default_rlimit
},
706 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit
, RLIMIT_RTTIME
, arg_default_rlimit
},
707 { "Manager", "DefaultCPUAccounting", config_parse_tristate
, 0, &arg_default_cpu_accounting
},
708 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_default_io_accounting
},
709 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_default_ip_accounting
},
710 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_default_blockio_accounting
},
711 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_default_memory_accounting
},
712 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_default_tasks_accounting
},
713 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_default_tasks_max
},
714 { "Manager", "DefaultMemoryPressureThresholdSec", config_parse_sec
, 0, &arg_default_memory_pressure_threshold_usec
},
715 { "Manager", "DefaultMemoryPressureWatch", config_parse_memory_pressure_watch
, 0, &arg_default_memory_pressure_watch
},
716 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, arg_runtime_scope
, &arg_cad_burst_action
},
717 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy
, 0, &arg_default_oom_policy
},
718 { "Manager", "DefaultOOMScoreAdjust", config_parse_oom_score_adjust
, 0, NULL
},
719 { "Manager", "ReloadLimitIntervalSec", config_parse_sec
, 0, &arg_reload_limit_interval_sec
},
720 { "Manager", "ReloadLimitBurst", config_parse_unsigned
, 0, &arg_reload_limit_burst
},
722 { "Manager", "DefaultSmackProcessLabel", config_parse_string
, 0, &arg_default_smack_process_label
},
724 { "Manager", "DefaultSmackProcessLabel", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
729 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
)
730 (void) config_parse_config_file("system.conf",
732 config_item_table_lookup
, items
,
736 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
739 assert(arg_runtime_scope
== RUNTIME_SCOPE_USER
);
741 r
= manager_find_user_config_paths(&files
, &dirs
);
743 return log_error_errno(r
, "Failed to determine config file paths: %m");
745 (void) config_parse_many(
746 (const char* const*) files
,
747 (const char* const*) dirs
,
751 config_item_table_lookup
, items
,
756 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we use
757 * USEC_INFINITY like everywhere else. */
758 if (arg_default_timeout_start_usec
<= 0)
759 arg_default_timeout_start_usec
= USEC_INFINITY
;
760 if (arg_default_timeout_stop_usec
<= 0)
761 arg_default_timeout_stop_usec
= USEC_INFINITY
;
766 static void set_manager_defaults(Manager
*m
) {
770 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
771 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
772 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
774 m
->default_timer_accuracy_usec
= arg_default_timer_accuracy_usec
;
775 m
->default_std_output
= arg_default_std_output
;
776 m
->default_std_error
= arg_default_std_error
;
777 m
->default_timeout_start_usec
= arg_default_timeout_start_usec
;
778 m
->default_timeout_stop_usec
= arg_default_timeout_stop_usec
;
779 m
->default_timeout_abort_usec
= arg_default_timeout_abort_usec
;
780 m
->default_timeout_abort_set
= arg_default_timeout_abort_set
;
781 m
->default_device_timeout_usec
= arg_default_device_timeout_usec
;
782 m
->default_restart_usec
= arg_default_restart_usec
;
783 m
->default_start_limit_interval
= arg_default_start_limit_interval
;
784 m
->default_start_limit_burst
= arg_default_start_limit_burst
;
786 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
787 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
788 if (arg_default_cpu_accounting
>= 0)
789 m
->default_cpu_accounting
= arg_default_cpu_accounting
;
791 m
->default_cpu_accounting
= cpu_accounting_is_cheap();
793 m
->default_io_accounting
= arg_default_io_accounting
;
794 m
->default_ip_accounting
= arg_default_ip_accounting
;
795 m
->default_blockio_accounting
= arg_default_blockio_accounting
;
796 m
->default_memory_accounting
= arg_default_memory_accounting
;
797 m
->default_tasks_accounting
= arg_default_tasks_accounting
;
798 m
->default_tasks_max
= arg_default_tasks_max
;
799 m
->default_memory_pressure_watch
= arg_default_memory_pressure_watch
;
800 m
->default_memory_pressure_threshold_usec
= arg_default_memory_pressure_threshold_usec
;
801 m
->default_oom_policy
= arg_default_oom_policy
;
802 m
->default_oom_score_adjust_set
= arg_default_oom_score_adjust_set
;
803 m
->default_oom_score_adjust
= arg_default_oom_score_adjust
;
805 (void) manager_set_default_smack_process_label(m
, arg_default_smack_process_label
);
807 (void) manager_set_default_rlimits(m
, arg_default_rlimit
);
809 (void) manager_default_environment(m
);
810 (void) manager_transient_environment_add(m
, arg_default_environment
);
813 static void set_manager_settings(Manager
*m
) {
818 /* Propagates the various manager settings into the manager object, i.e. properties that
819 * effect the manager itself (as opposed to just being inherited into newly allocated
820 * units, see set_manager_defaults() above). */
822 m
->confirm_spawn
= arg_confirm_spawn
;
823 m
->service_watchdogs
= arg_service_watchdogs
;
824 m
->cad_burst_action
= arg_cad_burst_action
;
825 /* Note that we don't do structured initialization here, otherwise it will reset the rate limit
826 * counter on every daemon-reload. */
827 m
->reload_ratelimit
.interval
= arg_reload_limit_interval_sec
;
828 m
->reload_ratelimit
.burst
= arg_reload_limit_burst
;
830 manager_set_watchdog(m
, WATCHDOG_RUNTIME
, arg_runtime_watchdog
);
831 manager_set_watchdog(m
, WATCHDOG_REBOOT
, arg_reboot_watchdog
);
832 manager_set_watchdog(m
, WATCHDOG_KEXEC
, arg_kexec_watchdog
);
833 manager_set_watchdog(m
, WATCHDOG_PRETIMEOUT
, arg_pretimeout_watchdog
);
834 r
= manager_set_watchdog_pretimeout_governor(m
, arg_watchdog_pretimeout_governor
);
836 log_warning_errno(r
, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor
);
838 manager_set_show_status(m
, arg_show_status
, "commandline");
839 m
->status_unit_format
= arg_status_unit_format
;
842 static int parse_argv(int argc
, char *argv
[]) {
848 static const struct option options
[] = {
849 COMMON_GETOPT_OPTIONS
,
850 SYSTEMD_GETOPT_OPTIONS
,
855 bool user_arg_seen
= false;
860 if (getpid_cached() == 1)
863 while ((c
= getopt_long(argc
, argv
, SYSTEMD_GETOPT_SHORT_OPTIONS
, options
, NULL
)) >= 0)
868 r
= log_set_max_level_from_string(optarg
);
870 return log_error_errno(r
, "Failed to parse log level \"%s\": %m", optarg
);
875 r
= log_set_target_from_string(optarg
);
877 return log_error_errno(r
, "Failed to parse log target \"%s\": %m", optarg
);
884 r
= log_show_color_from_string(optarg
);
886 return log_error_errno(r
, "Failed to parse log color setting \"%s\": %m",
889 log_show_color(true);
893 case ARG_LOG_LOCATION
:
895 r
= log_show_location_from_string(optarg
);
897 return log_error_errno(r
, "Failed to parse log location setting \"%s\": %m",
900 log_show_location(true);
907 r
= log_show_time_from_string(optarg
);
909 return log_error_errno(r
, "Failed to parse log time setting \"%s\": %m",
916 case ARG_DEFAULT_STD_OUTPUT
:
917 r
= exec_output_from_string(optarg
);
919 return log_error_errno(r
, "Failed to parse default standard output setting \"%s\": %m",
921 arg_default_std_output
= r
;
924 case ARG_DEFAULT_STD_ERROR
:
925 r
= exec_output_from_string(optarg
);
927 return log_error_errno(r
, "Failed to parse default standard error output setting \"%s\": %m",
929 arg_default_std_error
= r
;
933 r
= free_and_strdup(&arg_default_unit
, optarg
);
935 return log_error_errno(r
, "Failed to set default unit \"%s\": %m", optarg
);
940 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
944 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
945 user_arg_seen
= true;
949 arg_action
= ACTION_TEST
;
953 arg_pager_flags
|= PAGER_DISABLE
;
957 arg_action
= ACTION_VERSION
;
960 case ARG_DUMP_CONFIGURATION_ITEMS
:
961 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
964 case ARG_DUMP_BUS_PROPERTIES
:
965 arg_action
= ACTION_DUMP_BUS_PROPERTIES
;
968 case ARG_BUS_INTROSPECT
:
969 arg_bus_introspect
= optarg
;
970 arg_action
= ACTION_BUS_INTROSPECT
;
974 r
= parse_boolean_argument("--dump-core", optarg
, &arg_dump_core
);
980 r
= parse_crash_chvt(optarg
, &arg_crash_chvt
);
982 return log_error_errno(r
, "Failed to parse crash virtual terminal index: \"%s\": %m",
986 case ARG_CRASH_SHELL
:
987 r
= parse_boolean_argument("--crash-shell", optarg
, &arg_crash_shell
);
992 case ARG_CRASH_REBOOT
:
993 r
= parse_boolean_argument("--crash-reboot", optarg
, &arg_crash_reboot
);
998 case ARG_CONFIRM_SPAWN
:
999 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
1001 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
1003 return log_error_errno(r
, "Failed to parse confirm spawn option: \"%s\": %m",
1007 case ARG_SERVICE_WATCHDOGS
:
1008 r
= parse_boolean_argument("--service-watchdogs=", optarg
, &arg_service_watchdogs
);
1013 case ARG_SHOW_STATUS
:
1015 r
= parse_show_status(optarg
, &arg_show_status
);
1017 return log_error_errno(r
, "Failed to parse show status boolean: \"%s\": %m",
1020 arg_show_status
= SHOW_STATUS_YES
;
1023 case ARG_DESERIALIZE
: {
1027 fd
= parse_fd(optarg
);
1029 return log_error_errno(fd
, "Failed to parse serialization fd \"%s\": %m", optarg
);
1031 (void) fd_cloexec(fd
, true);
1033 f
= fdopen(fd
, "r");
1035 return log_error_errno(errno
, "Failed to open serialization fd %d: %m", fd
);
1037 safe_fclose(arg_serialization
);
1038 arg_serialization
= f
;
1043 case ARG_SWITCHED_ROOT
:
1044 arg_switched_root
= true;
1047 case ARG_MACHINE_ID
:
1048 r
= set_machine_id(optarg
);
1050 return log_error_errno(r
, "MachineID '%s' is not valid: %m", optarg
);
1054 arg_action
= ACTION_HELP
;
1058 log_set_max_level(LOG_DEBUG
);
1064 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1065 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1068 if (getpid_cached() != 1)
1074 assert_not_reached();
1077 if (optind
< argc
&& getpid_cached() != 1)
1078 /* Hmm, when we aren't run as init system let's complain about excess arguments */
1079 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Excess arguments.");
1081 if (arg_action
== ACTION_RUN
&& arg_runtime_scope
== RUNTIME_SCOPE_USER
&& !user_arg_seen
)
1082 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1083 "Explicit --user argument required to run as user manager.");
1088 static int help(void) {
1089 _cleanup_free_
char *link
= NULL
;
1092 r
= terminal_urlify_man("systemd", "1", &link
);
1096 printf("%s [OPTIONS...]\n\n"
1097 "%sStarts and monitors system and user services.%s\n\n"
1098 "This program takes no positional arguments.\n\n"
1100 " -h --help Show this help\n"
1101 " --version Show version\n"
1102 " --test Determine initial transaction, dump it and exit\n"
1103 " --system Combined with --test: operate in system mode\n"
1104 " --user Combined with --test: operate in user mode\n"
1105 " --dump-configuration-items Dump understood unit configuration items\n"
1106 " --dump-bus-properties Dump exposed bus properties\n"
1107 " --bus-introspect=PATH Write XML introspection data\n"
1108 " --unit=UNIT Set default unit\n"
1109 " --dump-core[=BOOL] Dump core on crash\n"
1110 " --crash-vt=NR Change to specified VT on crash\n"
1111 " --crash-reboot[=BOOL] Reboot on crash\n"
1112 " --crash-shell[=BOOL] Run shell on crash\n"
1113 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1114 " --show-status[=BOOL] Show status updates on the console during boot\n"
1115 " --log-target=TARGET Set log target (console, journal, kmsg,\n"
1116 " journal-or-kmsg, null)\n"
1117 " --log-level=LEVEL Set log level (debug, info, notice, warning,\n"
1118 " err, crit, alert, emerg)\n"
1119 " --log-color[=BOOL] Highlight important log messages\n"
1120 " --log-location[=BOOL] Include code location in log messages\n"
1121 " --log-time[=BOOL] Prefix log messages with current time\n"
1122 " --default-standard-output= Set default standard output for services\n"
1123 " --default-standard-error= Set default standard error output for services\n"
1124 " --no-pager Do not pipe output into a pager\n"
1125 "\nSee the %s for details.\n",
1126 program_invocation_short_name
,
1136 static int prepare_reexecute(
1140 bool switching_root
) {
1142 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1143 _cleanup_fclose_
FILE *f
= NULL
;
1150 r
= manager_open_serialization(m
, &f
);
1152 return log_error_errno(r
, "Failed to create serialization file: %m");
1154 /* Make sure nothing is really destructed when we shut down */
1156 bus_manager_send_reloading(m
, true);
1162 r
= manager_serialize(m
, f
, fds
, switching_root
);
1166 if (fseeko(f
, 0, SEEK_SET
) == (off_t
) -1)
1167 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1169 r
= fd_cloexec(fileno(f
), false);
1171 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1173 r
= fdset_cloexec(fds
, false);
1175 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1177 *ret_f
= TAKE_PTR(f
);
1178 *ret_fds
= TAKE_PTR(fds
);
1183 static void bump_file_max_and_nr_open(void) {
1185 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
1186 * numbers of file descriptors are no longer a performance problem and their memory is properly
1187 * tracked by memcg, thus counting them and limiting them in another two layers of limits is
1188 * unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
1189 * on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
1191 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1195 #if BUMP_PROC_SYS_FS_FILE_MAX
1196 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
1197 * different, but the operation would fail silently.) */
1198 r
= sysctl_write("fs/file-max", LONG_MAX_STR
);
1200 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
,
1201 r
, "Failed to bump fs.file-max, ignoring: %m");
1204 #if BUMP_PROC_SYS_FS_NR_OPEN
1207 /* Argh! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know
1208 * what they are. The expression by which the maximum is determined is dependent on the architecture,
1209 * and is something we don't really want to copy to userspace, as it is dependent on implementation
1210 * details of the kernel. Since the kernel doesn't expose the maximum value to us, we can only try
1211 * and hope. Hence, let's start with INT_MAX, and then keep halving the value until we find one that
1212 * works. Ugly? Yes, absolutely, but kernel APIs are kernel APIs, so what do can we do... 🤯 */
1217 v
&= ~(__SIZEOF_POINTER__
- 1); /* Round down to next multiple of the pointer size */
1219 log_warning("Can't bump fs.nr_open, value too small.");
1225 log_error_errno(k
, "Failed to read fs.nr_open: %m");
1228 if (k
>= v
) { /* Already larger */
1229 log_debug("Skipping bump, value is already larger.");
1233 r
= sysctl_writef("fs/nr_open", "%i", v
);
1235 log_debug("Couldn't write fs.nr_open as %i, halving it.", v
);
1240 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.nr_open, ignoring: %m");
1244 log_debug("Successfully bumped fs.nr_open to %i", v
);
1250 static int bump_rlimit_nofile(const struct rlimit
*saved_rlimit
) {
1251 struct rlimit new_rlimit
;
1254 /* Get the underlying absolute limit the kernel enforces */
1255 nr
= read_nr_open();
1257 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1258 new_rlimit
= (struct rlimit
) {
1259 .rlim_cur
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_cur
),
1260 .rlim_max
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_max
),
1263 /* Shortcut if nothing changes. */
1264 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_max
&&
1265 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_cur
) {
1266 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1270 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1271 * both hard and soft. */
1272 r
= setrlimit_closest(RLIMIT_NOFILE
, &new_rlimit
);
1274 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1279 static int bump_rlimit_memlock(const struct rlimit
*saved_rlimit
) {
1280 struct rlimit new_rlimit
;
1284 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
1285 * which should normally disable such checks. We need them to implement IPAddressAllow= and
1286 * IPAddressDeny=, hence let's bump the value high enough for our user. */
1288 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1289 * must be unsigned, hence this is a given, but let's make this clear here. */
1290 assert_cc(RLIM_INFINITY
> 0);
1292 mm
= physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
1293 * physical RAM. We allow an eighth to be locked by us, just to
1296 new_rlimit
= (struct rlimit
) {
1297 .rlim_cur
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_cur
, mm
),
1298 .rlim_max
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_max
, mm
),
1301 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_cur
&&
1302 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_max
) {
1303 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1307 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &new_rlimit
);
1309 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1314 static void test_usr(void) {
1316 /* Check that /usr is either on the same file system as / or mounted already. */
1318 if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) <= 0)
1321 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1322 "Some things will probably break (sometimes even silently) in mysterious ways. "
1323 "Consult https://www.freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1326 static int enforce_syscall_archs(Set
*archs
) {
1330 if (!is_seccomp_available())
1333 r
= seccomp_restrict_archs(arg_syscall_archs
);
1335 return log_error_errno(r
, "Failed to enforce system call architecture restrication: %m");
1340 static int os_release_status(void) {
1341 _cleanup_free_
char *pretty_name
= NULL
, *name
= NULL
, *version
= NULL
,
1342 *ansi_color
= NULL
, *support_end
= NULL
;
1345 r
= parse_os_release(NULL
,
1346 "PRETTY_NAME", &pretty_name
,
1348 "VERSION", &version
,
1349 "ANSI_COLOR", &ansi_color
,
1350 "SUPPORT_END", &support_end
);
1352 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1353 "Failed to read os-release file, ignoring: %m");
1355 const char *label
= os_release_pretty_name(pretty_name
, name
);
1357 if (show_status_on(arg_show_status
)) {
1358 if (log_get_show_color())
1359 status_printf(NULL
, 0,
1360 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1361 empty_to_null(ansi_color
) ?: "1",
1364 status_printf(NULL
, 0,
1365 "\nWelcome to %s!\n",
1369 if (support_end
&& os_release_support_ended(support_end
, /* quiet */ false, NULL
) > 0)
1370 /* pretty_name may include the version already, so we'll print the version only if we
1371 * have it and we're not using pretty_name. */
1372 status_printf(ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
, 0,
1373 "This OS version (%s%s%s) is past its end-of-support date (%s)",
1375 (pretty_name
|| !version
) ? "" : " version ",
1376 (pretty_name
|| !version
) ? "" : version
,
1382 static int setup_os_release(RuntimeScope scope
) {
1383 _cleanup_free_
char *os_release_dst
= NULL
;
1384 const char *os_release_src
= "/etc/os-release";
1387 if (access("/etc/os-release", F_OK
) < 0) {
1388 if (errno
!= ENOENT
)
1389 log_debug_errno(errno
, "Failed to check if /etc/os-release exists, ignoring: %m");
1391 os_release_src
= "/usr/lib/os-release";
1394 if (scope
== RUNTIME_SCOPE_SYSTEM
) {
1395 os_release_dst
= strdup("/run/systemd/propagate/.os-release-stage/os-release");
1396 if (!os_release_dst
)
1397 return log_oom_debug();
1399 if (asprintf(&os_release_dst
, "/run/user/" UID_FMT
"/systemd/propagate/.os-release-stage/os-release", geteuid()) < 0)
1400 return log_oom_debug();
1403 r
= mkdir_parents_label(os_release_dst
, 0755);
1405 return log_debug_errno(r
, "Failed to create parent directory of %s, ignoring: %m", os_release_dst
);
1407 r
= copy_file_atomic(os_release_src
, os_release_dst
, 0644, COPY_MAC_CREATE
|COPY_REPLACE
);
1409 return log_debug_errno(r
, "Failed to create %s, ignoring: %m", os_release_dst
);
1414 static int write_container_id(void) {
1416 int r
= 0; /* avoid false maybe-uninitialized warning */
1418 c
= getenv("container");
1423 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1425 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1430 static int bump_unix_max_dgram_qlen(void) {
1431 _cleanup_free_
char *qlen
= NULL
;
1435 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
1436 * the value really really early during boot, so that it is actually applied to all our sockets,
1437 * including the $NOTIFY_SOCKET one. */
1439 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1441 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1442 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1444 r
= safe_atolu(qlen
, &v
);
1446 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen
);
1448 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1451 r
= sysctl_write("net/unix/max_dgram_qlen", STRINGIFY(DEFAULT_UNIX_MAX_DGRAM_QLEN
));
1453 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1454 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1459 static int fixup_environment(void) {
1460 _cleanup_free_
char *term
= NULL
;
1464 /* Only fix up the environment when we are started as PID 1 */
1465 if (getpid_cached() != 1)
1468 /* We expect the environment to be set correctly if run inside a container. */
1469 if (detect_container() > 0)
1472 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
1473 * backend device used by the console. We try to make a better guess here since some consoles might
1474 * not have support for color mode for example.
1476 * However if TERM was configured through the kernel command line then leave it alone. */
1477 r
= proc_cmdline_get_key("TERM", 0, &term
);
1482 r
= proc_cmdline_get_key("systemd.tty.term.console", 0, &term
);
1487 t
= term
?: default_term_for_tty("/dev/console");
1489 if (setenv("TERM", t
, 1) < 0)
1492 /* The kernels sets HOME=/ for init. Let's undo this. */
1493 if (path_equal_ptr(getenv("HOME"), "/"))
1494 assert_se(unsetenv("HOME") == 0);
1499 static void redirect_telinit(int argc
, char *argv
[]) {
1501 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1503 #if HAVE_SYSV_COMPAT
1504 if (getpid_cached() == 1)
1507 if (!invoked_as(argv
, "init"))
1510 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1511 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1516 static int become_shutdown(int objective
, int retval
) {
1517 static const char* const table
[_MANAGER_OBJECTIVE_MAX
] = {
1518 [MANAGER_EXIT
] = "exit",
1519 [MANAGER_REBOOT
] = "reboot",
1520 [MANAGER_POWEROFF
] = "poweroff",
1521 [MANAGER_HALT
] = "halt",
1522 [MANAGER_KEXEC
] = "kexec",
1525 char log_level
[STRLEN("--log-level=") + DECIMAL_STR_MAX(int)],
1526 timeout
[STRLEN("--timeout=") + DECIMAL_STR_MAX(usec_t
) + STRLEN("us")],
1527 exit_code
[STRLEN("--exit-code=") + DECIMAL_STR_MAX(uint8_t)];
1529 _cleanup_strv_free_
char **env_block
= NULL
;
1530 usec_t watchdog_timer
= 0;
1533 assert(objective
>= 0 && objective
< _MANAGER_OBJECTIVE_MAX
);
1534 assert(table
[objective
]);
1536 xsprintf(log_level
, "--log-level=%d", log_get_max_level());
1537 xsprintf(timeout
, "--timeout=%" PRI_USEC
"us", arg_default_timeout_stop_usec
);
1539 const char* command_line
[10] = {
1540 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1544 /* Note that the last position is a terminator and must contain NULL. */
1548 assert(command_line
[pos
-1]);
1549 assert(!command_line
[pos
]);
1551 switch (log_get_target()) {
1553 case LOG_TARGET_KMSG
:
1554 case LOG_TARGET_JOURNAL_OR_KMSG
:
1555 case LOG_TARGET_SYSLOG_OR_KMSG
:
1556 command_line
[pos
++] = "--log-target=kmsg";
1559 case LOG_TARGET_NULL
:
1560 command_line
[pos
++] = "--log-target=null";
1563 case LOG_TARGET_CONSOLE
:
1565 command_line
[pos
++] = "--log-target=console";
1569 if (log_get_show_color())
1570 command_line
[pos
++] = "--log-color";
1572 if (log_get_show_location())
1573 command_line
[pos
++] = "--log-location";
1575 if (log_get_show_time())
1576 command_line
[pos
++] = "--log-time";
1578 xsprintf(exit_code
, "--exit-code=%d", retval
);
1579 command_line
[pos
++] = exit_code
;
1581 assert(pos
< ELEMENTSOF(command_line
));
1585 if (objective
== MANAGER_REBOOT
)
1586 watchdog_timer
= arg_reboot_watchdog
;
1587 else if (objective
== MANAGER_KEXEC
)
1588 watchdog_timer
= arg_kexec_watchdog
;
1590 /* If we reboot or kexec let's set the shutdown watchdog and tell the
1591 * shutdown binary to repeatedly ping it.
1592 * Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
1593 (void) watchdog_setup_pretimeout(0);
1594 (void) watchdog_setup_pretimeout_governor(NULL
);
1595 r
= watchdog_setup(watchdog_timer
);
1596 watchdog_close(r
< 0);
1598 /* The environment block: */
1600 env_block
= strv_copy(environ
);
1602 /* Tell the binary how often to ping, ignore failure */
1603 (void) strv_extendf(&env_block
, "WATCHDOG_USEC="USEC_FMT
, watchdog_timer
);
1605 if (arg_watchdog_device
)
1606 (void) strv_extendf(&env_block
, "WATCHDOG_DEVICE=%s", arg_watchdog_device
);
1608 /* Avoid the creation of new processes forked by the kernel; at this
1609 * point, we will not listen to the signals anyway */
1610 if (detect_container() <= 0)
1611 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1613 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1617 static void initialize_clock(void) {
1620 /* This is called very early on, before we parse the kernel command line or otherwise figure out why
1621 * we are running, but only once. */
1623 if (clock_is_localtime(NULL
) > 0) {
1626 /* The very first call of settimeofday() also does a time warp in the kernel.
1628 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
1629 * take care of maintaining the RTC and do all adjustments. This matches the behavior of
1630 * Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
1632 r
= clock_set_timezone(&min
);
1634 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1636 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1638 } else if (!in_initrd())
1640 * Do a dummy very first call to seal the kernel's time warp magic.
1642 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
1643 * LOCAL, but the real system could be set up that way. In such case, we need to delay the
1644 * time-warp or the sealing until we reach the real system.
1646 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
1647 * the time will jump or be incorrect at every daylight saving time change. All kernel local
1648 * time concepts will be treated as UTC that way.
1650 (void) clock_reset_timewarp();
1652 ClockChangeDirection change_dir
;
1653 r
= clock_apply_epoch(&change_dir
);
1654 if (r
> 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1655 log_info("System time before build time, advancing clock.");
1656 else if (r
> 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1657 log_info("System time is further ahead than %s after build time, resetting clock to build time.",
1658 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1659 else if (r
< 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1660 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1661 else if (r
< 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1662 log_error_errno(r
, "Current system time is further ahead %s after build time, but cannot correct: %m",
1663 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1666 static void apply_clock_update(void) {
1667 /* This is called later than initialize_clock(), i.e. after we parsed configuration files/kernel
1668 * command line and such. */
1670 if (arg_clock_usec
== 0)
1673 if (getpid_cached() != 1)
1676 if (clock_settime(CLOCK_REALTIME
, TIMESPEC_STORE(arg_clock_usec
)) < 0)
1677 log_error_errno(errno
, "Failed to set system clock to time specified on kernel command line: %m");
1679 log_info("Set system clock to %s, as specified on the kernel command line.",
1680 FORMAT_TIMESTAMP(arg_clock_usec
));
1683 static void cmdline_take_random_seed(void) {
1687 if (arg_random_seed_size
== 0)
1690 if (getpid_cached() != 1)
1693 assert(arg_random_seed
);
1694 suggested
= random_pool_size();
1696 if (arg_random_seed_size
< suggested
)
1697 log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
1698 arg_random_seed_size
, suggested
);
1700 r
= random_write_entropy(-1, arg_random_seed
, arg_random_seed_size
, true);
1702 log_warning_errno(r
, "Failed to credit entropy specified on kernel command line, ignoring: %m");
1706 log_notice("Successfully credited entropy passed on kernel command line.\n"
1707 "Note that the seed provided this way is accessible to unprivileged programs. "
1708 "This functionality should not be used outside of testing environments.");
1711 static void initialize_coredump(bool skip_setup
) {
1712 if (getpid_cached() != 1)
1715 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
1716 * the limit) will process core dumps for system services by default. */
1717 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1718 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1720 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1721 * until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
1722 * command line later so core dumps can still be generated during early startup and in initrd. */
1724 disable_coredumps();
1727 static void initialize_core_pattern(bool skip_setup
) {
1730 if (skip_setup
|| !arg_early_core_pattern
)
1733 if (getpid_cached() != 1)
1736 r
= write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1738 log_warning_errno(r
, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1739 arg_early_core_pattern
);
1742 static void update_cpu_affinity(bool skip_setup
) {
1743 _cleanup_free_
char *mask
= NULL
;
1745 if (skip_setup
|| !arg_cpu_affinity
.set
)
1748 assert(arg_cpu_affinity
.allocated
> 0);
1750 mask
= cpu_set_to_range_string(&arg_cpu_affinity
);
1751 log_debug("Setting CPU affinity to {%s}.", strnull(mask
));
1753 if (sched_setaffinity(0, arg_cpu_affinity
.allocated
, arg_cpu_affinity
.set
) < 0)
1754 log_warning_errno(errno
, "Failed to set CPU affinity, ignoring: %m");
1757 static void update_numa_policy(bool skip_setup
) {
1759 _cleanup_free_
char *nodes
= NULL
;
1760 const char * policy
= NULL
;
1762 if (skip_setup
|| !mpol_is_valid(numa_policy_get_type(&arg_numa_policy
)))
1765 if (DEBUG_LOGGING
) {
1766 policy
= mpol_to_string(numa_policy_get_type(&arg_numa_policy
));
1767 nodes
= cpu_set_to_range_string(&arg_numa_policy
.nodes
);
1768 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy
), strnull(nodes
));
1771 r
= apply_numa_policy(&arg_numa_policy
);
1772 if (r
== -EOPNOTSUPP
)
1773 log_debug_errno(r
, "NUMA support not available, ignoring.");
1775 log_warning_errno(r
, "Failed to set NUMA memory policy, ignoring: %m");
1778 static void filter_args(
1787 /* Copy some filtered arguments into the dst array from src. */
1788 for (int i
= 1; i
< argc
; i
++) {
1789 if (STR_IN_SET(src
[i
],
1795 if (startswith(src
[i
], "--deserialize="))
1797 if (streq(src
[i
], "--deserialize")) {
1798 i
++; /* Skip the argument too */
1802 /* Skip target unit designators. We already acted upon this information and have queued
1803 * appropriate jobs. We don't want to redo all this after reexecution. */
1804 if (startswith(src
[i
], "--unit="))
1806 if (streq(src
[i
], "--unit")) {
1807 i
++; /* Skip the argument too */
1811 /* Seems we have a good old option. Let's pass it over to the new instance. */
1812 dst
[(*dst_index
)++] = src
[i
];
1816 static void finish_remaining_processes(ManagerObjective objective
) {
1817 assert(objective
>= 0 && objective
< _MANAGER_OBJECTIVE_MAX
);
1819 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
1820 * SIGCHLD for them after deserializing. */
1821 if (IN_SET(objective
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
))
1822 broadcast_signal(SIGTERM
, /* wait_for_exit= */ false, /* send_sighup= */ true, arg_default_timeout_stop_usec
);
1824 /* On soft reboot really make sure nothing is left */
1825 if (objective
== MANAGER_SOFT_REBOOT
)
1826 broadcast_signal(SIGKILL
, /* wait_for_exit= */ false, /* send_sighup= */ false, arg_default_timeout_stop_usec
);
1829 static int do_reexecute(
1830 ManagerObjective objective
,
1833 const struct rlimit
*saved_rlimit_nofile
,
1834 const struct rlimit
*saved_rlimit_memlock
,
1836 const char *switch_root_dir
,
1837 const char *switch_root_init
,
1838 const char **ret_error_message
) {
1840 size_t i
, args_size
;
1844 assert(IN_SET(objective
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
));
1846 assert(saved_rlimit_nofile
);
1847 assert(saved_rlimit_memlock
);
1848 assert(ret_error_message
);
1850 if (switch_root_init
) {
1851 r
= chase(switch_root_init
, switch_root_dir
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1853 log_warning_errno(r
, "Failed to chase configured init %s/%s: %m",
1854 strempty(switch_root_dir
), switch_root_init
);
1856 r
= chase(SYSTEMD_BINARY_PATH
, switch_root_dir
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1858 log_debug_errno(r
, "Failed to chase our own binary %s/%s: %m",
1859 strempty(switch_root_dir
), SYSTEMD_BINARY_PATH
);
1863 r
= chase("/sbin/init", switch_root_dir
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1865 return log_error_errno(r
, "Failed to chase %s/sbin/init", strempty(switch_root_dir
));
1868 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1869 * rebooted while we do that */
1870 watchdog_close(true);
1872 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1873 * the kernel default to its child processes */
1874 if (saved_rlimit_nofile
->rlim_cur
!= 0)
1875 (void) setrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
);
1876 if (saved_rlimit_memlock
->rlim_cur
!= RLIM_INFINITY
)
1877 (void) setrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
);
1879 finish_remaining_processes(objective
);
1881 if (!switch_root_dir
&& objective
== MANAGER_SOFT_REBOOT
) {
1882 /* If no switch root dir is specified, then check if /run/nextroot/ qualifies and use that */
1883 r
= path_is_os_tree("/run/nextroot");
1884 if (r
< 0 && r
!= -ENOENT
)
1885 log_debug_errno(r
, "Failed to determine if /run/nextroot/ is a valid OS tree, ignoring: %m");
1887 switch_root_dir
= "/run/nextroot";
1890 if (switch_root_dir
) {
1891 r
= switch_root(/* new_root= */ switch_root_dir
,
1892 /* old_root_after= */ NULL
,
1893 /* flags= */ (objective
== MANAGER_SWITCH_ROOT
? SWITCH_ROOT_DESTROY_OLD_ROOT
: 0) |
1894 (objective
== MANAGER_SOFT_REBOOT
? 0 : SWITCH_ROOT_RECURSIVE_RUN
));
1896 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
1899 args_size
= argc
+ 5;
1900 args
= newa(const char*, args_size
);
1902 if (!switch_root_init
) {
1903 char sfd
[STRLEN("--deserialize=") + DECIMAL_STR_MAX(int)];
1905 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1906 * only if the user didn't specify an explicit init to spawn. */
1908 assert(arg_serialization
);
1911 xsprintf(sfd
, "--deserialize=%i", fileno(arg_serialization
));
1913 i
= 1; /* Leave args[0] empty for now. */
1915 /* Put our stuff first to make sure it always gets parsed in case
1916 * we get weird stuff from the kernel cmdline (like --) */
1917 if (IN_SET(objective
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
))
1918 args
[i
++] = "--switched-root";
1919 args
[i
++] = runtime_scope_cmdline_option_to_string(arg_runtime_scope
);
1922 filter_args(args
, &i
, argv
, argc
);
1926 assert(i
<= args_size
);
1929 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
1930 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
1931 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
1932 * and wait() for it in the parent, before proceeding into the exec().
1934 valgrind_summary_hack();
1936 args
[0] = SYSTEMD_BINARY_PATH
;
1937 (void) execv(args
[0], (char* const*) args
);
1939 if (objective
== MANAGER_REEXECUTE
) {
1940 *ret_error_message
= "Failed to execute our own binary";
1941 return log_error_errno(errno
, "Failed to execute our own binary %s: %m", args
[0]);
1944 log_debug_errno(errno
, "Failed to execute our own binary %s, trying fallback: %m", args
[0]);
1947 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
1948 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
1949 * but let's hope that doesn't matter.) */
1951 arg_serialization
= safe_fclose(arg_serialization
);
1952 fds
= fdset_free(fds
);
1954 /* Reopen the console */
1955 (void) make_console_stdio();
1957 i
= 1; /* Leave args[0] empty for now. */
1958 for (int j
= 1; j
<= argc
; j
++)
1959 args
[i
++] = argv
[j
];
1960 assert(i
<= args_size
);
1962 /* Re-enable any blocked signals, especially important if we switch from initrd to init=... */
1963 (void) reset_all_signal_handlers();
1964 (void) reset_signal_mask();
1965 (void) rlimit_nofile_safe();
1967 if (switch_root_init
) {
1968 args
[0] = switch_root_init
;
1969 (void) execve(args
[0], (char* const*) args
, saved_env
);
1970 log_warning_errno(errno
, "Failed to execute configured init %s, trying fallback: %m", args
[0]);
1973 args
[0] = "/sbin/init";
1974 (void) execv(args
[0], (char* const*) args
);
1977 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
1978 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
1979 "Failed to execute /sbin/init");
1981 *ret_error_message
= "Failed to execute fallback shell";
1983 log_warning("No /sbin/init, trying fallback");
1985 args
[0] = "/bin/sh";
1987 (void) execve(args
[0], (char* const*) args
, saved_env
);
1988 return log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
1990 return log_error_errno(r
, "Failed to execute /sbin/init, giving up: %m");
1993 static int invoke_main_loop(
1995 const struct rlimit
*saved_rlimit_nofile
,
1996 const struct rlimit
*saved_rlimit_memlock
,
1997 int *ret_retval
, /* Return parameters relevant for shutting down */
1998 FDSet
**ret_fds
, /* Return parameters for reexecuting */
1999 char **ret_switch_root_dir
, /* … */
2000 char **ret_switch_root_init
, /* … */
2001 const char **ret_error_message
) {
2006 assert(saved_rlimit_nofile
);
2007 assert(saved_rlimit_memlock
);
2010 assert(ret_switch_root_dir
);
2011 assert(ret_switch_root_init
);
2012 assert(ret_error_message
);
2015 int objective
= manager_loop(m
);
2016 if (objective
< 0) {
2017 *ret_error_message
= "Failed to run main loop";
2018 return log_struct_errno(LOG_EMERG
, objective
,
2019 LOG_MESSAGE("Failed to run main loop: %m"),
2020 "MESSAGE_ID=" SD_MESSAGE_CORE_MAINLOOP_FAILED_STR
);
2023 switch (objective
) {
2025 case MANAGER_RELOAD
: {
2026 LogTarget saved_log_target
;
2027 int saved_log_level
;
2029 manager_send_reloading(m
);
2031 log_info("Reloading...");
2033 /* First, save any overridden log level/target, then parse the configuration file,
2034 * which might change the log level to new settings. */
2036 saved_log_level
= m
->log_level_overridden
? log_get_max_level() : -1;
2037 saved_log_target
= m
->log_target_overridden
? log_get_target() : _LOG_TARGET_INVALID
;
2039 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
2041 set_manager_defaults(m
);
2042 set_manager_settings(m
);
2044 update_cpu_affinity(false);
2045 update_numa_policy(false);
2047 if (saved_log_level
>= 0)
2048 manager_override_log_level(m
, saved_log_level
);
2049 if (saved_log_target
>= 0)
2050 manager_override_log_target(m
, saved_log_target
);
2052 if (manager_reload(m
) < 0)
2053 /* Reloading failed before the point of no return.
2054 * Let's continue running as if nothing happened. */
2055 m
->objective
= MANAGER_OK
;
2057 log_info("Reloading finished in " USEC_FMT
" ms.",
2058 usec_sub_unsigned(now(CLOCK_MONOTONIC
), m
->timestamps
[MANAGER_TIMESTAMP_UNITS_LOAD
].monotonic
) / USEC_PER_MSEC
);
2063 case MANAGER_REEXECUTE
:
2065 manager_send_reloading(m
); /* From the perspective of the manager calling us this is
2066 * pretty much the same as a reload */
2068 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, false);
2070 *ret_error_message
= "Failed to prepare for reexecution";
2074 log_notice("Reexecuting.");
2076 *ret_retval
= EXIT_SUCCESS
;
2077 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2081 case MANAGER_SWITCH_ROOT
:
2083 manager_send_reloading(m
); /* From the perspective of the manager calling us this is
2084 * pretty much the same as a reload */
2086 manager_set_switching_root(m
, true);
2088 if (!m
->switch_root_init
) {
2089 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, true);
2091 *ret_error_message
= "Failed to prepare for reexecution";
2097 log_notice("Switching root.");
2099 *ret_retval
= EXIT_SUCCESS
;
2101 /* Steal the switch root parameters */
2102 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
2103 *ret_switch_root_init
= TAKE_PTR(m
->switch_root_init
);
2107 case MANAGER_SOFT_REBOOT
:
2108 manager_send_reloading(m
);
2109 manager_set_switching_root(m
, true);
2111 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, /* switching_root= */ true);
2113 *ret_error_message
= "Failed to prepare for reexecution";
2117 log_notice("Soft-rebooting.");
2119 *ret_retval
= EXIT_SUCCESS
;
2120 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
2121 *ret_switch_root_init
= NULL
;
2126 if (MANAGER_IS_USER(m
)) {
2129 *ret_retval
= m
->return_value
;
2131 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2137 case MANAGER_REBOOT
:
2138 case MANAGER_POWEROFF
:
2140 case MANAGER_KEXEC
: {
2141 log_notice("Shutting down.");
2143 *ret_retval
= m
->return_value
;
2145 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2151 assert_not_reached();
2156 static void log_execution_mode(bool *ret_first_boot
) {
2157 bool first_boot
= false;
2160 assert(ret_first_boot
);
2162 switch (arg_runtime_scope
) {
2164 case RUNTIME_SCOPE_SYSTEM
: {
2168 log_info("systemd " GIT_VERSION
" running in %ssystem mode (%s)",
2169 arg_action
== ACTION_TEST
? "test " : "",
2172 v
= detect_virtualization();
2174 log_info("Detected virtualization %s.", virtualization_to_string(v
));
2176 v
= detect_confidential_virtualization();
2178 log_info("Detected confidential virtualization %s.", confidential_virtualization_to_string(v
));
2180 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2183 log_info("Running in initrd.");
2185 _cleanup_free_
char *id_text
= NULL
;
2187 /* Let's check whether we are in first boot. First, check if an override was
2188 * specified on the kernel commandline. If yes, we honour that. */
2190 r
= proc_cmdline_get_bool("systemd.condition-first-boot", /* flags = */ 0, &first_boot
);
2192 log_debug_errno(r
, "Failed to parse systemd.condition-first-boot= kernel commandline argument, ignoring: %m");
2195 log_full(first_boot
? LOG_INFO
: LOG_DEBUG
,
2196 "Kernel commandline argument says we are %s first boot.",
2197 first_boot
? "in" : "not in");
2199 /* Second, perform autodetection. We use /etc/machine-id as flag file for
2200 * this: If it is missing or contains the value "uninitialized", this is the
2201 * first boot. In other cases, it is not. This allows container managers and
2202 * installers to provision a couple of files in /etc but still permit the
2203 * first-boot initialization to occur. If the container manager wants to
2204 * provision the machine ID it should pass $container_uuid to PID 1. */
2206 r
= read_one_line_file("/etc/machine-id", &id_text
);
2207 if (r
< 0 || streq(id_text
, "uninitialized")) {
2208 if (r
< 0 && r
!= -ENOENT
)
2209 log_warning_errno(r
, "Unexpected error while reading /etc/machine-id, ignoring: %m");
2212 log_info("Detected first boot.");
2214 log_debug("Detected initialized system, this is not the first boot.");
2218 assert_se(uname(&uts
) >= 0);
2220 if (strverscmp_improved(uts
.release
, KERNEL_BASELINE_VERSION
) < 0)
2221 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2222 "Your mileage may vary.", uts
.release
, KERNEL_BASELINE_VERSION
);
2224 log_debug("Kernel version %s, our baseline is %s", uts
.release
, KERNEL_BASELINE_VERSION
);
2229 case RUNTIME_SCOPE_USER
:
2230 if (DEBUG_LOGGING
) {
2231 _cleanup_free_
char *t
= NULL
;
2233 t
= uid_to_name(getuid());
2234 log_debug("systemd " GIT_VERSION
" running in %suser mode for user " UID_FMT
"/%s. (%s)",
2235 arg_action
== ACTION_TEST
? " test" : "",
2236 getuid(), strna(t
), systemd_features
);
2242 assert_not_reached();
2245 *ret_first_boot
= first_boot
;
2248 static int initialize_runtime(
2251 struct rlimit
*saved_rlimit_nofile
,
2252 struct rlimit
*saved_rlimit_memlock
,
2253 const char **ret_error_message
) {
2256 assert(ret_error_message
);
2258 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2260 * - Some only apply to --system instances
2261 * - Some only apply to --user instances
2262 * - Some only apply when we first start up, but not when we reexecute
2265 if (arg_action
!= ACTION_RUN
)
2268 update_cpu_affinity(skip_setup
);
2269 update_numa_policy(skip_setup
);
2271 switch (arg_runtime_scope
) {
2273 case RUNTIME_SCOPE_SYSTEM
:
2274 /* Make sure we leave a core dump without panicking the kernel. */
2275 install_crash_handler();
2278 r
= mount_cgroup_controllers();
2280 *ret_error_message
= "Failed to mount cgroup hierarchies";
2284 /* Pull credentials from various sources into a common credential directory (we do
2285 * this here, before setting up the machine ID, so that we can use credential info
2286 * for setting up the machine ID) */
2287 (void) import_credentials();
2289 (void) os_release_status();
2290 (void) hostname_setup(true);
2291 /* Force transient machine-id on first boot. */
2292 machine_id_setup(/* root= */ NULL
, /* force_transient= */ first_boot
, arg_machine_id
, /* ret_machine_id */ NULL
);
2293 (void) loopback_setup();
2294 bump_unix_max_dgram_qlen();
2295 bump_file_max_and_nr_open();
2297 write_container_id();
2299 /* Copy os-release to the propagate directory, so that we update it for services running
2300 * under RootDirectory=/RootImage= when we do a soft reboot. */
2301 r
= setup_os_release(RUNTIME_SCOPE_SYSTEM
);
2303 log_warning_errno(r
, "Failed to copy os-release for propagation, ignoring: %m");
2306 r
= watchdog_set_device(arg_watchdog_device
);
2308 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device
);
2312 case RUNTIME_SCOPE_USER
: {
2313 _cleanup_free_
char *p
= NULL
;
2315 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2316 * user mode. In system mode mount_setup() already did that. */
2318 r
= xdg_user_runtime_dir(&p
, "/systemd");
2320 *ret_error_message
= "$XDG_RUNTIME_DIR is not set";
2321 return log_struct_errno(LOG_EMERG
, r
,
2322 LOG_MESSAGE("Failed to determine $XDG_RUNTIME_DIR path: %m"),
2323 "MESSAGE_ID=" SD_MESSAGE_CORE_NO_XDGDIR_PATH_STR
);
2326 (void) mkdir_p_label(p
, 0755);
2327 (void) make_inaccessible_nodes(p
, UID_INVALID
, GID_INVALID
);
2328 r
= setup_os_release(RUNTIME_SCOPE_USER
);
2330 log_warning_errno(r
, "Failed to copy os-release for propagation, ignoring: %m");
2335 assert_not_reached();
2338 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
2339 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
2340 log_warning_errno(errno
, "Failed to adjust timer slack, ignoring: %m");
2342 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2344 if (!cap_test_all(arg_capability_bounding_set
)) {
2345 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
2347 *ret_error_message
= "Failed to drop capability bounding set of usermode helpers";
2348 return log_struct_errno(LOG_EMERG
, r
,
2349 LOG_MESSAGE("Failed to drop capability bounding set of usermode helpers: %m"),
2350 "MESSAGE_ID=" SD_MESSAGE_CORE_CAPABILITY_BOUNDING_USER_STR
);
2353 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
2355 *ret_error_message
= "Failed to drop capability bounding set";
2356 return log_struct_errno(LOG_EMERG
, r
,
2357 LOG_MESSAGE("Failed to drop capability bounding set: %m"),
2358 "MESSAGE_ID=" SD_MESSAGE_CORE_CAPABILITY_BOUNDING_STR
);
2362 if (arg_no_new_privs
) {
2363 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2364 *ret_error_message
= "Failed to disable new privileges";
2365 return log_struct_errno(LOG_EMERG
, errno
,
2366 LOG_MESSAGE("Failed to disable new privileges: %m"),
2367 "MESSAGE_ID=" SD_MESSAGE_CORE_DISABLE_PRIVILEGES_STR
);
2372 if (arg_syscall_archs
) {
2373 r
= enforce_syscall_archs(arg_syscall_archs
);
2375 *ret_error_message
= "Failed to set syscall architectures";
2380 r
= make_reaper_process(true);
2382 log_warning_errno(r
, "Failed to make us a subreaper, ignoring: %m");
2384 /* Bump up RLIMIT_NOFILE for systemd itself */
2385 (void) bump_rlimit_nofile(saved_rlimit_nofile
);
2386 (void) bump_rlimit_memlock(saved_rlimit_memlock
);
2391 static int do_queue_default_job(
2393 const char **ret_error_message
) {
2395 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2401 if (arg_default_unit
)
2402 unit
= arg_default_unit
;
2403 else if (in_initrd())
2404 unit
= SPECIAL_INITRD_TARGET
;
2406 unit
= SPECIAL_DEFAULT_TARGET
;
2408 log_debug("Activating default unit: %s", unit
);
2410 r
= manager_load_startable_unit_or_warn(m
, unit
, NULL
, &target
);
2411 if (r
< 0 && in_initrd() && !arg_default_unit
) {
2412 /* Fall back to default.target, which we used to always use by default. Only do this if no
2413 * explicit configuration was given. */
2415 log_info("Falling back to " SPECIAL_DEFAULT_TARGET
".");
2417 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_DEFAULT_TARGET
, NULL
, &target
);
2420 log_info("Falling back to " SPECIAL_RESCUE_TARGET
".");
2422 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_RESCUE_TARGET
, NULL
, &target
);
2424 *ret_error_message
= r
== -ERFKILL
? SPECIAL_RESCUE_TARGET
" masked"
2425 : "Failed to load " SPECIAL_RESCUE_TARGET
;
2430 assert(target
->load_state
== UNIT_LOADED
);
2432 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, NULL
, &error
, &job
);
2434 log_debug_errno(r
, "Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
2436 sd_bus_error_free(&error
);
2438 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, NULL
, &error
, &job
);
2440 *ret_error_message
= "Failed to start default target";
2441 return log_struct_errno(LOG_EMERG
, r
,
2442 LOG_MESSAGE("Failed to start default target: %s", bus_error_message(&error
, r
)),
2443 "MESSAGE_ID=" SD_MESSAGE_CORE_START_TARGET_FAILED_STR
);
2447 *ret_error_message
= "Failed to isolate default target";
2448 return log_struct_errno(LOG_EMERG
, r
,
2449 LOG_MESSAGE("Failed to isolate default target: %s", bus_error_message(&error
, r
)),
2450 "MESSAGE_ID=" SD_MESSAGE_CORE_ISOLATE_TARGET_FAILED_STR
);
2452 log_info("Queued %s job for default target %s.",
2453 job_type_to_string(job
->type
),
2454 unit_status_string(job
->unit
, NULL
));
2456 m
->default_unit_job_id
= job
->id
;
2461 static void save_rlimits(struct rlimit
*saved_rlimit_nofile
,
2462 struct rlimit
*saved_rlimit_memlock
) {
2464 assert(saved_rlimit_nofile
);
2465 assert(saved_rlimit_memlock
);
2467 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
) < 0)
2468 log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2470 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
) < 0)
2471 log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2474 static void fallback_rlimit_nofile(const struct rlimit
*saved_rlimit_nofile
) {
2477 if (arg_default_rlimit
[RLIMIT_NOFILE
])
2480 /* Make sure forked processes get limits based on the original kernel setting */
2482 rl
= newdup(struct rlimit
, saved_rlimit_nofile
, 1);
2488 /* Bump the hard limit for system services to a substantially higher value. The default
2489 * hard limit current kernels set is pretty low (4K), mostly for historical
2490 * reasons. According to kernel developers, the fd handling in recent kernels has been
2491 * optimized substantially enough, so that we can bump the limit now, without paying too
2492 * high a price in memory or performance. Note however that we only bump the hard limit,
2493 * not the soft limit. That's because select() works the way it works, and chokes on fds
2494 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2495 * unexpecting programs that they get fds higher than what they can process using
2496 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2497 * this pitfall: programs that are written by folks aware of the select() problem in mind
2498 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2499 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2501 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2504 /* Get the underlying absolute limit the kernel enforces */
2505 nr
= read_nr_open();
2507 rl
->rlim_max
= MIN((rlim_t
) nr
, MAX(rl
->rlim_max
, (rlim_t
) HIGH_RLIMIT_NOFILE
));
2510 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2511 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2512 * instance), then lower what we pass on to not confuse our children */
2513 rl
->rlim_cur
= MIN(rl
->rlim_cur
, (rlim_t
) FD_SETSIZE
);
2515 arg_default_rlimit
[RLIMIT_NOFILE
] = rl
;
2518 static void fallback_rlimit_memlock(const struct rlimit
*saved_rlimit_memlock
) {
2521 /* Pass the original value down to invoked processes */
2523 if (arg_default_rlimit
[RLIMIT_MEMLOCK
])
2526 rl
= newdup(struct rlimit
, saved_rlimit_memlock
, 1);
2532 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2533 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2534 * default for this since kernel 5.16) */
2535 rl
->rlim_max
= MAX(rl
->rlim_max
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2536 rl
->rlim_cur
= MAX(rl
->rlim_cur
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2539 arg_default_rlimit
[RLIMIT_MEMLOCK
] = rl
;
2542 static void setenv_manager_environment(void) {
2545 STRV_FOREACH(p
, arg_manager_environment
) {
2546 log_debug("Setting '%s' in our own environment.", *p
);
2548 r
= putenv_dup(*p
, true);
2550 log_warning_errno(errno
, "Failed to setenv \"%s\", ignoring: %m", *p
);
2554 static void reset_arguments(void) {
2555 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2557 arg_default_unit
= mfree(arg_default_unit
);
2559 /* arg_runtime_scope — ignore */
2561 arg_dump_core
= true;
2562 arg_crash_chvt
= -1;
2563 arg_crash_shell
= false;
2564 arg_crash_reboot
= false;
2565 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2566 arg_show_status
= _SHOW_STATUS_INVALID
;
2567 arg_status_unit_format
= STATUS_UNIT_FORMAT_DEFAULT
;
2568 arg_switched_root
= false;
2569 arg_pager_flags
= 0;
2570 arg_service_watchdogs
= true;
2571 arg_default_std_output
= EXEC_OUTPUT_JOURNAL
;
2572 arg_default_std_error
= EXEC_OUTPUT_INHERIT
;
2573 arg_default_restart_usec
= DEFAULT_RESTART_USEC
;
2574 arg_default_timeout_start_usec
= manager_default_timeout(arg_runtime_scope
);
2575 arg_default_timeout_stop_usec
= manager_default_timeout(arg_runtime_scope
);
2576 arg_default_timeout_abort_usec
= manager_default_timeout(arg_runtime_scope
);
2577 arg_default_timeout_abort_set
= false;
2578 arg_default_device_timeout_usec
= manager_default_timeout(arg_runtime_scope
);
2579 arg_default_start_limit_interval
= DEFAULT_START_LIMIT_INTERVAL
;
2580 arg_default_start_limit_burst
= DEFAULT_START_LIMIT_BURST
;
2581 arg_runtime_watchdog
= 0;
2582 arg_reboot_watchdog
= 10 * USEC_PER_MINUTE
;
2583 arg_kexec_watchdog
= 0;
2584 arg_pretimeout_watchdog
= 0;
2585 arg_early_core_pattern
= mfree(arg_early_core_pattern
);
2586 arg_watchdog_device
= mfree(arg_watchdog_device
);
2587 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
2589 arg_default_environment
= strv_free(arg_default_environment
);
2590 arg_manager_environment
= strv_free(arg_manager_environment
);
2591 rlimit_free_all(arg_default_rlimit
);
2593 arg_capability_bounding_set
= CAP_MASK_UNSET
;
2594 arg_no_new_privs
= false;
2595 arg_timer_slack_nsec
= NSEC_INFINITY
;
2596 arg_default_timer_accuracy_usec
= 1 * USEC_PER_MINUTE
;
2598 arg_syscall_archs
= set_free(arg_syscall_archs
);
2600 /* arg_serialization — ignore */
2602 arg_default_cpu_accounting
= -1;
2603 arg_default_io_accounting
= false;
2604 arg_default_ip_accounting
= false;
2605 arg_default_blockio_accounting
= false;
2606 arg_default_memory_accounting
= MEMORY_ACCOUNTING_DEFAULT
;
2607 arg_default_tasks_accounting
= true;
2608 arg_default_tasks_max
= DEFAULT_TASKS_MAX
;
2609 arg_default_memory_pressure_threshold_usec
= MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC
;
2610 arg_default_memory_pressure_watch
= CGROUP_PRESSURE_WATCH_AUTO
;
2611 arg_machine_id
= (sd_id128_t
) {};
2612 arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
2613 arg_default_oom_policy
= OOM_STOP
;
2615 cpu_set_reset(&arg_cpu_affinity
);
2616 numa_policy_reset(&arg_numa_policy
);
2618 arg_random_seed
= mfree(arg_random_seed
);
2619 arg_random_seed_size
= 0;
2622 arg_default_oom_score_adjust_set
= false;
2623 arg_default_smack_process_label
= mfree(arg_default_smack_process_label
);
2625 arg_reload_limit_interval_sec
= 0;
2626 arg_reload_limit_burst
= 0;
2629 static void determine_default_oom_score_adjust(void) {
2632 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2633 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2636 if (arg_default_oom_score_adjust_set
)
2642 r
= get_oom_score_adjust(&a
);
2644 return (void) log_warning_errno(r
, "Failed to determine current OOM score adjustment value, ignoring: %m");
2646 assert_cc(100 <= OOM_SCORE_ADJ_MAX
);
2647 b
= a
>= OOM_SCORE_ADJ_MAX
- 100 ? OOM_SCORE_ADJ_MAX
: a
+ 100;
2652 arg_default_oom_score_adjust
= b
;
2653 arg_default_oom_score_adjust_set
= true;
2656 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
2657 const struct rlimit
*saved_rlimit_memlock
) {
2660 assert(saved_rlimit_nofile
);
2661 assert(saved_rlimit_memlock
);
2663 /* Assign configuration defaults */
2666 r
= parse_config_file();
2668 log_warning_errno(r
, "Failed to parse config file, ignoring: %m");
2670 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2671 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
2673 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2676 /* Initialize some default rlimits for services if they haven't been configured */
2677 fallback_rlimit_nofile(saved_rlimit_nofile
);
2678 fallback_rlimit_memlock(saved_rlimit_memlock
);
2680 /* Note that this also parses bits from the kernel command line, including "debug". */
2681 log_parse_environment();
2683 /* Initialize the show status setting if it hasn't been set explicitly yet */
2684 if (arg_show_status
== _SHOW_STATUS_INVALID
)
2685 arg_show_status
= SHOW_STATUS_YES
;
2687 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2688 determine_default_oom_score_adjust();
2690 /* Push variables into the manager environment block */
2691 setenv_manager_environment();
2693 /* Parse log environment variables again to take into account any new environment variables. */
2694 log_parse_environment();
2699 static int safety_checks(void) {
2701 if (getpid_cached() == 1 &&
2702 arg_action
!= ACTION_RUN
)
2703 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2704 "Unsupported execution mode while PID 1.");
2706 if (getpid_cached() == 1 &&
2707 arg_runtime_scope
== RUNTIME_SCOPE_USER
)
2708 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2709 "Can't run --user mode as PID 1.");
2711 if (arg_action
== ACTION_RUN
&&
2712 arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
&&
2713 getpid_cached() != 1)
2714 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2715 "Can't run system mode unless PID 1.");
2717 if (arg_action
== ACTION_TEST
&&
2719 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2720 "Don't run test mode as root.");
2722 switch (arg_runtime_scope
) {
2724 case RUNTIME_SCOPE_USER
:
2726 if (arg_action
== ACTION_RUN
&&
2728 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2729 "Trying to run as user instance, but the system has not been booted with systemd.");
2731 if (arg_action
== ACTION_RUN
&&
2732 !getenv("XDG_RUNTIME_DIR"))
2733 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH
),
2734 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2738 case RUNTIME_SCOPE_SYSTEM
:
2739 if (arg_action
== ACTION_RUN
&&
2740 running_in_chroot() > 0)
2741 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2742 "Cannot be run in a chroot() environment.");
2746 assert_not_reached();
2752 static int initialize_security(
2753 bool *loaded_policy
,
2754 dual_timestamp
*security_start_timestamp
,
2755 dual_timestamp
*security_finish_timestamp
,
2756 const char **ret_error_message
) {
2760 assert(loaded_policy
);
2761 assert(security_start_timestamp
);
2762 assert(security_finish_timestamp
);
2763 assert(ret_error_message
);
2765 dual_timestamp_get(security_start_timestamp
);
2767 r
= mac_selinux_setup(loaded_policy
);
2769 *ret_error_message
= "Failed to load SELinux policy";
2773 r
= mac_smack_setup(loaded_policy
);
2775 *ret_error_message
= "Failed to load SMACK policy";
2779 r
= mac_apparmor_setup();
2781 *ret_error_message
= "Failed to load AppArmor policy";
2787 *ret_error_message
= "Failed to load IMA policy";
2791 dual_timestamp_get(security_finish_timestamp
);
2795 static int collect_fds(FDSet
**ret_fds
, const char **ret_error_message
) {
2799 assert(ret_error_message
);
2801 /* Pick up all fds passed to us. We apply a filter here: we only take the fds that have O_CLOEXEC
2802 * off. All fds passed via execve() to us must have O_CLOEXEC off, and our own code and dependencies
2803 * should be clean enough to set O_CLOEXEC universally. Thus checking the bit should be a safe
2804 * mechanism to distinguish passed in fds from our own.
2806 * Why bother? Some subsystems we initialize early, specifically selinux might keep fds open in our
2807 * process behind our back. We should not take possession of that (and then accidentally close
2808 * it). SELinux thankfully sets O_CLOEXEC on its fds, so this test should work. */
2809 r
= fdset_new_fill(/* filter_cloexec= */ 0, ret_fds
);
2811 *ret_error_message
= "Failed to allocate fd set";
2812 return log_struct_errno(LOG_EMERG
, r
,
2813 LOG_MESSAGE("Failed to allocate fd set: %m"),
2814 "MESSAGE_ID=" SD_MESSAGE_CORE_FD_SET_FAILED_STR
);
2817 (void) fdset_cloexec(*ret_fds
, true);
2819 /* The serialization fd should have O_CLOEXEC turned on already, let's verify that we didn't pick it up here */
2820 assert_se(!arg_serialization
|| !fdset_contains(*ret_fds
, fileno(arg_serialization
)));
2825 static void setup_console_terminal(bool skip_setup
) {
2827 if (arg_runtime_scope
!= RUNTIME_SCOPE_SYSTEM
)
2830 /* Become a session leader if we aren't one yet. */
2833 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2834 * controlling tty. */
2835 (void) release_terminal();
2837 /* Reset the console, but only if this is really init and we are freshly booted */
2838 if (getpid_cached() == 1 && !skip_setup
)
2839 (void) console_setup();
2842 static bool early_skip_setup_check(int argc
, char *argv
[]) {
2843 bool found_deserialize
= false;
2845 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2846 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2847 * special setup things anyway, even if in that case we also do deserialization. */
2849 for (int i
= 1; i
< argc
; i
++)
2850 if (streq(argv
[i
], "--switched-root"))
2851 return false; /* If we switched root, don't skip the setup. */
2852 else if (startswith(argv
[i
], "--deserialize=") || streq(argv
[i
], "--deserialize"))
2853 found_deserialize
= true;
2855 return found_deserialize
; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2858 static int save_env(void) {
2861 l
= strv_copy(environ
);
2865 strv_free_and_replace(saved_env
, l
);
2869 int main(int argc
, char *argv
[]) {
2871 initrd_timestamp
= DUAL_TIMESTAMP_NULL
,
2872 userspace_timestamp
= DUAL_TIMESTAMP_NULL
,
2873 kernel_timestamp
= DUAL_TIMESTAMP_NULL
,
2874 security_start_timestamp
= DUAL_TIMESTAMP_NULL
,
2875 security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
2876 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0),
2877 saved_rlimit_memlock
= RLIMIT_MAKE_CONST(RLIM_INFINITY
); /* The original rlimits we passed
2878 * in. Note we use different values
2879 * for the two that indicate whether
2880 * these fields are initialized! */
2881 bool skip_setup
, loaded_policy
= false, queue_default_job
= false, first_boot
= false;
2882 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
2883 usec_t before_startup
, after_startup
;
2884 static char systemd
[] = "systemd";
2885 const char *error_message
= NULL
;
2886 int r
, retval
= EXIT_FAILURE
;
2890 assert_se(argc
> 0 && !isempty(argv
[0]));
2892 /* SysV compatibility: redirect init → telinit */
2893 redirect_telinit(argc
, argv
);
2895 /* Take timestamps early on */
2896 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
2897 dual_timestamp_get(&userspace_timestamp
);
2899 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2901 skip_setup
= early_skip_setup_check(argc
, argv
);
2903 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2904 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2906 program_invocation_short_name
= systemd
;
2907 (void) prctl(PR_SET_NAME
, systemd
);
2909 /* Save the original command line */
2910 save_argc_argv(argc
, argv
);
2912 /* Save the original environment as we might need to restore it if we're requested to execute another
2913 * system manager later. */
2916 error_message
= "Failed to copy environment block";
2920 /* Make sure that if the user says "syslog" we actually log to the journal. */
2921 log_set_upgrade_syslog_to_journal(true);
2923 if (getpid_cached() == 1) {
2924 /* When we run as PID 1 force system mode */
2925 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
2927 /* Disable the umask logic */
2930 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2931 * not be activated yet (even though the log socket for it exists). */
2932 log_set_prohibit_ipc(true);
2934 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
2935 * is important so that we never end up logging to any foreign stderr, for example if we have
2936 * to log in a child process right before execve()'ing the actual binary, at a point in time
2937 * where socket activation stderr/stdout area already set up. */
2938 log_set_always_reopen_console(true);
2940 if (detect_container() <= 0) {
2942 /* Running outside of a container as PID 1 */
2943 log_set_target_and_open(LOG_TARGET_KMSG
);
2946 initrd_timestamp
= userspace_timestamp
;
2949 r
= mount_setup_early();
2951 error_message
= "Failed to mount early API filesystems";
2956 /* We might have just mounted /proc, so let's try to parse the kernel
2957 * command line log arguments immediately. */
2958 log_parse_environment();
2960 /* Let's open the log backend a second time, in case the first time didn't
2961 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2962 * available, and it previously wasn't. */
2966 disable_printk_ratelimit();
2968 r
= initialize_security(
2970 &security_start_timestamp
,
2971 &security_finish_timestamp
,
2977 if (mac_init() < 0) {
2978 error_message
= "Failed to initialize MAC support";
2985 /* Set the default for later on, but don't actually open the logs like this for
2986 * now. Note that if we are transitioning from the initrd there might still be
2987 * journal fd open, and we shouldn't attempt opening that before we parsed
2988 * /proc/cmdline which might redirect output elsewhere. */
2989 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
2992 /* Running inside a container, as PID 1 */
2993 log_set_target_and_open(LOG_TARGET_CONSOLE
);
2995 /* For later on, see above... */
2996 log_set_target(LOG_TARGET_JOURNAL
);
2998 /* clear the kernel timestamp, because we are in a container */
2999 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
3002 initialize_coredump(skip_setup
);
3004 r
= fixup_environment();
3006 log_struct_errno(LOG_EMERG
, r
,
3007 LOG_MESSAGE("Failed to fix up PID 1 environment: %m"),
3008 "MESSAGE_ID=" SD_MESSAGE_CORE_PID1_ENVIRONMENT_STR
);
3009 error_message
= "Failed to fix up PID1 environment";
3013 /* Try to figure out if we can use colors with the console. No need to do that for user
3014 * instances since they never log into the console. */
3015 log_show_color(colors_enabled());
3017 r
= make_null_stdio();
3019 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null, ignoring: %m");
3021 /* Load the kernel modules early. */
3023 (void) kmod_setup();
3025 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
3026 r
= mount_setup(loaded_policy
, skip_setup
);
3028 error_message
= "Failed to mount API filesystems";
3032 /* The efivarfs is now mounted, let's lock down the system token. */
3033 lock_down_efi_variables();
3035 /* Cache command-line options passed from EFI variables */
3037 (void) cache_efi_options_variable();
3039 /* Running as user instance */
3040 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
3041 log_set_always_reopen_console(true);
3042 log_set_target_and_open(LOG_TARGET_AUTO
);
3044 /* clear the kernel timestamp, because we are not PID 1 */
3045 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
3047 /* Clear ambient capabilities, so services do not inherit them implicitly. Dropping them does
3048 * not affect the permitted and effective sets which are important for the manager itself to
3050 capability_ambient_set_apply(0, /* also_inherit= */ false);
3052 if (mac_init() < 0) {
3053 error_message
= "Failed to initialize MAC support";
3058 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
3059 * transitioning from the initrd to the main systemd or suchlike. */
3060 save_rlimits(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
3062 /* Reset all signal handlers. */
3063 (void) reset_all_signal_handlers();
3064 (void) ignore_signals(SIGNALS_IGNORE
);
3066 (void) parse_configuration(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
3068 r
= parse_argv(argc
, argv
);
3070 error_message
= "Failed to parse commandline arguments";
3074 r
= safety_checks();
3078 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
, ACTION_DUMP_CONFIGURATION_ITEMS
, ACTION_DUMP_BUS_PROPERTIES
, ACTION_BUS_INTROSPECT
))
3079 pager_open(arg_pager_flags
);
3081 if (arg_action
!= ACTION_RUN
)
3084 if (arg_action
== ACTION_HELP
) {
3085 retval
= help() < 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
3087 } else if (arg_action
== ACTION_VERSION
) {
3090 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
3091 unit_dump_config_items(stdout
);
3092 retval
= EXIT_SUCCESS
;
3094 } else if (arg_action
== ACTION_DUMP_BUS_PROPERTIES
) {
3095 dump_bus_properties(stdout
);
3096 retval
= EXIT_SUCCESS
;
3098 } else if (arg_action
== ACTION_BUS_INTROSPECT
) {
3099 r
= bus_manager_introspect_implementations(stdout
, arg_bus_introspect
);
3100 retval
= r
>= 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
3104 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
3106 /* Move out of the way, so that we won't block unmounts */
3107 assert_se(chdir("/") == 0);
3109 if (arg_action
== ACTION_RUN
) {
3111 /* Apply the systemd.clock_usec= kernel command line switch */
3112 apply_clock_update();
3114 /* Apply random seed from kernel command line */
3115 cmdline_take_random_seed();
3118 /* A core pattern might have been specified via the cmdline. */
3119 initialize_core_pattern(skip_setup
);
3121 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
3124 /* Remember open file descriptors for later deserialization */
3125 r
= collect_fds(&fds
, &error_message
);
3129 /* Give up any control of the console, but make sure its initialized. */
3130 setup_console_terminal(skip_setup
);
3132 /* Open the logging devices, if possible and necessary */
3136 log_execution_mode(&first_boot
);
3138 r
= initialize_runtime(skip_setup
,
3140 &saved_rlimit_nofile
,
3141 &saved_rlimit_memlock
,
3146 r
= manager_new(arg_runtime_scope
,
3147 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
3150 log_struct_errno(LOG_EMERG
, r
,
3151 LOG_MESSAGE("Failed to allocate manager object: %m"),
3152 "MESSAGE_ID=" SD_MESSAGE_CORE_MANAGER_ALLOCATE_STR
);
3153 error_message
= "Failed to allocate manager object";
3157 m
->timestamps
[MANAGER_TIMESTAMP_KERNEL
] = kernel_timestamp
;
3158 m
->timestamps
[MANAGER_TIMESTAMP_INITRD
] = initrd_timestamp
;
3159 m
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
] = userspace_timestamp
;
3160 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START
)] = security_start_timestamp
;
3161 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH
)] = security_finish_timestamp
;
3163 set_manager_defaults(m
);
3164 set_manager_settings(m
);
3165 manager_set_first_boot(m
, first_boot
);
3166 manager_set_switching_root(m
, arg_switched_root
);
3168 /* Remember whether we should queue the default job */
3169 queue_default_job
= !arg_serialization
|| arg_switched_root
;
3171 before_startup
= now(CLOCK_MONOTONIC
);
3173 r
= manager_startup(m
, arg_serialization
, fds
, /* root= */ NULL
);
3175 error_message
= "Failed to start up manager";
3179 /* This will close all file descriptors that were opened, but not claimed by any unit. */
3180 fds
= fdset_free(fds
);
3181 arg_serialization
= safe_fclose(arg_serialization
);
3183 if (queue_default_job
) {
3184 r
= do_queue_default_job(m
, &error_message
);
3189 after_startup
= now(CLOCK_MONOTONIC
);
3191 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
3192 "Loaded units and determined initial transaction in %s.",
3193 FORMAT_TIMESPAN(after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
3195 if (arg_action
== ACTION_TEST
) {
3196 manager_test_summary(m
);
3197 retval
= EXIT_SUCCESS
;
3201 r
= invoke_main_loop(m
,
3202 &saved_rlimit_nofile
,
3203 &saved_rlimit_memlock
,
3209 assert(r
< 0 || IN_SET(r
, MANAGER_EXIT
, /* MANAGER_OK is not expected here. */
3213 MANAGER_SOFT_REBOOT
,
3217 MANAGER_SWITCH_ROOT
));
3223 arg_reboot_watchdog
= manager_get_watchdog(m
, WATCHDOG_REBOOT
);
3224 arg_kexec_watchdog
= manager_get_watchdog(m
, WATCHDOG_KEXEC
);
3225 m
= manager_free(m
);
3228 mac_selinux_finish();
3230 if (IN_SET(r
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
))
3233 &saved_rlimit_nofile
,
3234 &saved_rlimit_memlock
,
3238 &error_message
); /* This only returns if reexecution failed */
3240 arg_serialization
= safe_fclose(arg_serialization
);
3241 fds
= fdset_free(fds
);
3243 saved_env
= strv_free(saved_env
);
3245 #if HAVE_VALGRIND_VALGRIND_H
3246 /* If we are PID 1 and running under valgrind, then let's exit
3247 * here explicitly. valgrind will only generate nice output on
3248 * exit(), not on exec(), hence let's do the former not the
3250 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
3251 /* Cleanup watchdog_device strings for valgrind. We need them
3252 * in become_shutdown() so normally we cannot free them yet. */
3253 watchdog_free_device();
3259 #if HAS_FEATURE_ADDRESS_SANITIZER
3260 __lsan_do_leak_check();
3264 (void) sd_notifyf(0, "ERRNO=%i", -r
);
3266 /* Try to invoke the shutdown binary unless we already failed.
3267 * If we failed above, we want to freeze after finishing cleanup. */
3268 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
&&
3269 IN_SET(r
, MANAGER_EXIT
, MANAGER_REBOOT
, MANAGER_POWEROFF
, MANAGER_HALT
, MANAGER_KEXEC
)) {
3270 r
= become_shutdown(r
, retval
);
3271 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3272 error_message
= "Failed to execute shutdown binary";
3275 /* This is primarily useful when running systemd in a VM, as it provides the user running the VM with
3276 * a mechanism to pick up systemd's exit status in the VM. */
3277 (void) sd_notifyf(0, "EXIT_STATUS=%i", retval
);
3279 watchdog_free_device();
3280 arg_watchdog_device
= mfree(arg_watchdog_device
);
3282 if (getpid_cached() == 1) {
3284 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
3285 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
3286 "%s.", error_message
);
3287 freeze_or_exit_or_reboot();