]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/main.c
Merge pull request #23021 from fbuihuu/tmpfiles-fix-precedence-with-plus-sign
[thirdparty/systemd.git] / src / core / main.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <getopt.h>
6 #include <linux/oom.h>
7 #include <sys/mount.h>
8 #include <sys/prctl.h>
9 #include <sys/utsname.h>
10 #include <unistd.h>
11 #if HAVE_SECCOMP
12 #include <seccomp.h>
13 #endif
14 #if HAVE_VALGRIND_VALGRIND_H
15 #include <valgrind/valgrind.h>
16 #endif
17
18 #include "sd-bus.h"
19 #include "sd-daemon.h"
20 #include "sd-messages.h"
21
22 #include "alloc-util.h"
23 #include "apparmor-setup.h"
24 #include "architecture.h"
25 #if HAVE_LIBBPF
26 #include "bpf-lsm.h"
27 #endif
28 #include "build.h"
29 #include "bus-error.h"
30 #include "bus-util.h"
31 #include "capability-util.h"
32 #include "cgroup-util.h"
33 #include "clock-util.h"
34 #include "conf-parser.h"
35 #include "cpu-set-util.h"
36 #include "crash-handler.h"
37 #include "dbus-manager.h"
38 #include "dbus.h"
39 #include "def.h"
40 #include "dev-setup.h"
41 #include "efi-random.h"
42 #include "efivars.h"
43 #include "emergency-action.h"
44 #include "env-util.h"
45 #include "exit-status.h"
46 #include "fd-util.h"
47 #include "fdset.h"
48 #include "fileio.h"
49 #include "format-util.h"
50 #include "fs-util.h"
51 #include "hexdecoct.h"
52 #include "hostname-setup.h"
53 #include "ima-setup.h"
54 #include "killall.h"
55 #include "kmod-setup.h"
56 #include "limits-util.h"
57 #include "load-fragment.h"
58 #include "log.h"
59 #include "loopback-setup.h"
60 #include "machine-id-setup.h"
61 #include "main.h"
62 #include "manager.h"
63 #include "manager-dump.h"
64 #include "manager-serialize.h"
65 #include "mkdir-label.h"
66 #include "mount-setup.h"
67 #include "os-util.h"
68 #include "pager.h"
69 #include "parse-argument.h"
70 #include "parse-util.h"
71 #include "path-util.h"
72 #include "pretty-print.h"
73 #include "proc-cmdline.h"
74 #include "process-util.h"
75 #include "random-util.h"
76 #include "rlimit-util.h"
77 #if HAVE_SECCOMP
78 #include "seccomp-util.h"
79 #endif
80 #include "selinux-setup.h"
81 #include "selinux-util.h"
82 #include "signal-util.h"
83 #include "smack-setup.h"
84 #include "special.h"
85 #include "stat-util.h"
86 #include "stdio-util.h"
87 #include "strv.h"
88 #include "switch-root.h"
89 #include "sysctl-util.h"
90 #include "terminal-util.h"
91 #include "time-util.h"
92 #include "umask-util.h"
93 #include "user-util.h"
94 #include "util.h"
95 #include "virt.h"
96 #include "watchdog.h"
97
98 #if HAS_FEATURE_ADDRESS_SANITIZER
99 #include <sanitizer/lsan_interface.h>
100 #endif
101
102 #define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
103
104 static enum {
105 ACTION_RUN,
106 ACTION_HELP,
107 ACTION_VERSION,
108 ACTION_TEST,
109 ACTION_DUMP_CONFIGURATION_ITEMS,
110 ACTION_DUMP_BUS_PROPERTIES,
111 ACTION_BUS_INTROSPECT,
112 } arg_action = ACTION_RUN;
113
114 static const char *arg_bus_introspect = NULL;
115
116 /* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
117 * defaults are assigned in reset_arguments() below. */
118 static char *arg_default_unit;
119 static bool arg_system;
120 bool arg_dump_core;
121 int arg_crash_chvt;
122 bool arg_crash_shell;
123 bool arg_crash_reboot;
124 static char *arg_confirm_spawn;
125 static ShowStatus arg_show_status;
126 static StatusUnitFormat arg_status_unit_format;
127 static bool arg_switched_root;
128 static PagerFlags arg_pager_flags;
129 static bool arg_service_watchdogs;
130 static ExecOutput arg_default_std_output;
131 static ExecOutput arg_default_std_error;
132 static usec_t arg_default_restart_usec;
133 static usec_t arg_default_timeout_start_usec;
134 static usec_t arg_default_timeout_stop_usec;
135 static usec_t arg_default_timeout_abort_usec;
136 static bool arg_default_timeout_abort_set;
137 static usec_t arg_default_start_limit_interval;
138 static unsigned arg_default_start_limit_burst;
139 static usec_t arg_runtime_watchdog;
140 static usec_t arg_reboot_watchdog;
141 static usec_t arg_kexec_watchdog;
142 static usec_t arg_pretimeout_watchdog;
143 static char *arg_early_core_pattern;
144 static char *arg_watchdog_pretimeout_governor;
145 static char *arg_watchdog_device;
146 static char **arg_default_environment;
147 static char **arg_manager_environment;
148 static struct rlimit *arg_default_rlimit[_RLIMIT_MAX];
149 static uint64_t arg_capability_bounding_set;
150 static bool arg_no_new_privs;
151 static nsec_t arg_timer_slack_nsec;
152 static usec_t arg_default_timer_accuracy_usec;
153 static Set* arg_syscall_archs;
154 static FILE* arg_serialization;
155 static int arg_default_cpu_accounting;
156 static bool arg_default_io_accounting;
157 static bool arg_default_ip_accounting;
158 static bool arg_default_blockio_accounting;
159 static bool arg_default_memory_accounting;
160 static bool arg_default_tasks_accounting;
161 static TasksMax arg_default_tasks_max;
162 static sd_id128_t arg_machine_id;
163 static EmergencyAction arg_cad_burst_action;
164 static OOMPolicy arg_default_oom_policy;
165 static CPUSet arg_cpu_affinity;
166 static NUMAPolicy arg_numa_policy;
167 static usec_t arg_clock_usec;
168 static void *arg_random_seed;
169 static size_t arg_random_seed_size;
170 static int arg_default_oom_score_adjust;
171 static bool arg_default_oom_score_adjust_set;
172
173 /* A copy of the original environment block */
174 static char **saved_env = NULL;
175
176 static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
177 const struct rlimit *saved_rlimit_memlock);
178
179 static int manager_find_user_config_paths(char ***ret_files, char ***ret_dirs) {
180 _cleanup_free_ char *base = NULL;
181 _cleanup_strv_free_ char **files = NULL, **dirs = NULL;
182 int r;
183
184 r = xdg_user_config_dir(&base, "/systemd");
185 if (r < 0)
186 return r;
187
188 r = strv_extendf(&files, "%s/user.conf", base);
189 if (r < 0)
190 return r;
191
192 r = strv_extend(&files, PKGSYSCONFDIR "/user.conf");
193 if (r < 0)
194 return r;
195
196 r = strv_consume(&dirs, TAKE_PTR(base));
197 if (r < 0)
198 return r;
199
200 r = strv_extend_strv(&dirs, CONF_PATHS_STRV("systemd"), false);
201 if (r < 0)
202 return r;
203
204 *ret_files = TAKE_PTR(files);
205 *ret_dirs = TAKE_PTR(dirs);
206 return 0;
207 }
208
209 static int console_setup(void) {
210 _cleanup_close_ int tty_fd = -1;
211 int r;
212
213 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
214 if (tty_fd < 0)
215 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
216
217 /* We don't want to force text mode. plymouth may be showing
218 * pictures already from initrd. */
219 r = reset_terminal_fd(tty_fd, false);
220 if (r < 0)
221 return log_error_errno(r, "Failed to reset /dev/console: %m");
222
223 return 0;
224 }
225
226 static int set_machine_id(const char *m) {
227 sd_id128_t t;
228 assert(m);
229
230 if (sd_id128_from_string(m, &t) < 0)
231 return -EINVAL;
232
233 if (sd_id128_is_null(t))
234 return -EINVAL;
235
236 arg_machine_id = t;
237 return 0;
238 }
239
240 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
241 int r;
242
243 assert(key);
244
245 if (STR_IN_SET(key, "systemd.unit", "rd.systemd.unit")) {
246
247 if (proc_cmdline_value_missing(key, value))
248 return 0;
249
250 if (!unit_name_is_valid(value, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
251 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key, value);
252 else if (in_initrd() == !!startswith(key, "rd."))
253 return free_and_strdup_warn(&arg_default_unit, value);
254
255 } else if (proc_cmdline_key_streq(key, "systemd.dump_core")) {
256
257 r = value ? parse_boolean(value) : true;
258 if (r < 0)
259 log_warning_errno(r, "Failed to parse dump core switch %s, ignoring: %m", value);
260 else
261 arg_dump_core = r;
262
263 } else if (proc_cmdline_key_streq(key, "systemd.early_core_pattern")) {
264
265 if (proc_cmdline_value_missing(key, value))
266 return 0;
267
268 if (path_is_absolute(value))
269 (void) parse_path_argument(value, false, &arg_early_core_pattern);
270 else
271 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value);
272
273 } else if (proc_cmdline_key_streq(key, "systemd.crash_chvt")) {
274
275 if (!value)
276 arg_crash_chvt = 0; /* turn on */
277 else {
278 r = parse_crash_chvt(value, &arg_crash_chvt);
279 if (r < 0)
280 log_warning_errno(r, "Failed to parse crash chvt switch %s, ignoring: %m", value);
281 }
282
283 } else if (proc_cmdline_key_streq(key, "systemd.crash_shell")) {
284
285 r = value ? parse_boolean(value) : true;
286 if (r < 0)
287 log_warning_errno(r, "Failed to parse crash shell switch %s, ignoring: %m", value);
288 else
289 arg_crash_shell = r;
290
291 } else if (proc_cmdline_key_streq(key, "systemd.crash_reboot")) {
292
293 r = value ? parse_boolean(value) : true;
294 if (r < 0)
295 log_warning_errno(r, "Failed to parse crash reboot switch %s, ignoring: %m", value);
296 else
297 arg_crash_reboot = r;
298
299 } else if (proc_cmdline_key_streq(key, "systemd.confirm_spawn")) {
300 char *s;
301
302 r = parse_confirm_spawn(value, &s);
303 if (r < 0)
304 log_warning_errno(r, "Failed to parse confirm_spawn switch %s, ignoring: %m", value);
305 else
306 free_and_replace(arg_confirm_spawn, s);
307
308 } else if (proc_cmdline_key_streq(key, "systemd.service_watchdogs")) {
309
310 r = value ? parse_boolean(value) : true;
311 if (r < 0)
312 log_warning_errno(r, "Failed to parse service watchdog switch %s, ignoring: %m", value);
313 else
314 arg_service_watchdogs = r;
315
316 } else if (proc_cmdline_key_streq(key, "systemd.show_status")) {
317
318 if (value) {
319 r = parse_show_status(value, &arg_show_status);
320 if (r < 0)
321 log_warning_errno(r, "Failed to parse show status switch %s, ignoring: %m", value);
322 } else
323 arg_show_status = SHOW_STATUS_YES;
324
325 } else if (proc_cmdline_key_streq(key, "systemd.status_unit_format")) {
326
327 if (proc_cmdline_value_missing(key, value))
328 return 0;
329
330 r = status_unit_format_from_string(value);
331 if (r < 0)
332 log_warning_errno(r, "Failed to parse %s=%s, ignoring: %m", key, value);
333 else
334 arg_status_unit_format = r;
335
336 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_output")) {
337
338 if (proc_cmdline_value_missing(key, value))
339 return 0;
340
341 r = exec_output_from_string(value);
342 if (r < 0)
343 log_warning_errno(r, "Failed to parse default standard output switch %s, ignoring: %m", value);
344 else
345 arg_default_std_output = r;
346
347 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_error")) {
348
349 if (proc_cmdline_value_missing(key, value))
350 return 0;
351
352 r = exec_output_from_string(value);
353 if (r < 0)
354 log_warning_errno(r, "Failed to parse default standard error switch %s, ignoring: %m", value);
355 else
356 arg_default_std_error = r;
357
358 } else if (streq(key, "systemd.setenv")) {
359
360 if (proc_cmdline_value_missing(key, value))
361 return 0;
362
363 if (!env_assignment_is_valid(value))
364 log_warning("Environment variable assignment '%s' is not valid. Ignoring.", value);
365 else {
366 r = strv_env_replace_strdup(&arg_default_environment, value);
367 if (r < 0)
368 return log_oom();
369 }
370
371 } else if (proc_cmdline_key_streq(key, "systemd.machine_id")) {
372
373 if (proc_cmdline_value_missing(key, value))
374 return 0;
375
376 r = set_machine_id(value);
377 if (r < 0)
378 log_warning_errno(r, "MachineID '%s' is not valid, ignoring: %m", value);
379
380 } else if (proc_cmdline_key_streq(key, "systemd.default_timeout_start_sec")) {
381
382 if (proc_cmdline_value_missing(key, value))
383 return 0;
384
385 r = parse_sec(value, &arg_default_timeout_start_usec);
386 if (r < 0)
387 log_warning_errno(r, "Failed to parse default start timeout '%s', ignoring: %m", value);
388
389 if (arg_default_timeout_start_usec <= 0)
390 arg_default_timeout_start_usec = USEC_INFINITY;
391
392 } else if (proc_cmdline_key_streq(key, "systemd.cpu_affinity")) {
393
394 if (proc_cmdline_value_missing(key, value))
395 return 0;
396
397 r = parse_cpu_set(value, &arg_cpu_affinity);
398 if (r < 0)
399 log_warning_errno(r, "Failed to parse CPU affinity mask '%s', ignoring: %m", value);
400
401 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_device")) {
402
403 if (proc_cmdline_value_missing(key, value))
404 return 0;
405
406 (void) parse_path_argument(value, false, &arg_watchdog_device);
407
408 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_sec")) {
409
410 if (proc_cmdline_value_missing(key, value))
411 return 0;
412
413 if (streq(value, "default"))
414 arg_runtime_watchdog = USEC_INFINITY;
415 else if (streq(value, "off"))
416 arg_runtime_watchdog = 0;
417 else {
418 r = parse_sec(value, &arg_runtime_watchdog);
419 if (r < 0) {
420 log_warning_errno(r, "Failed to parse systemd.watchdog_sec= argument '%s', ignoring: %m", value);
421 return 0;
422 }
423 }
424
425 arg_kexec_watchdog = arg_reboot_watchdog = arg_runtime_watchdog;
426
427 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_pre_sec")) {
428
429 if (proc_cmdline_value_missing(key, value))
430 return 0;
431
432 if (streq(value, "default"))
433 arg_pretimeout_watchdog = USEC_INFINITY;
434 else if (streq(value, "off"))
435 arg_pretimeout_watchdog = 0;
436 else {
437 r = parse_sec(value, &arg_pretimeout_watchdog);
438 if (r < 0) {
439 log_warning_errno(r, "Failed to parse systemd.watchdog_pre_sec= argument '%s', ignoring: %m", value);
440 return 0;
441 }
442 }
443
444 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_pretimeout_governor")) {
445
446 if (proc_cmdline_value_missing(key, value) || isempty(value)) {
447 arg_watchdog_pretimeout_governor = mfree(arg_watchdog_pretimeout_governor);
448 return 0;
449 }
450
451 if (!string_is_safe(value)) {
452 log_warning("Watchdog pretimeout governor '%s' is not valid, ignoring.", value);
453 return 0;
454 }
455
456 return free_and_strdup_warn(&arg_watchdog_pretimeout_governor, value);
457
458 } else if (proc_cmdline_key_streq(key, "systemd.clock_usec")) {
459
460 if (proc_cmdline_value_missing(key, value))
461 return 0;
462
463 r = safe_atou64(value, &arg_clock_usec);
464 if (r < 0)
465 log_warning_errno(r, "Failed to parse systemd.clock_usec= argument, ignoring: %s", value);
466
467 } else if (proc_cmdline_key_streq(key, "systemd.random_seed")) {
468 void *p;
469 size_t sz;
470
471 if (proc_cmdline_value_missing(key, value))
472 return 0;
473
474 r = unbase64mem(value, SIZE_MAX, &p, &sz);
475 if (r < 0)
476 log_warning_errno(r, "Failed to parse systemd.random_seed= argument, ignoring: %s", value);
477
478 free(arg_random_seed);
479 arg_random_seed = sz > 0 ? p : mfree(p);
480 arg_random_seed_size = sz;
481
482 } else if (streq(key, "quiet") && !value) {
483
484 if (arg_show_status == _SHOW_STATUS_INVALID)
485 arg_show_status = SHOW_STATUS_ERROR;
486
487 } else if (streq(key, "debug") && !value) {
488
489 /* Note that log_parse_environment() handles 'debug'
490 * too, and sets the log level to LOG_DEBUG. */
491
492 if (detect_container() > 0)
493 log_set_target(LOG_TARGET_CONSOLE);
494
495 } else if (!value) {
496 const char *target;
497
498 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
499 target = runlevel_to_target(key);
500 if (target)
501 return free_and_strdup_warn(&arg_default_unit, target);
502 }
503
504 return 0;
505 }
506
507 #define DEFINE_SETTER(name, func, descr) \
508 static int name(const char *unit, \
509 const char *filename, \
510 unsigned line, \
511 const char *section, \
512 unsigned section_line, \
513 const char *lvalue, \
514 int ltype, \
515 const char *rvalue, \
516 void *data, \
517 void *userdata) { \
518 \
519 int r; \
520 \
521 assert(filename); \
522 assert(lvalue); \
523 assert(rvalue); \
524 \
525 r = func(rvalue); \
526 if (r < 0) \
527 log_syntax(unit, LOG_ERR, filename, line, r, \
528 "Invalid " descr "'%s': %m", \
529 rvalue); \
530 \
531 return 0; \
532 }
533
534 DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level");
535 DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target");
536 DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color");
537 DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location");
538 DEFINE_SETTER(config_parse_time, log_show_time_from_string, "time");
539
540 static int config_parse_default_timeout_abort(
541 const char *unit,
542 const char *filename,
543 unsigned line,
544 const char *section,
545 unsigned section_line,
546 const char *lvalue,
547 int ltype,
548 const char *rvalue,
549 void *data,
550 void *userdata) {
551 int r;
552
553 r = config_parse_timeout_abort(unit, filename, line, section, section_line, lvalue, ltype, rvalue,
554 &arg_default_timeout_abort_usec, userdata);
555 if (r >= 0)
556 arg_default_timeout_abort_set = r;
557 return 0;
558 }
559
560 static int config_parse_oom_score_adjust(
561 const char *unit,
562 const char *filename,
563 unsigned line,
564 const char *section,
565 unsigned section_line,
566 const char *lvalue,
567 int ltype,
568 const char *rvalue,
569 void *data,
570 void *userdata) {
571
572 int oa, r;
573
574 if (isempty(rvalue)) {
575 arg_default_oom_score_adjust_set = false;
576 return 0;
577 }
578
579 r = parse_oom_score_adjust(rvalue, &oa);
580 if (r < 0) {
581 log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse the OOM score adjust value '%s', ignoring: %m", rvalue);
582 return 0;
583 }
584
585 arg_default_oom_score_adjust = oa;
586 arg_default_oom_score_adjust_set = true;
587
588 return 0;
589 }
590
591 static int parse_config_file(void) {
592 const ConfigTableItem items[] = {
593 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
594 { "Manager", "LogTarget", config_parse_target, 0, NULL },
595 { "Manager", "LogColor", config_parse_color, 0, NULL },
596 { "Manager", "LogLocation", config_parse_location, 0, NULL },
597 { "Manager", "LogTime", config_parse_time, 0, NULL },
598 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
599 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt, 0, &arg_crash_chvt },
600 { "Manager", "CrashChangeVT", config_parse_crash_chvt, 0, &arg_crash_chvt },
601 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
602 { "Manager", "CrashReboot", config_parse_bool, 0, &arg_crash_reboot },
603 { "Manager", "ShowStatus", config_parse_show_status, 0, &arg_show_status },
604 { "Manager", "StatusUnitFormat", config_parse_status_unit_format, 0, &arg_status_unit_format },
605 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, &arg_cpu_affinity },
606 { "Manager", "NUMAPolicy", config_parse_numa_policy, 0, &arg_numa_policy.type },
607 { "Manager", "NUMAMask", config_parse_numa_mask, 0, &arg_numa_policy },
608 { "Manager", "JoinControllers", config_parse_warn_compat, DISABLED_CONFIGURATION, NULL },
609 { "Manager", "RuntimeWatchdogSec", config_parse_watchdog_sec, 0, &arg_runtime_watchdog },
610 { "Manager", "RuntimeWatchdogPreSec", config_parse_watchdog_sec, 0, &arg_pretimeout_watchdog },
611 { "Manager", "RebootWatchdogSec", config_parse_watchdog_sec, 0, &arg_reboot_watchdog },
612 { "Manager", "ShutdownWatchdogSec", config_parse_watchdog_sec, 0, &arg_reboot_watchdog }, /* obsolete alias */
613 { "Manager", "KExecWatchdogSec", config_parse_watchdog_sec, 0, &arg_kexec_watchdog },
614 { "Manager", "WatchdogDevice", config_parse_path, 0, &arg_watchdog_device },
615 { "Manager", "RuntimeWatchdogPreGovernor", config_parse_string, CONFIG_PARSE_STRING_SAFE, &arg_watchdog_pretimeout_governor },
616 { "Manager", "CapabilityBoundingSet", config_parse_capability_set, 0, &arg_capability_bounding_set },
617 { "Manager", "NoNewPrivileges", config_parse_bool, 0, &arg_no_new_privs },
618 #if HAVE_SECCOMP
619 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
620 #endif
621 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
622 { "Manager", "DefaultTimerAccuracySec", config_parse_sec, 0, &arg_default_timer_accuracy_usec },
623 { "Manager", "DefaultStandardOutput", config_parse_output_restricted, 0, &arg_default_std_output },
624 { "Manager", "DefaultStandardError", config_parse_output_restricted, 0, &arg_default_std_error },
625 { "Manager", "DefaultTimeoutStartSec", config_parse_sec, 0, &arg_default_timeout_start_usec },
626 { "Manager", "DefaultTimeoutStopSec", config_parse_sec, 0, &arg_default_timeout_stop_usec },
627 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort, 0, NULL },
628 { "Manager", "DefaultRestartSec", config_parse_sec, 0, &arg_default_restart_usec },
629 { "Manager", "DefaultStartLimitInterval", config_parse_sec, 0, &arg_default_start_limit_interval }, /* obsolete alias */
630 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec, 0, &arg_default_start_limit_interval },
631 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned, 0, &arg_default_start_limit_burst },
632 { "Manager", "DefaultEnvironment", config_parse_environ, 0, &arg_default_environment },
633 { "Manager", "ManagerEnvironment", config_parse_environ, 0, &arg_manager_environment },
634 { "Manager", "DefaultLimitCPU", config_parse_rlimit, RLIMIT_CPU, arg_default_rlimit },
635 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit, RLIMIT_FSIZE, arg_default_rlimit },
636 { "Manager", "DefaultLimitDATA", config_parse_rlimit, RLIMIT_DATA, arg_default_rlimit },
637 { "Manager", "DefaultLimitSTACK", config_parse_rlimit, RLIMIT_STACK, arg_default_rlimit },
638 { "Manager", "DefaultLimitCORE", config_parse_rlimit, RLIMIT_CORE, arg_default_rlimit },
639 { "Manager", "DefaultLimitRSS", config_parse_rlimit, RLIMIT_RSS, arg_default_rlimit },
640 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit, RLIMIT_NOFILE, arg_default_rlimit },
641 { "Manager", "DefaultLimitAS", config_parse_rlimit, RLIMIT_AS, arg_default_rlimit },
642 { "Manager", "DefaultLimitNPROC", config_parse_rlimit, RLIMIT_NPROC, arg_default_rlimit },
643 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit, RLIMIT_MEMLOCK, arg_default_rlimit },
644 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit, RLIMIT_LOCKS, arg_default_rlimit },
645 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit, RLIMIT_SIGPENDING, arg_default_rlimit },
646 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit, RLIMIT_MSGQUEUE, arg_default_rlimit },
647 { "Manager", "DefaultLimitNICE", config_parse_rlimit, RLIMIT_NICE, arg_default_rlimit },
648 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit, RLIMIT_RTPRIO, arg_default_rlimit },
649 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit, RLIMIT_RTTIME, arg_default_rlimit },
650 { "Manager", "DefaultCPUAccounting", config_parse_tristate, 0, &arg_default_cpu_accounting },
651 { "Manager", "DefaultIOAccounting", config_parse_bool, 0, &arg_default_io_accounting },
652 { "Manager", "DefaultIPAccounting", config_parse_bool, 0, &arg_default_ip_accounting },
653 { "Manager", "DefaultBlockIOAccounting", config_parse_bool, 0, &arg_default_blockio_accounting },
654 { "Manager", "DefaultMemoryAccounting", config_parse_bool, 0, &arg_default_memory_accounting },
655 { "Manager", "DefaultTasksAccounting", config_parse_bool, 0, &arg_default_tasks_accounting },
656 { "Manager", "DefaultTasksMax", config_parse_tasks_max, 0, &arg_default_tasks_max },
657 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action, 0, &arg_cad_burst_action },
658 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy, 0, &arg_default_oom_policy },
659 { "Manager", "DefaultOOMScoreAdjust", config_parse_oom_score_adjust, 0, NULL },
660 {}
661 };
662
663 _cleanup_strv_free_ char **files = NULL, **dirs = NULL;
664 const char *suffix;
665 int r;
666
667 if (arg_system)
668 suffix = "system.conf.d";
669 else {
670 r = manager_find_user_config_paths(&files, &dirs);
671 if (r < 0)
672 return log_error_errno(r, "Failed to determine config file paths: %m");
673
674 suffix = "user.conf.d";
675 }
676
677 (void) config_parse_many(
678 (const char* const*) (files ?: STRV_MAKE(PKGSYSCONFDIR "/system.conf")),
679 (const char* const*) (dirs ?: CONF_PATHS_STRV("systemd")),
680 suffix,
681 "Manager\0",
682 config_item_table_lookup, items,
683 CONFIG_PARSE_WARN,
684 NULL,
685 NULL);
686
687 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we use
688 * USEC_INFINITY like everywhere else. */
689 if (arg_default_timeout_start_usec <= 0)
690 arg_default_timeout_start_usec = USEC_INFINITY;
691 if (arg_default_timeout_stop_usec <= 0)
692 arg_default_timeout_stop_usec = USEC_INFINITY;
693
694 return 0;
695 }
696
697 static void set_manager_defaults(Manager *m) {
698
699 assert(m);
700
701 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
702 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
703 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
704
705 m->default_timer_accuracy_usec = arg_default_timer_accuracy_usec;
706 m->default_std_output = arg_default_std_output;
707 m->default_std_error = arg_default_std_error;
708 m->default_timeout_start_usec = arg_default_timeout_start_usec;
709 m->default_timeout_stop_usec = arg_default_timeout_stop_usec;
710 m->default_timeout_abort_usec = arg_default_timeout_abort_usec;
711 m->default_timeout_abort_set = arg_default_timeout_abort_set;
712 m->default_restart_usec = arg_default_restart_usec;
713 m->default_start_limit_interval = arg_default_start_limit_interval;
714 m->default_start_limit_burst = arg_default_start_limit_burst;
715
716 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
717 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
718 if (arg_default_cpu_accounting >= 0)
719 m->default_cpu_accounting = arg_default_cpu_accounting;
720 else
721 m->default_cpu_accounting = cpu_accounting_is_cheap();
722
723 m->default_io_accounting = arg_default_io_accounting;
724 m->default_ip_accounting = arg_default_ip_accounting;
725 m->default_blockio_accounting = arg_default_blockio_accounting;
726 m->default_memory_accounting = arg_default_memory_accounting;
727 m->default_tasks_accounting = arg_default_tasks_accounting;
728 m->default_tasks_max = arg_default_tasks_max;
729 m->default_oom_policy = arg_default_oom_policy;
730 m->default_oom_score_adjust_set = arg_default_oom_score_adjust_set;
731 m->default_oom_score_adjust = arg_default_oom_score_adjust;
732
733 (void) manager_set_default_rlimits(m, arg_default_rlimit);
734
735 (void) manager_default_environment(m);
736 (void) manager_transient_environment_add(m, arg_default_environment);
737 }
738
739 static void set_manager_settings(Manager *m) {
740 int r;
741
742 assert(m);
743
744 /* Propagates the various manager settings into the manager object, i.e. properties that
745 * effect the manager itself (as opposed to just being inherited into newly allocated
746 * units, see set_manager_defaults() above). */
747
748 m->confirm_spawn = arg_confirm_spawn;
749 m->service_watchdogs = arg_service_watchdogs;
750 m->cad_burst_action = arg_cad_burst_action;
751
752 manager_set_watchdog(m, WATCHDOG_RUNTIME, arg_runtime_watchdog);
753 manager_set_watchdog(m, WATCHDOG_REBOOT, arg_reboot_watchdog);
754 manager_set_watchdog(m, WATCHDOG_KEXEC, arg_kexec_watchdog);
755 manager_set_watchdog(m, WATCHDOG_PRETIMEOUT, arg_pretimeout_watchdog);
756 r = manager_set_watchdog_pretimeout_governor(m, arg_watchdog_pretimeout_governor);
757 if (r < 0)
758 log_warning_errno(r, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor);
759
760 manager_set_show_status(m, arg_show_status, "commandline");
761 m->status_unit_format = arg_status_unit_format;
762 }
763
764 static int parse_argv(int argc, char *argv[]) {
765 enum {
766 ARG_LOG_LEVEL = 0x100,
767 ARG_LOG_TARGET,
768 ARG_LOG_COLOR,
769 ARG_LOG_LOCATION,
770 ARG_LOG_TIME,
771 ARG_UNIT,
772 ARG_SYSTEM,
773 ARG_USER,
774 ARG_TEST,
775 ARG_NO_PAGER,
776 ARG_VERSION,
777 ARG_DUMP_CONFIGURATION_ITEMS,
778 ARG_DUMP_BUS_PROPERTIES,
779 ARG_BUS_INTROSPECT,
780 ARG_DUMP_CORE,
781 ARG_CRASH_CHVT,
782 ARG_CRASH_SHELL,
783 ARG_CRASH_REBOOT,
784 ARG_CONFIRM_SPAWN,
785 ARG_SHOW_STATUS,
786 ARG_DESERIALIZE,
787 ARG_SWITCHED_ROOT,
788 ARG_DEFAULT_STD_OUTPUT,
789 ARG_DEFAULT_STD_ERROR,
790 ARG_MACHINE_ID,
791 ARG_SERVICE_WATCHDOGS,
792 };
793
794 static const struct option options[] = {
795 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
796 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
797 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
798 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
799 { "log-time", optional_argument, NULL, ARG_LOG_TIME },
800 { "unit", required_argument, NULL, ARG_UNIT },
801 { "system", no_argument, NULL, ARG_SYSTEM },
802 { "user", no_argument, NULL, ARG_USER },
803 { "test", no_argument, NULL, ARG_TEST },
804 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
805 { "help", no_argument, NULL, 'h' },
806 { "version", no_argument, NULL, ARG_VERSION },
807 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
808 { "dump-bus-properties", no_argument, NULL, ARG_DUMP_BUS_PROPERTIES },
809 { "bus-introspect", required_argument, NULL, ARG_BUS_INTROSPECT },
810 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
811 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
812 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
813 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
814 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
815 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
816 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
817 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
818 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
819 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
820 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
821 { "service-watchdogs", required_argument, NULL, ARG_SERVICE_WATCHDOGS },
822 {}
823 };
824
825 int c, r;
826 bool user_arg_seen = false;
827
828 assert(argc >= 1);
829 assert(argv);
830
831 if (getpid_cached() == 1)
832 opterr = 0;
833
834 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
835
836 switch (c) {
837
838 case ARG_LOG_LEVEL:
839 r = log_set_max_level_from_string(optarg);
840 if (r < 0)
841 return log_error_errno(r, "Failed to parse log level \"%s\": %m", optarg);
842
843 break;
844
845 case ARG_LOG_TARGET:
846 r = log_set_target_from_string(optarg);
847 if (r < 0)
848 return log_error_errno(r, "Failed to parse log target \"%s\": %m", optarg);
849
850 break;
851
852 case ARG_LOG_COLOR:
853
854 if (optarg) {
855 r = log_show_color_from_string(optarg);
856 if (r < 0)
857 return log_error_errno(r, "Failed to parse log color setting \"%s\": %m",
858 optarg);
859 } else
860 log_show_color(true);
861
862 break;
863
864 case ARG_LOG_LOCATION:
865 if (optarg) {
866 r = log_show_location_from_string(optarg);
867 if (r < 0)
868 return log_error_errno(r, "Failed to parse log location setting \"%s\": %m",
869 optarg);
870 } else
871 log_show_location(true);
872
873 break;
874
875 case ARG_LOG_TIME:
876
877 if (optarg) {
878 r = log_show_time_from_string(optarg);
879 if (r < 0)
880 return log_error_errno(r, "Failed to parse log time setting \"%s\": %m",
881 optarg);
882 } else
883 log_show_time(true);
884
885 break;
886
887 case ARG_DEFAULT_STD_OUTPUT:
888 r = exec_output_from_string(optarg);
889 if (r < 0)
890 return log_error_errno(r, "Failed to parse default standard output setting \"%s\": %m",
891 optarg);
892 arg_default_std_output = r;
893 break;
894
895 case ARG_DEFAULT_STD_ERROR:
896 r = exec_output_from_string(optarg);
897 if (r < 0)
898 return log_error_errno(r, "Failed to parse default standard error output setting \"%s\": %m",
899 optarg);
900 arg_default_std_error = r;
901 break;
902
903 case ARG_UNIT:
904 r = free_and_strdup(&arg_default_unit, optarg);
905 if (r < 0)
906 return log_error_errno(r, "Failed to set default unit \"%s\": %m", optarg);
907
908 break;
909
910 case ARG_SYSTEM:
911 arg_system = true;
912 break;
913
914 case ARG_USER:
915 arg_system = false;
916 user_arg_seen = true;
917 break;
918
919 case ARG_TEST:
920 arg_action = ACTION_TEST;
921 break;
922
923 case ARG_NO_PAGER:
924 arg_pager_flags |= PAGER_DISABLE;
925 break;
926
927 case ARG_VERSION:
928 arg_action = ACTION_VERSION;
929 break;
930
931 case ARG_DUMP_CONFIGURATION_ITEMS:
932 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
933 break;
934
935 case ARG_DUMP_BUS_PROPERTIES:
936 arg_action = ACTION_DUMP_BUS_PROPERTIES;
937 break;
938
939 case ARG_BUS_INTROSPECT:
940 arg_bus_introspect = optarg;
941 arg_action = ACTION_BUS_INTROSPECT;
942 break;
943
944 case ARG_DUMP_CORE:
945 r = parse_boolean_argument("--dump-core", optarg, &arg_dump_core);
946 if (r < 0)
947 return r;
948 break;
949
950 case ARG_CRASH_CHVT:
951 r = parse_crash_chvt(optarg, &arg_crash_chvt);
952 if (r < 0)
953 return log_error_errno(r, "Failed to parse crash virtual terminal index: \"%s\": %m",
954 optarg);
955 break;
956
957 case ARG_CRASH_SHELL:
958 r = parse_boolean_argument("--crash-shell", optarg, &arg_crash_shell);
959 if (r < 0)
960 return r;
961 break;
962
963 case ARG_CRASH_REBOOT:
964 r = parse_boolean_argument("--crash-reboot", optarg, &arg_crash_reboot);
965 if (r < 0)
966 return r;
967 break;
968
969 case ARG_CONFIRM_SPAWN:
970 arg_confirm_spawn = mfree(arg_confirm_spawn);
971
972 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
973 if (r < 0)
974 return log_error_errno(r, "Failed to parse confirm spawn option: \"%s\": %m",
975 optarg);
976 break;
977
978 case ARG_SERVICE_WATCHDOGS:
979 r = parse_boolean_argument("--service-watchdogs=", optarg, &arg_service_watchdogs);
980 if (r < 0)
981 return r;
982 break;
983
984 case ARG_SHOW_STATUS:
985 if (optarg) {
986 r = parse_show_status(optarg, &arg_show_status);
987 if (r < 0)
988 return log_error_errno(r, "Failed to parse show status boolean: \"%s\": %m",
989 optarg);
990 } else
991 arg_show_status = SHOW_STATUS_YES;
992 break;
993
994 case ARG_DESERIALIZE: {
995 int fd;
996 FILE *f;
997
998 r = safe_atoi(optarg, &fd);
999 if (r < 0)
1000 log_error_errno(r, "Failed to parse deserialize option \"%s\": %m", optarg);
1001 if (fd < 0)
1002 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1003 "Invalid deserialize fd: %d",
1004 fd);
1005
1006 (void) fd_cloexec(fd, true);
1007
1008 f = fdopen(fd, "r");
1009 if (!f)
1010 return log_error_errno(errno, "Failed to open serialization fd %d: %m", fd);
1011
1012 safe_fclose(arg_serialization);
1013 arg_serialization = f;
1014
1015 break;
1016 }
1017
1018 case ARG_SWITCHED_ROOT:
1019 arg_switched_root = true;
1020 break;
1021
1022 case ARG_MACHINE_ID:
1023 r = set_machine_id(optarg);
1024 if (r < 0)
1025 return log_error_errno(r, "MachineID '%s' is not valid: %m", optarg);
1026 break;
1027
1028 case 'h':
1029 arg_action = ACTION_HELP;
1030 break;
1031
1032 case 'D':
1033 log_set_max_level(LOG_DEBUG);
1034 break;
1035
1036 case 'b':
1037 case 's':
1038 case 'z':
1039 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1040 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1041 */
1042 case '?':
1043 if (getpid_cached() != 1)
1044 return -EINVAL;
1045 else
1046 return 0;
1047
1048 default:
1049 assert_not_reached();
1050 }
1051
1052 if (optind < argc && getpid_cached() != 1)
1053 /* Hmm, when we aren't run as init system let's complain about excess arguments */
1054 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Excess arguments.");
1055
1056 if (arg_action == ACTION_RUN && !arg_system && !user_arg_seen)
1057 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1058 "Explicit --user argument required to run as user manager.");
1059
1060 return 0;
1061 }
1062
1063 static int help(void) {
1064 _cleanup_free_ char *link = NULL;
1065 int r;
1066
1067 r = terminal_urlify_man("systemd", "1", &link);
1068 if (r < 0)
1069 return log_oom();
1070
1071 printf("%s [OPTIONS...]\n\n"
1072 "%sStarts and monitors system and user services.%s\n\n"
1073 "This program takes no positional arguments.\n\n"
1074 "%sOptions%s:\n"
1075 " -h --help Show this help\n"
1076 " --version Show version\n"
1077 " --test Determine initial transaction, dump it and exit\n"
1078 " --system Combined with --test: operate in system mode\n"
1079 " --user Combined with --test: operate in user mode\n"
1080 " --dump-configuration-items Dump understood unit configuration items\n"
1081 " --dump-bus-properties Dump exposed bus properties\n"
1082 " --bus-introspect=PATH Write XML introspection data\n"
1083 " --unit=UNIT Set default unit\n"
1084 " --dump-core[=BOOL] Dump core on crash\n"
1085 " --crash-vt=NR Change to specified VT on crash\n"
1086 " --crash-reboot[=BOOL] Reboot on crash\n"
1087 " --crash-shell[=BOOL] Run shell on crash\n"
1088 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1089 " --show-status[=BOOL] Show status updates on the console during boot\n"
1090 " --log-target=TARGET Set log target (console, journal, kmsg,\n"
1091 " journal-or-kmsg, null)\n"
1092 " --log-level=LEVEL Set log level (debug, info, notice, warning,\n"
1093 " err, crit, alert, emerg)\n"
1094 " --log-color[=BOOL] Highlight important log messages\n"
1095 " --log-location[=BOOL] Include code location in log messages\n"
1096 " --log-time[=BOOL] Prefix log messages with current time\n"
1097 " --default-standard-output= Set default standard output for services\n"
1098 " --default-standard-error= Set default standard error output for services\n"
1099 " --no-pager Do not pipe output into a pager\n"
1100 "\nSee the %s for details.\n",
1101 program_invocation_short_name,
1102 ansi_highlight(),
1103 ansi_normal(),
1104 ansi_underline(),
1105 ansi_normal(),
1106 link);
1107
1108 return 0;
1109 }
1110
1111 static int prepare_reexecute(
1112 Manager *m,
1113 FILE **ret_f,
1114 FDSet **ret_fds,
1115 bool switching_root) {
1116
1117 _cleanup_fdset_free_ FDSet *fds = NULL;
1118 _cleanup_fclose_ FILE *f = NULL;
1119 int r;
1120
1121 assert(m);
1122 assert(ret_f);
1123 assert(ret_fds);
1124
1125 r = manager_open_serialization(m, &f);
1126 if (r < 0)
1127 return log_error_errno(r, "Failed to create serialization file: %m");
1128
1129 /* Make sure nothing is really destructed when we shut down */
1130 m->n_reloading++;
1131 bus_manager_send_reloading(m, true);
1132
1133 fds = fdset_new();
1134 if (!fds)
1135 return log_oom();
1136
1137 r = manager_serialize(m, f, fds, switching_root);
1138 if (r < 0)
1139 return r;
1140
1141 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1142 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
1143
1144 r = fd_cloexec(fileno(f), false);
1145 if (r < 0)
1146 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
1147
1148 r = fdset_cloexec(fds, false);
1149 if (r < 0)
1150 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
1151
1152 *ret_f = TAKE_PTR(f);
1153 *ret_fds = TAKE_PTR(fds);
1154
1155 return 0;
1156 }
1157
1158 static void bump_file_max_and_nr_open(void) {
1159
1160 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
1161 * numbers of file descriptors are no longer a performance problem and their memory is properly
1162 * tracked by memcg, thus counting them and limiting them in another two layers of limits is
1163 * unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
1164 * on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
1165
1166 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1167 int r;
1168 #endif
1169
1170 #if BUMP_PROC_SYS_FS_FILE_MAX
1171 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
1172 * different, but the operation would fail silently.) */
1173 r = sysctl_writef("fs/file-max", "%li\n", LONG_MAX);
1174 if (r < 0)
1175 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r, "Failed to bump fs.file-max, ignoring: %m");
1176 #endif
1177
1178 #if BUMP_PROC_SYS_FS_NR_OPEN
1179 int v = INT_MAX;
1180
1181 /* Argh! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know
1182 * what they are. The expression by which the maximum is determined is dependent on the architecture,
1183 * and is something we don't really want to copy to userspace, as it is dependent on implementation
1184 * details of the kernel. Since the kernel doesn't expose the maximum value to us, we can only try
1185 * and hope. Hence, let's start with INT_MAX, and then keep halving the value until we find one that
1186 * works. Ugly? Yes, absolutely, but kernel APIs are kernel APIs, so what do can we do... 🤯 */
1187
1188 for (;;) {
1189 int k;
1190
1191 v &= ~(__SIZEOF_POINTER__ - 1); /* Round down to next multiple of the pointer size */
1192 if (v < 1024) {
1193 log_warning("Can't bump fs.nr_open, value too small.");
1194 break;
1195 }
1196
1197 k = read_nr_open();
1198 if (k < 0) {
1199 log_error_errno(k, "Failed to read fs.nr_open: %m");
1200 break;
1201 }
1202 if (k >= v) { /* Already larger */
1203 log_debug("Skipping bump, value is already larger.");
1204 break;
1205 }
1206
1207 r = sysctl_writef("fs/nr_open", "%i\n", v);
1208 if (r == -EINVAL) {
1209 log_debug("Couldn't write fs.nr_open as %i, halving it.", v);
1210 v /= 2;
1211 continue;
1212 }
1213 if (r < 0) {
1214 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r, "Failed to bump fs.nr_open, ignoring: %m");
1215 break;
1216 }
1217
1218 log_debug("Successfully bumped fs.nr_open to %i", v);
1219 break;
1220 }
1221 #endif
1222 }
1223
1224 static int bump_rlimit_nofile(const struct rlimit *saved_rlimit) {
1225 struct rlimit new_rlimit;
1226 int r, nr;
1227
1228 /* Get the underlying absolute limit the kernel enforces */
1229 nr = read_nr_open();
1230
1231 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1232 new_rlimit = (struct rlimit) {
1233 .rlim_cur = MAX((rlim_t) nr, saved_rlimit->rlim_cur),
1234 .rlim_max = MAX((rlim_t) nr, saved_rlimit->rlim_max),
1235 };
1236
1237 /* Shortcut if nothing changes. */
1238 if (saved_rlimit->rlim_max >= new_rlimit.rlim_max &&
1239 saved_rlimit->rlim_cur >= new_rlimit.rlim_cur) {
1240 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1241 return 0;
1242 }
1243
1244 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1245 * both hard and soft. */
1246 r = setrlimit_closest(RLIMIT_NOFILE, &new_rlimit);
1247 if (r < 0)
1248 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1249
1250 return 0;
1251 }
1252
1253 static int bump_rlimit_memlock(const struct rlimit *saved_rlimit) {
1254 struct rlimit new_rlimit;
1255 uint64_t mm;
1256 int r;
1257
1258 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
1259 * which should normally disable such checks. We need them to implement IPAddressAllow= and
1260 * IPAddressDeny=, hence let's bump the value high enough for our user. */
1261
1262 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1263 * must be unsigned, hence this is a given, but let's make this clear here. */
1264 assert_cc(RLIM_INFINITY > 0);
1265
1266 mm = physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
1267 * physical RAM. We allow an eighth to be locked by us, just to
1268 * pick a value. */
1269
1270 new_rlimit = (struct rlimit) {
1271 .rlim_cur = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_cur, mm),
1272 .rlim_max = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_max, mm),
1273 };
1274
1275 if (saved_rlimit->rlim_max >= new_rlimit.rlim_cur &&
1276 saved_rlimit->rlim_cur >= new_rlimit.rlim_max) {
1277 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1278 return 0;
1279 }
1280
1281 r = setrlimit_closest(RLIMIT_MEMLOCK, &new_rlimit);
1282 if (r < 0)
1283 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1284
1285 return 0;
1286 }
1287
1288 static void test_usr(void) {
1289
1290 /* Check that /usr is either on the same file system as / or mounted already. */
1291
1292 if (dir_is_empty("/usr") <= 0)
1293 return;
1294
1295 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1296 "Some things will probably break (sometimes even silently) in mysterious ways. "
1297 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1298 }
1299
1300 static int enforce_syscall_archs(Set *archs) {
1301 #if HAVE_SECCOMP
1302 int r;
1303
1304 if (!is_seccomp_available())
1305 return 0;
1306
1307 r = seccomp_restrict_archs(arg_syscall_archs);
1308 if (r < 0)
1309 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
1310 #endif
1311 return 0;
1312 }
1313
1314 static int status_welcome(void) {
1315 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1316 int r;
1317
1318 if (!show_status_on(arg_show_status))
1319 return 0;
1320
1321 r = parse_os_release(NULL,
1322 "PRETTY_NAME", &pretty_name,
1323 "ANSI_COLOR", &ansi_color);
1324 if (r < 0)
1325 log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1326 "Failed to read os-release file, ignoring: %m");
1327
1328 if (log_get_show_color())
1329 return status_printf(NULL, 0,
1330 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1331 isempty(ansi_color) ? "1" : ansi_color,
1332 isempty(pretty_name) ? "Linux" : pretty_name);
1333 else
1334 return status_printf(NULL, 0,
1335 "\nWelcome to %s!\n",
1336 isempty(pretty_name) ? "Linux" : pretty_name);
1337 }
1338
1339 static int write_container_id(void) {
1340 const char *c;
1341 int r = 0; /* avoid false maybe-uninitialized warning */
1342
1343 c = getenv("container");
1344 if (isempty(c))
1345 return 0;
1346
1347 RUN_WITH_UMASK(0022)
1348 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
1349 if (r < 0)
1350 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
1351
1352 return 1;
1353 }
1354
1355 static int bump_unix_max_dgram_qlen(void) {
1356 _cleanup_free_ char *qlen = NULL;
1357 unsigned long v;
1358 int r;
1359
1360 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
1361 * the value really really early during boot, so that it is actually applied to all our sockets,
1362 * including the $NOTIFY_SOCKET one. */
1363
1364 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1365 if (r < 0)
1366 return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1367 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1368
1369 r = safe_atolu(qlen, &v);
1370 if (r < 0)
1371 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen);
1372
1373 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1374 return 0;
1375
1376 r = write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER,
1377 "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN);
1378 if (r < 0)
1379 return log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1380 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1381
1382 return 1;
1383 }
1384
1385 static int fixup_environment(void) {
1386 _cleanup_free_ char *term = NULL;
1387 const char *t;
1388 int r;
1389
1390 /* Only fix up the environment when we are started as PID 1 */
1391 if (getpid_cached() != 1)
1392 return 0;
1393
1394 /* We expect the environment to be set correctly if run inside a container. */
1395 if (detect_container() > 0)
1396 return 0;
1397
1398 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
1399 * backend device used by the console. We try to make a better guess here since some consoles might
1400 * not have support for color mode for example.
1401 *
1402 * However if TERM was configured through the kernel command line then leave it alone. */
1403 r = proc_cmdline_get_key("TERM", 0, &term);
1404 if (r < 0)
1405 return r;
1406
1407 t = term ?: default_term_for_tty("/dev/console");
1408
1409 if (setenv("TERM", t, 1) < 0)
1410 return -errno;
1411
1412 /* The kernels sets HOME=/ for init. Let's undo this. */
1413 if (path_equal_ptr(getenv("HOME"), "/"))
1414 assert_se(unsetenv("HOME") == 0);
1415
1416 return 0;
1417 }
1418
1419 static void redirect_telinit(int argc, char *argv[]) {
1420
1421 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1422
1423 #if HAVE_SYSV_COMPAT
1424 if (getpid_cached() == 1)
1425 return;
1426
1427 if (!invoked_as(argv, "init"))
1428 return;
1429
1430 execv(SYSTEMCTL_BINARY_PATH, argv);
1431 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
1432 exit(EXIT_FAILURE);
1433 #endif
1434 }
1435
1436 static int become_shutdown(
1437 const char *shutdown_verb,
1438 int retval) {
1439
1440 char log_level[DECIMAL_STR_MAX(int) + 1],
1441 exit_code[DECIMAL_STR_MAX(uint8_t) + 1],
1442 timeout[DECIMAL_STR_MAX(usec_t) + 1];
1443
1444 const char* command_line[13] = {
1445 SYSTEMD_SHUTDOWN_BINARY_PATH,
1446 shutdown_verb,
1447 "--timeout", timeout,
1448 "--log-level", log_level,
1449 "--log-target",
1450 };
1451
1452 _cleanup_strv_free_ char **env_block = NULL;
1453 usec_t watchdog_timer = 0;
1454 size_t pos = 7;
1455 int r;
1456
1457 assert(shutdown_verb);
1458 assert(!command_line[pos]);
1459 env_block = strv_copy(environ);
1460
1461 xsprintf(log_level, "%d", log_get_max_level());
1462 xsprintf(timeout, "%" PRI_USEC "us", arg_default_timeout_stop_usec);
1463
1464 switch (log_get_target()) {
1465
1466 case LOG_TARGET_KMSG:
1467 case LOG_TARGET_JOURNAL_OR_KMSG:
1468 case LOG_TARGET_SYSLOG_OR_KMSG:
1469 command_line[pos++] = "kmsg";
1470 break;
1471
1472 case LOG_TARGET_NULL:
1473 command_line[pos++] = "null";
1474 break;
1475
1476 case LOG_TARGET_CONSOLE:
1477 default:
1478 command_line[pos++] = "console";
1479 break;
1480 };
1481
1482 if (log_get_show_color())
1483 command_line[pos++] = "--log-color";
1484
1485 if (log_get_show_location())
1486 command_line[pos++] = "--log-location";
1487
1488 if (log_get_show_time())
1489 command_line[pos++] = "--log-time";
1490
1491 if (streq(shutdown_verb, "exit")) {
1492 command_line[pos++] = "--exit-code";
1493 command_line[pos++] = exit_code;
1494 xsprintf(exit_code, "%d", retval);
1495 }
1496
1497 assert(pos < ELEMENTSOF(command_line));
1498
1499 if (streq(shutdown_verb, "reboot"))
1500 watchdog_timer = arg_reboot_watchdog;
1501 else if (streq(shutdown_verb, "kexec"))
1502 watchdog_timer = arg_kexec_watchdog;
1503
1504 /* If we reboot or kexec let's set the shutdown watchdog and tell the
1505 * shutdown binary to repeatedly ping it.
1506 * Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
1507 (void) watchdog_setup_pretimeout(0);
1508 (void) watchdog_setup_pretimeout_governor(NULL);
1509 r = watchdog_setup(watchdog_timer);
1510 watchdog_close(r < 0);
1511
1512 /* Tell the binary how often to ping, ignore failure */
1513 (void) strv_extendf(&env_block, "WATCHDOG_USEC="USEC_FMT, watchdog_timer);
1514
1515 if (arg_watchdog_device)
1516 (void) strv_extendf(&env_block, "WATCHDOG_DEVICE=%s", arg_watchdog_device);
1517
1518 /* Avoid the creation of new processes forked by the kernel; at this
1519 * point, we will not listen to the signals anyway */
1520 if (detect_container() <= 0)
1521 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
1522
1523 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
1524 return -errno;
1525 }
1526
1527 static void initialize_clock(void) {
1528 int r;
1529
1530 /* This is called very early on, before we parse the kernel command line or otherwise figure out why
1531 * we are running, but only once. */
1532
1533 if (clock_is_localtime(NULL) > 0) {
1534 int min;
1535
1536 /* The very first call of settimeofday() also does a time warp in the kernel.
1537 *
1538 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
1539 * take care of maintaining the RTC and do all adjustments. This matches the behavior of
1540 * Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
1541 */
1542 r = clock_set_timezone(&min);
1543 if (r < 0)
1544 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
1545 else
1546 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1547
1548 } else if (!in_initrd())
1549 /*
1550 * Do a dummy very first call to seal the kernel's time warp magic.
1551 *
1552 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
1553 * LOCAL, but the real system could be set up that way. In such case, we need to delay the
1554 * time-warp or the sealing until we reach the real system.
1555 *
1556 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
1557 * the time will jump or be incorrect at every daylight saving time change. All kernel local
1558 * time concepts will be treated as UTC that way.
1559 */
1560 (void) clock_reset_timewarp();
1561
1562 ClockChangeDirection change_dir;
1563 r = clock_apply_epoch(&change_dir);
1564 if (r > 0 && change_dir == CLOCK_CHANGE_FORWARD)
1565 log_info("System time before build time, advancing clock.");
1566 else if (r > 0 && change_dir == CLOCK_CHANGE_BACKWARD)
1567 log_info("System time is further ahead than %s after build time, resetting clock to build time.",
1568 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX, USEC_PER_DAY));
1569 else if (r < 0 && change_dir == CLOCK_CHANGE_FORWARD)
1570 log_error_errno(r, "Current system time is before build time, but cannot correct: %m");
1571 else if (r < 0 && change_dir == CLOCK_CHANGE_BACKWARD)
1572 log_error_errno(r, "Current system time is further ahead %s after build time, but cannot correct: %m",
1573 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX, USEC_PER_DAY));
1574 }
1575
1576 static void apply_clock_update(void) {
1577 /* This is called later than initialize_clock(), i.e. after we parsed configuration files/kernel
1578 * command line and such. */
1579
1580 if (arg_clock_usec == 0)
1581 return;
1582
1583 if (getpid_cached() != 1)
1584 return;
1585
1586 if (clock_settime(CLOCK_REALTIME, TIMESPEC_STORE(arg_clock_usec)) < 0)
1587 log_error_errno(errno, "Failed to set system clock to time specified on kernel command line: %m");
1588 else
1589 log_info("Set system clock to %s, as specified on the kernel command line.",
1590 FORMAT_TIMESTAMP(arg_clock_usec));
1591 }
1592
1593 static void cmdline_take_random_seed(void) {
1594 size_t suggested;
1595 int r;
1596
1597 if (arg_random_seed_size == 0)
1598 return;
1599
1600 if (getpid_cached() != 1)
1601 return;
1602
1603 assert(arg_random_seed);
1604 suggested = random_pool_size();
1605
1606 if (arg_random_seed_size < suggested)
1607 log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
1608 arg_random_seed_size, suggested);
1609
1610 r = random_write_entropy(-1, arg_random_seed, arg_random_seed_size, true);
1611 if (r < 0) {
1612 log_warning_errno(r, "Failed to credit entropy specified on kernel command line, ignoring: %m");
1613 return;
1614 }
1615
1616 log_notice("Successfully credited entropy passed on kernel command line.\n"
1617 "Note that the seed provided this way is accessible to unprivileged programs. "
1618 "This functionality should not be used outside of testing environments.");
1619 }
1620
1621 static void initialize_coredump(bool skip_setup) {
1622 #if ENABLE_COREDUMP
1623 if (getpid_cached() != 1)
1624 return;
1625
1626 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
1627 * the limit) will process core dumps for system services by default. */
1628 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1629 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
1630
1631 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1632 * until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
1633 * command line later so core dumps can still be generated during early startup and in initramfs. */
1634 if (!skip_setup)
1635 disable_coredumps();
1636 #endif
1637 }
1638
1639 static void initialize_core_pattern(bool skip_setup) {
1640 int r;
1641
1642 if (skip_setup || !arg_early_core_pattern)
1643 return;
1644
1645 if (getpid_cached() != 1)
1646 return;
1647
1648 r = write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern, WRITE_STRING_FILE_DISABLE_BUFFER);
1649 if (r < 0)
1650 log_warning_errno(r, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1651 arg_early_core_pattern);
1652 }
1653
1654 static void update_cpu_affinity(bool skip_setup) {
1655 _cleanup_free_ char *mask = NULL;
1656
1657 if (skip_setup || !arg_cpu_affinity.set)
1658 return;
1659
1660 assert(arg_cpu_affinity.allocated > 0);
1661
1662 mask = cpu_set_to_range_string(&arg_cpu_affinity);
1663 log_debug("Setting CPU affinity to {%s}.", strnull(mask));
1664
1665 if (sched_setaffinity(0, arg_cpu_affinity.allocated, arg_cpu_affinity.set) < 0)
1666 log_warning_errno(errno, "Failed to set CPU affinity, ignoring: %m");
1667 }
1668
1669 static void update_numa_policy(bool skip_setup) {
1670 int r;
1671 _cleanup_free_ char *nodes = NULL;
1672 const char * policy = NULL;
1673
1674 if (skip_setup || !mpol_is_valid(numa_policy_get_type(&arg_numa_policy)))
1675 return;
1676
1677 if (DEBUG_LOGGING) {
1678 policy = mpol_to_string(numa_policy_get_type(&arg_numa_policy));
1679 nodes = cpu_set_to_range_string(&arg_numa_policy.nodes);
1680 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy), strnull(nodes));
1681 }
1682
1683 r = apply_numa_policy(&arg_numa_policy);
1684 if (r == -EOPNOTSUPP)
1685 log_debug_errno(r, "NUMA support not available, ignoring.");
1686 else if (r < 0)
1687 log_warning_errno(r, "Failed to set NUMA memory policy, ignoring: %m");
1688 }
1689
1690 static void filter_args(
1691 const char* dst[],
1692 size_t *dst_index,
1693 char **src,
1694 int argc) {
1695
1696 assert(dst);
1697 assert(dst_index);
1698
1699 /* Copy some filtered arguments into the dst array from src. */
1700 for (int i = 1; i < argc; i++) {
1701 if (STR_IN_SET(src[i],
1702 "--switched-root",
1703 "--system",
1704 "--user"))
1705 continue;
1706
1707 if (startswith(src[i], "--deserialize="))
1708 continue;
1709 if (streq(src[i], "--deserialize")) {
1710 i++; /* Skip the argument too */
1711 continue;
1712 }
1713
1714 /* Skip target unit designators. We already acted upon this information and have queued
1715 * appropriate jobs. We don't want to redo all this after reexecution. */
1716 if (startswith(src[i], "--unit="))
1717 continue;
1718 if (streq(src[i], "--unit")) {
1719 i++; /* Skip the argument too */
1720 continue;
1721 }
1722
1723 if (startswith(src[i],
1724 in_initrd() ? "rd.systemd.unit=" : "systemd.unit="))
1725 continue;
1726
1727 if (runlevel_to_target(src[i]))
1728 continue;
1729
1730 /* Seems we have a good old option. Let's pass it over to the new instance. */
1731 dst[(*dst_index)++] = src[i];
1732 }
1733 }
1734
1735 static int do_reexecute(
1736 ManagerObjective objective,
1737 int argc,
1738 char* argv[],
1739 const struct rlimit *saved_rlimit_nofile,
1740 const struct rlimit *saved_rlimit_memlock,
1741 FDSet *fds,
1742 const char *switch_root_dir,
1743 const char *switch_root_init,
1744 const char **ret_error_message) {
1745
1746 size_t i, args_size;
1747 const char **args;
1748 int r;
1749
1750 assert(IN_SET(objective, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT));
1751 assert(argc >= 0);
1752 assert(saved_rlimit_nofile);
1753 assert(saved_rlimit_memlock);
1754 assert(ret_error_message);
1755
1756 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1757 * rebooted while we do that */
1758 watchdog_close(true);
1759
1760 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1761 * the kernel default to its child processes */
1762 if (saved_rlimit_nofile->rlim_cur != 0)
1763 (void) setrlimit(RLIMIT_NOFILE, saved_rlimit_nofile);
1764 if (saved_rlimit_memlock->rlim_cur != RLIM_INFINITY)
1765 (void) setrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock);
1766
1767 if (switch_root_dir) {
1768 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can
1769 * handle the SIGCHLD for them after deserializing. */
1770 broadcast_signal(SIGTERM, false, true, arg_default_timeout_stop_usec);
1771
1772 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1773 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
1774 if (r < 0)
1775 log_error_errno(r, "Failed to switch root, trying to continue: %m");
1776 }
1777
1778 args_size = argc + 6;
1779 args = newa(const char*, args_size);
1780
1781 if (!switch_root_init) {
1782 char sfd[DECIMAL_STR_MAX(int)];
1783
1784 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1785 * only if the user didn't specify an explicit init to spawn. */
1786
1787 assert(arg_serialization);
1788 assert(fds);
1789
1790 xsprintf(sfd, "%i", fileno(arg_serialization));
1791
1792 i = 1; /* Leave args[0] empty for now. */
1793 filter_args(args, &i, argv, argc);
1794
1795 if (switch_root_dir)
1796 args[i++] = "--switched-root";
1797 args[i++] = arg_system ? "--system" : "--user";
1798 args[i++] = "--deserialize";
1799 args[i++] = sfd;
1800 args[i++] = NULL;
1801
1802 assert(i <= args_size);
1803
1804 /*
1805 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
1806 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
1807 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
1808 * and wait() for it in the parent, before proceeding into the exec().
1809 */
1810 valgrind_summary_hack();
1811
1812 args[0] = SYSTEMD_BINARY_PATH;
1813 (void) execv(args[0], (char* const*) args);
1814
1815 if (objective == MANAGER_REEXECUTE) {
1816 *ret_error_message = "Failed to execute our own binary";
1817 return log_error_errno(errno, "Failed to execute our own binary %s: %m", args[0]);
1818 }
1819
1820 log_debug_errno(errno, "Failed to execute our own binary %s, trying fallback: %m", args[0]);
1821 }
1822
1823 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
1824 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
1825 * but let's hope that doesn't matter.) */
1826
1827 arg_serialization = safe_fclose(arg_serialization);
1828 fds = fdset_free(fds);
1829
1830 /* Reopen the console */
1831 (void) make_console_stdio();
1832
1833 i = 1; /* Leave args[0] empty for now. */
1834 for (int j = 1; j <= argc; j++)
1835 args[i++] = argv[j];
1836 assert(i <= args_size);
1837
1838 /* Re-enable any blocked signals, especially important if we switch from initial ramdisk to init=... */
1839 (void) reset_all_signal_handlers();
1840 (void) reset_signal_mask();
1841 (void) rlimit_nofile_safe();
1842
1843 if (switch_root_init) {
1844 args[0] = switch_root_init;
1845 (void) execve(args[0], (char* const*) args, saved_env);
1846 log_warning_errno(errno, "Failed to execute configured init %s, trying fallback: %m", args[0]);
1847 }
1848
1849 args[0] = "/sbin/init";
1850 (void) execv(args[0], (char* const*) args);
1851 r = -errno;
1852
1853 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1854 ANSI_HIGHLIGHT_RED " !! " ANSI_NORMAL,
1855 "Failed to execute /sbin/init");
1856
1857 *ret_error_message = "Failed to execute fallback shell";
1858 if (r == -ENOENT) {
1859 log_warning("No /sbin/init, trying fallback");
1860
1861 args[0] = "/bin/sh";
1862 args[1] = NULL;
1863 (void) execve(args[0], (char* const*) args, saved_env);
1864 return log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
1865 } else
1866 return log_error_errno(r, "Failed to execute /sbin/init, giving up: %m");
1867 }
1868
1869 static int invoke_main_loop(
1870 Manager *m,
1871 const struct rlimit *saved_rlimit_nofile,
1872 const struct rlimit *saved_rlimit_memlock,
1873 int *ret_retval, /* Return parameters relevant for shutting down */
1874 const char **ret_shutdown_verb, /* … */
1875 FDSet **ret_fds, /* Return parameters for reexecuting */
1876 char **ret_switch_root_dir, /* … */
1877 char **ret_switch_root_init, /* … */
1878 const char **ret_error_message) {
1879
1880 int r;
1881
1882 assert(m);
1883 assert(saved_rlimit_nofile);
1884 assert(saved_rlimit_memlock);
1885 assert(ret_retval);
1886 assert(ret_shutdown_verb);
1887 assert(ret_fds);
1888 assert(ret_switch_root_dir);
1889 assert(ret_switch_root_init);
1890 assert(ret_error_message);
1891
1892 for (;;) {
1893 int objective = manager_loop(m);
1894 if (objective < 0) {
1895 *ret_error_message = "Failed to run main loop";
1896 return log_emergency_errno(objective, "Failed to run main loop: %m");
1897 }
1898
1899 switch (objective) {
1900
1901 case MANAGER_RELOAD: {
1902 LogTarget saved_log_target;
1903 int saved_log_level;
1904
1905 log_info("Reloading.");
1906
1907 /* First, save any overridden log level/target, then parse the configuration file,
1908 * which might change the log level to new settings. */
1909
1910 saved_log_level = m->log_level_overridden ? log_get_max_level() : -1;
1911 saved_log_target = m->log_target_overridden ? log_get_target() : _LOG_TARGET_INVALID;
1912
1913 (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
1914
1915 set_manager_defaults(m);
1916 set_manager_settings(m);
1917
1918 update_cpu_affinity(false);
1919 update_numa_policy(false);
1920
1921 if (saved_log_level >= 0)
1922 manager_override_log_level(m, saved_log_level);
1923 if (saved_log_target >= 0)
1924 manager_override_log_target(m, saved_log_target);
1925
1926 if (manager_reload(m) < 0)
1927 /* Reloading failed before the point of no return.
1928 * Let's continue running as if nothing happened. */
1929 m->objective = MANAGER_OK;
1930
1931 continue;
1932 }
1933
1934 case MANAGER_REEXECUTE:
1935 r = prepare_reexecute(m, &arg_serialization, ret_fds, false);
1936 if (r < 0) {
1937 *ret_error_message = "Failed to prepare for reexecution";
1938 return r;
1939 }
1940
1941 log_notice("Reexecuting.");
1942
1943 *ret_retval = EXIT_SUCCESS;
1944 *ret_shutdown_verb = NULL;
1945 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1946
1947 return objective;
1948
1949 case MANAGER_SWITCH_ROOT:
1950 if (!m->switch_root_init) {
1951 r = prepare_reexecute(m, &arg_serialization, ret_fds, true);
1952 if (r < 0) {
1953 *ret_error_message = "Failed to prepare for reexecution";
1954 return r;
1955 }
1956 } else
1957 *ret_fds = NULL;
1958
1959 log_notice("Switching root.");
1960
1961 *ret_retval = EXIT_SUCCESS;
1962 *ret_shutdown_verb = NULL;
1963
1964 /* Steal the switch root parameters */
1965 *ret_switch_root_dir = TAKE_PTR(m->switch_root);
1966 *ret_switch_root_init = TAKE_PTR(m->switch_root_init);
1967
1968 return objective;
1969
1970 case MANAGER_EXIT:
1971 if (MANAGER_IS_USER(m)) {
1972 log_debug("Exit.");
1973
1974 *ret_retval = m->return_value;
1975 *ret_shutdown_verb = NULL;
1976 *ret_fds = NULL;
1977 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1978
1979 return objective;
1980 }
1981
1982 _fallthrough_;
1983 case MANAGER_REBOOT:
1984 case MANAGER_POWEROFF:
1985 case MANAGER_HALT:
1986 case MANAGER_KEXEC: {
1987 static const char* const table[_MANAGER_OBJECTIVE_MAX] = {
1988 [MANAGER_EXIT] = "exit",
1989 [MANAGER_REBOOT] = "reboot",
1990 [MANAGER_POWEROFF] = "poweroff",
1991 [MANAGER_HALT] = "halt",
1992 [MANAGER_KEXEC] = "kexec",
1993 };
1994
1995 log_notice("Shutting down.");
1996
1997 *ret_retval = m->return_value;
1998 assert_se(*ret_shutdown_verb = table[m->objective]);
1999 *ret_fds = NULL;
2000 *ret_switch_root_dir = *ret_switch_root_init = NULL;
2001
2002 return objective;
2003 }
2004
2005 default:
2006 assert_not_reached();
2007 }
2008 }
2009 }
2010
2011 static void log_execution_mode(bool *ret_first_boot) {
2012 assert(ret_first_boot);
2013
2014 if (arg_system) {
2015 struct utsname uts;
2016 int v;
2017
2018 log_info("systemd " GIT_VERSION " running in %ssystem mode (%s)",
2019 arg_action == ACTION_TEST ? "test " : "",
2020 systemd_features);
2021
2022 v = detect_virtualization();
2023 if (v > 0)
2024 log_info("Detected virtualization %s.", virtualization_to_string(v));
2025
2026 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2027
2028 if (in_initrd()) {
2029 *ret_first_boot = false;
2030 log_info("Running in initial RAM disk.");
2031 } else {
2032 int r;
2033 _cleanup_free_ char *id_text = NULL;
2034
2035 /* Let's check whether we are in first boot. We use /etc/machine-id as flag file
2036 * for this: If it is missing or contains the value "uninitialized", this is the
2037 * first boot. In any other case, it is not. This allows container managers and
2038 * installers to provision a couple of files already. If the container manager
2039 * wants to provision the machine ID itself it should pass $container_uuid to PID 1. */
2040
2041 r = read_one_line_file("/etc/machine-id", &id_text);
2042 if (r < 0 || streq(id_text, "uninitialized")) {
2043 if (r < 0 && r != -ENOENT)
2044 log_warning_errno(r, "Unexpected error while reading /etc/machine-id, ignoring: %m");
2045
2046 *ret_first_boot = true;
2047 log_info("Detected first boot.");
2048 } else {
2049 *ret_first_boot = false;
2050 log_debug("Detected initialized system, this is not the first boot.");
2051 }
2052 }
2053
2054 assert_se(uname(&uts) >= 0);
2055
2056 if (strverscmp_improved(uts.release, KERNEL_BASELINE_VERSION) < 0)
2057 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2058 "Your mileage may vary.", uts.release, KERNEL_BASELINE_VERSION);
2059 else
2060 log_debug("Kernel version %s, our baseline is %s", uts.release, KERNEL_BASELINE_VERSION);
2061 } else {
2062 if (DEBUG_LOGGING) {
2063 _cleanup_free_ char *t = NULL;
2064
2065 t = uid_to_name(getuid());
2066 log_debug("systemd " GIT_VERSION " running in %suser mode for user " UID_FMT "/%s. (%s)",
2067 arg_action == ACTION_TEST ? " test" : "",
2068 getuid(), strna(t), systemd_features);
2069 }
2070
2071 *ret_first_boot = false;
2072 }
2073 }
2074
2075 static int initialize_runtime(
2076 bool skip_setup,
2077 bool first_boot,
2078 struct rlimit *saved_rlimit_nofile,
2079 struct rlimit *saved_rlimit_memlock,
2080 const char **ret_error_message) {
2081 int r;
2082
2083 assert(ret_error_message);
2084
2085 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2086 *
2087 * - Some only apply to --system instances
2088 * - Some only apply to --user instances
2089 * - Some only apply when we first start up, but not when we reexecute
2090 */
2091
2092 if (arg_action != ACTION_RUN)
2093 return 0;
2094
2095 update_cpu_affinity(skip_setup);
2096 update_numa_policy(skip_setup);
2097
2098 if (arg_system) {
2099 /* Make sure we leave a core dump without panicking the kernel. */
2100 install_crash_handler();
2101
2102 if (!skip_setup) {
2103 r = mount_cgroup_controllers();
2104 if (r < 0) {
2105 *ret_error_message = "Failed to mount cgroup hierarchies";
2106 return r;
2107 }
2108
2109 status_welcome();
2110 (void) hostname_setup(true);
2111 /* Force transient machine-id on first boot. */
2112 machine_id_setup(NULL, first_boot, arg_machine_id, NULL);
2113 (void) loopback_setup();
2114 bump_unix_max_dgram_qlen();
2115 bump_file_max_and_nr_open();
2116 test_usr();
2117 write_container_id();
2118 }
2119
2120 if (arg_watchdog_device) {
2121 r = watchdog_set_device(arg_watchdog_device);
2122 if (r < 0)
2123 log_warning_errno(r, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device);
2124 }
2125 } else {
2126 _cleanup_free_ char *p = NULL;
2127
2128 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2129 * user mode. In system mode mount_setup() already did that. */
2130
2131 r = xdg_user_runtime_dir(&p, "/systemd");
2132 if (r < 0) {
2133 *ret_error_message = "$XDG_RUNTIME_DIR is not set";
2134 return log_emergency_errno(r, "Failed to determine $XDG_RUNTIME_DIR path: %m");
2135 }
2136
2137 (void) mkdir_p_label(p, 0755);
2138 (void) make_inaccessible_nodes(p, UID_INVALID, GID_INVALID);
2139 }
2140
2141 if (arg_timer_slack_nsec != NSEC_INFINITY)
2142 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
2143 log_warning_errno(errno, "Failed to adjust timer slack, ignoring: %m");
2144
2145 if (arg_system && !cap_test_all(arg_capability_bounding_set)) {
2146 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
2147 if (r < 0) {
2148 *ret_error_message = "Failed to drop capability bounding set of usermode helpers";
2149 return log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
2150 }
2151
2152 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
2153 if (r < 0) {
2154 *ret_error_message = "Failed to drop capability bounding set";
2155 return log_emergency_errno(r, "Failed to drop capability bounding set: %m");
2156 }
2157 }
2158
2159 if (arg_system && arg_no_new_privs) {
2160 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
2161 *ret_error_message = "Failed to disable new privileges";
2162 return log_emergency_errno(errno, "Failed to disable new privileges: %m");
2163 }
2164 }
2165
2166 if (arg_syscall_archs) {
2167 r = enforce_syscall_archs(arg_syscall_archs);
2168 if (r < 0) {
2169 *ret_error_message = "Failed to set syscall architectures";
2170 return r;
2171 }
2172 }
2173
2174 if (!arg_system)
2175 /* Become reaper of our children */
2176 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
2177 log_warning_errno(errno, "Failed to make us a subreaper, ignoring: %m");
2178
2179 /* Bump up RLIMIT_NOFILE for systemd itself */
2180 (void) bump_rlimit_nofile(saved_rlimit_nofile);
2181 (void) bump_rlimit_memlock(saved_rlimit_memlock);
2182
2183 return 0;
2184 }
2185
2186 static int do_queue_default_job(
2187 Manager *m,
2188 const char **ret_error_message) {
2189
2190 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2191 const char *unit;
2192 Job *job;
2193 Unit *target;
2194 int r;
2195
2196 if (arg_default_unit)
2197 unit = arg_default_unit;
2198 else if (in_initrd())
2199 unit = SPECIAL_INITRD_TARGET;
2200 else
2201 unit = SPECIAL_DEFAULT_TARGET;
2202
2203 log_debug("Activating default unit: %s", unit);
2204
2205 r = manager_load_startable_unit_or_warn(m, unit, NULL, &target);
2206 if (r < 0 && in_initrd() && !arg_default_unit) {
2207 /* Fall back to default.target, which we used to always use by default. Only do this if no
2208 * explicit configuration was given. */
2209
2210 log_info("Falling back to " SPECIAL_DEFAULT_TARGET ".");
2211
2212 r = manager_load_startable_unit_or_warn(m, SPECIAL_DEFAULT_TARGET, NULL, &target);
2213 }
2214 if (r < 0) {
2215 log_info("Falling back to " SPECIAL_RESCUE_TARGET ".");
2216
2217 r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, NULL, &target);
2218 if (r < 0) {
2219 *ret_error_message = r == -ERFKILL ? SPECIAL_RESCUE_TARGET " masked"
2220 : "Failed to load " SPECIAL_RESCUE_TARGET;
2221 return r;
2222 }
2223 }
2224
2225 assert(target->load_state == UNIT_LOADED);
2226
2227 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, NULL, &error, &job);
2228 if (r == -EPERM) {
2229 log_debug_errno(r, "Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
2230
2231 sd_bus_error_free(&error);
2232
2233 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, NULL, &error, &job);
2234 if (r < 0) {
2235 *ret_error_message = "Failed to start default target";
2236 return log_emergency_errno(r, "Failed to start default target: %s", bus_error_message(&error, r));
2237 }
2238
2239 } else if (r < 0) {
2240 *ret_error_message = "Failed to isolate default target";
2241 return log_emergency_errno(r, "Failed to isolate default target: %s", bus_error_message(&error, r));
2242 } else
2243 log_info("Queued %s job for default target %s.",
2244 job_type_to_string(job->type),
2245 unit_status_string(job->unit, NULL));
2246
2247 m->default_unit_job_id = job->id;
2248
2249 return 0;
2250 }
2251
2252 static void save_rlimits(struct rlimit *saved_rlimit_nofile,
2253 struct rlimit *saved_rlimit_memlock) {
2254
2255 assert(saved_rlimit_nofile);
2256 assert(saved_rlimit_memlock);
2257
2258 if (getrlimit(RLIMIT_NOFILE, saved_rlimit_nofile) < 0)
2259 log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2260
2261 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock) < 0)
2262 log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2263 }
2264
2265 static void fallback_rlimit_nofile(const struct rlimit *saved_rlimit_nofile) {
2266 struct rlimit *rl;
2267
2268 if (arg_default_rlimit[RLIMIT_NOFILE])
2269 return;
2270
2271 /* Make sure forked processes get limits based on the original kernel setting */
2272
2273 rl = newdup(struct rlimit, saved_rlimit_nofile, 1);
2274 if (!rl) {
2275 log_oom();
2276 return;
2277 }
2278
2279 /* Bump the hard limit for system services to a substantially higher value. The default
2280 * hard limit current kernels set is pretty low (4K), mostly for historical
2281 * reasons. According to kernel developers, the fd handling in recent kernels has been
2282 * optimized substantially enough, so that we can bump the limit now, without paying too
2283 * high a price in memory or performance. Note however that we only bump the hard limit,
2284 * not the soft limit. That's because select() works the way it works, and chokes on fds
2285 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2286 * unexpecting programs that they get fds higher than what they can process using
2287 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2288 * this pitfall: programs that are written by folks aware of the select() problem in mind
2289 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2290 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2291 * we pass. */
2292 if (arg_system) {
2293 int nr;
2294
2295 /* Get the underlying absolute limit the kernel enforces */
2296 nr = read_nr_open();
2297
2298 rl->rlim_max = MIN((rlim_t) nr, MAX(rl->rlim_max, (rlim_t) HIGH_RLIMIT_NOFILE));
2299 }
2300
2301 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2302 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2303 * instance), then lower what we pass on to not confuse our children */
2304 rl->rlim_cur = MIN(rl->rlim_cur, (rlim_t) FD_SETSIZE);
2305
2306 arg_default_rlimit[RLIMIT_NOFILE] = rl;
2307 }
2308
2309 static void fallback_rlimit_memlock(const struct rlimit *saved_rlimit_memlock) {
2310 struct rlimit *rl;
2311
2312 /* Pass the original value down to invoked processes */
2313
2314 if (arg_default_rlimit[RLIMIT_MEMLOCK])
2315 return;
2316
2317 rl = newdup(struct rlimit, saved_rlimit_memlock, 1);
2318 if (!rl) {
2319 log_oom();
2320 return;
2321 }
2322
2323 if (arg_system) {
2324 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2325 * default for this since kernel 5.16) */
2326 rl->rlim_max = MAX(rl->rlim_max, (rlim_t) DEFAULT_RLIMIT_MEMLOCK);
2327 rl->rlim_cur = MAX(rl->rlim_cur, (rlim_t) DEFAULT_RLIMIT_MEMLOCK);
2328 }
2329
2330 arg_default_rlimit[RLIMIT_MEMLOCK] = rl;
2331 }
2332
2333 static void setenv_manager_environment(void) {
2334 int r;
2335
2336 STRV_FOREACH(p, arg_manager_environment) {
2337 log_debug("Setting '%s' in our own environment.", *p);
2338
2339 r = putenv_dup(*p, true);
2340 if (r < 0)
2341 log_warning_errno(errno, "Failed to setenv \"%s\", ignoring: %m", *p);
2342 }
2343 }
2344
2345 static void reset_arguments(void) {
2346 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2347
2348 arg_default_unit = mfree(arg_default_unit);
2349
2350 /* arg_system — ignore */
2351
2352 arg_dump_core = true;
2353 arg_crash_chvt = -1;
2354 arg_crash_shell = false;
2355 arg_crash_reboot = false;
2356 arg_confirm_spawn = mfree(arg_confirm_spawn);
2357 arg_show_status = _SHOW_STATUS_INVALID;
2358 arg_status_unit_format = STATUS_UNIT_FORMAT_DEFAULT;
2359 arg_switched_root = false;
2360 arg_pager_flags = 0;
2361 arg_service_watchdogs = true;
2362 arg_default_std_output = EXEC_OUTPUT_JOURNAL;
2363 arg_default_std_error = EXEC_OUTPUT_INHERIT;
2364 arg_default_restart_usec = DEFAULT_RESTART_USEC;
2365 arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
2366 arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
2367 arg_default_timeout_abort_usec = DEFAULT_TIMEOUT_USEC;
2368 arg_default_timeout_abort_set = false;
2369 arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
2370 arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
2371 arg_runtime_watchdog = 0;
2372 arg_reboot_watchdog = 10 * USEC_PER_MINUTE;
2373 arg_kexec_watchdog = 0;
2374 arg_pretimeout_watchdog = 0;
2375 arg_early_core_pattern = NULL;
2376 arg_watchdog_device = NULL;
2377 arg_watchdog_pretimeout_governor = mfree(arg_watchdog_pretimeout_governor);
2378
2379 arg_default_environment = strv_free(arg_default_environment);
2380 arg_manager_environment = strv_free(arg_manager_environment);
2381 rlimit_free_all(arg_default_rlimit);
2382
2383 arg_capability_bounding_set = CAP_ALL;
2384 arg_no_new_privs = false;
2385 arg_timer_slack_nsec = NSEC_INFINITY;
2386 arg_default_timer_accuracy_usec = 1 * USEC_PER_MINUTE;
2387
2388 arg_syscall_archs = set_free(arg_syscall_archs);
2389
2390 /* arg_serialization — ignore */
2391
2392 arg_default_cpu_accounting = -1;
2393 arg_default_io_accounting = false;
2394 arg_default_ip_accounting = false;
2395 arg_default_blockio_accounting = false;
2396 arg_default_memory_accounting = MEMORY_ACCOUNTING_DEFAULT;
2397 arg_default_tasks_accounting = true;
2398 arg_default_tasks_max = DEFAULT_TASKS_MAX;
2399 arg_machine_id = (sd_id128_t) {};
2400 arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
2401 arg_default_oom_policy = OOM_STOP;
2402
2403 cpu_set_reset(&arg_cpu_affinity);
2404 numa_policy_reset(&arg_numa_policy);
2405
2406 arg_random_seed = mfree(arg_random_seed);
2407 arg_random_seed_size = 0;
2408 arg_clock_usec = 0;
2409
2410 arg_default_oom_score_adjust_set = false;
2411 }
2412
2413 static void determine_default_oom_score_adjust(void) {
2414 int r, a, b;
2415
2416 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2417 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2418 * user). */
2419
2420 if (arg_default_oom_score_adjust_set)
2421 return;
2422
2423 if (getuid() == 0)
2424 return;
2425
2426 r = get_oom_score_adjust(&a);
2427 if (r < 0)
2428 return (void) log_warning_errno(r, "Failed to determine current OOM score adjustment value, ignoring: %m");
2429
2430 assert_cc(100 <= OOM_SCORE_ADJ_MAX);
2431 b = a >= OOM_SCORE_ADJ_MAX - 100 ? OOM_SCORE_ADJ_MAX : a + 100;
2432
2433 if (a == b)
2434 return;
2435
2436 arg_default_oom_score_adjust = b;
2437 arg_default_oom_score_adjust_set = true;
2438 }
2439
2440 static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
2441 const struct rlimit *saved_rlimit_memlock) {
2442 int r;
2443
2444 assert(saved_rlimit_nofile);
2445 assert(saved_rlimit_memlock);
2446
2447 /* Assign configuration defaults */
2448 reset_arguments();
2449
2450 r = parse_config_file();
2451 if (r < 0)
2452 log_warning_errno(r, "Failed to parse config file, ignoring: %m");
2453
2454 if (arg_system) {
2455 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
2456 if (r < 0)
2457 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
2458 }
2459
2460 /* Initialize some default rlimits for services if they haven't been configured */
2461 fallback_rlimit_nofile(saved_rlimit_nofile);
2462 fallback_rlimit_memlock(saved_rlimit_memlock);
2463
2464 /* Note that this also parses bits from the kernel command line, including "debug". */
2465 log_parse_environment();
2466
2467 /* Initialize the show status setting if it hasn't been set explicitly yet */
2468 if (arg_show_status == _SHOW_STATUS_INVALID)
2469 arg_show_status = SHOW_STATUS_YES;
2470
2471 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2472 determine_default_oom_score_adjust();
2473
2474 /* Push variables into the manager environment block */
2475 setenv_manager_environment();
2476
2477 /* Parse log environment variables again to take into account any new environment variables. */
2478 log_parse_environment();
2479
2480 return 0;
2481 }
2482
2483 static int safety_checks(void) {
2484
2485 if (getpid_cached() == 1 &&
2486 arg_action != ACTION_RUN)
2487 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2488 "Unsupported execution mode while PID 1.");
2489
2490 if (getpid_cached() == 1 &&
2491 !arg_system)
2492 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2493 "Can't run --user mode as PID 1.");
2494
2495 if (arg_action == ACTION_RUN &&
2496 arg_system &&
2497 getpid_cached() != 1)
2498 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2499 "Can't run system mode unless PID 1.");
2500
2501 if (arg_action == ACTION_TEST &&
2502 geteuid() == 0)
2503 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2504 "Don't run test mode as root.");
2505
2506 if (!arg_system &&
2507 arg_action == ACTION_RUN &&
2508 sd_booted() <= 0)
2509 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2510 "Trying to run as user instance, but the system has not been booted with systemd.");
2511
2512 if (!arg_system &&
2513 arg_action == ACTION_RUN &&
2514 !getenv("XDG_RUNTIME_DIR"))
2515 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH),
2516 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2517
2518 if (arg_system &&
2519 arg_action == ACTION_RUN &&
2520 running_in_chroot() > 0)
2521 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2522 "Cannot be run in a chroot() environment.");
2523
2524 return 0;
2525 }
2526
2527 static int initialize_security(
2528 bool *loaded_policy,
2529 dual_timestamp *security_start_timestamp,
2530 dual_timestamp *security_finish_timestamp,
2531 const char **ret_error_message) {
2532
2533 int r;
2534
2535 assert(loaded_policy);
2536 assert(security_start_timestamp);
2537 assert(security_finish_timestamp);
2538 assert(ret_error_message);
2539
2540 dual_timestamp_get(security_start_timestamp);
2541
2542 r = mac_selinux_setup(loaded_policy);
2543 if (r < 0) {
2544 *ret_error_message = "Failed to load SELinux policy";
2545 return r;
2546 }
2547
2548 r = mac_smack_setup(loaded_policy);
2549 if (r < 0) {
2550 *ret_error_message = "Failed to load SMACK policy";
2551 return r;
2552 }
2553
2554 r = mac_apparmor_setup();
2555 if (r < 0) {
2556 *ret_error_message = "Failed to load AppArmor policy";
2557 return r;
2558 }
2559
2560 r = ima_setup();
2561 if (r < 0) {
2562 *ret_error_message = "Failed to load IMA policy";
2563 return r;
2564 }
2565
2566 dual_timestamp_get(security_finish_timestamp);
2567 return 0;
2568 }
2569
2570 static int collect_fds(FDSet **ret_fds, const char **ret_error_message) {
2571 int r;
2572
2573 assert(ret_fds);
2574 assert(ret_error_message);
2575
2576 r = fdset_new_fill(ret_fds);
2577 if (r < 0) {
2578 *ret_error_message = "Failed to allocate fd set";
2579 return log_emergency_errno(r, "Failed to allocate fd set: %m");
2580 }
2581
2582 fdset_cloexec(*ret_fds, true);
2583
2584 if (arg_serialization)
2585 assert_se(fdset_remove(*ret_fds, fileno(arg_serialization)) >= 0);
2586
2587 return 0;
2588 }
2589
2590 static void setup_console_terminal(bool skip_setup) {
2591
2592 if (!arg_system)
2593 return;
2594
2595 /* Become a session leader if we aren't one yet. */
2596 (void) setsid();
2597
2598 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2599 * controlling tty. */
2600 (void) release_terminal();
2601
2602 /* Reset the console, but only if this is really init and we are freshly booted */
2603 if (getpid_cached() == 1 && !skip_setup)
2604 (void) console_setup();
2605 }
2606
2607 static bool early_skip_setup_check(int argc, char *argv[]) {
2608 bool found_deserialize = false;
2609
2610 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2611 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2612 * special setup things anyway, even if in that case we also do deserialization. */
2613
2614 for (int i = 1; i < argc; i++)
2615 if (streq(argv[i], "--switched-root"))
2616 return false; /* If we switched root, don't skip the setup. */
2617 else if (streq(argv[i], "--deserialize"))
2618 found_deserialize = true;
2619
2620 return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2621 }
2622
2623 static int save_env(void) {
2624 char **l;
2625
2626 l = strv_copy(environ);
2627 if (!l)
2628 return -ENOMEM;
2629
2630 strv_free_and_replace(saved_env, l);
2631 return 0;
2632 }
2633
2634 int main(int argc, char *argv[]) {
2635 dual_timestamp
2636 initrd_timestamp = DUAL_TIMESTAMP_NULL,
2637 userspace_timestamp = DUAL_TIMESTAMP_NULL,
2638 kernel_timestamp = DUAL_TIMESTAMP_NULL,
2639 security_start_timestamp = DUAL_TIMESTAMP_NULL,
2640 security_finish_timestamp = DUAL_TIMESTAMP_NULL;
2641 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0),
2642 saved_rlimit_memlock = RLIMIT_MAKE_CONST(RLIM_INFINITY); /* The original rlimits we passed
2643 * in. Note we use different values
2644 * for the two that indicate whether
2645 * these fields are initialized! */
2646 bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false;
2647 char *switch_root_dir = NULL, *switch_root_init = NULL;
2648 usec_t before_startup, after_startup;
2649 static char systemd[] = "systemd";
2650 const char *shutdown_verb = NULL, *error_message = NULL;
2651 int r, retval = EXIT_FAILURE;
2652 Manager *m = NULL;
2653 FDSet *fds = NULL;
2654
2655 assert_se(argc > 0 && !isempty(argv[0]));
2656
2657 /* SysV compatibility: redirect init → telinit */
2658 redirect_telinit(argc, argv);
2659
2660 /* Take timestamps early on */
2661 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
2662 dual_timestamp_get(&userspace_timestamp);
2663
2664 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2665 * reexecuting. */
2666 skip_setup = early_skip_setup_check(argc, argv);
2667
2668 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2669 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2670 * right-away. */
2671 program_invocation_short_name = systemd;
2672 (void) prctl(PR_SET_NAME, systemd);
2673
2674 /* Save the original command line */
2675 save_argc_argv(argc, argv);
2676
2677 /* Save the original environment as we might need to restore it if we're requested to execute another
2678 * system manager later. */
2679 r = save_env();
2680 if (r < 0) {
2681 error_message = "Failed to copy environment block";
2682 goto finish;
2683 }
2684
2685 /* Make sure that if the user says "syslog" we actually log to the journal. */
2686 log_set_upgrade_syslog_to_journal(true);
2687
2688 if (getpid_cached() == 1) {
2689 /* When we run as PID 1 force system mode */
2690 arg_system = true;
2691
2692 /* Disable the umask logic */
2693 umask(0);
2694
2695 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2696 * not be activated yet (even though the log socket for it exists). */
2697 log_set_prohibit_ipc(true);
2698
2699 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
2700 * is important so that we never end up logging to any foreign stderr, for example if we have
2701 * to log in a child process right before execve()'ing the actual binary, at a point in time
2702 * where socket activation stderr/stdout area already set up. */
2703 log_set_always_reopen_console(true);
2704
2705 if (detect_container() <= 0) {
2706
2707 /* Running outside of a container as PID 1 */
2708 log_set_target(LOG_TARGET_KMSG);
2709 log_open();
2710
2711 if (in_initrd())
2712 initrd_timestamp = userspace_timestamp;
2713
2714 if (!skip_setup) {
2715 r = mount_setup_early();
2716 if (r < 0) {
2717 error_message = "Failed to mount early API filesystems";
2718 goto finish;
2719 }
2720
2721 /* Let's open the log backend a second time, in case the first time didn't
2722 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2723 * available, and it previously wasn't. */
2724 log_open();
2725
2726 disable_printk_ratelimit();
2727
2728 r = initialize_security(
2729 &loaded_policy,
2730 &security_start_timestamp,
2731 &security_finish_timestamp,
2732 &error_message);
2733 if (r < 0)
2734 goto finish;
2735 }
2736
2737 if (mac_selinux_init() < 0) {
2738 error_message = "Failed to initialize SELinux support";
2739 goto finish;
2740 }
2741
2742 if (!skip_setup)
2743 initialize_clock();
2744
2745 /* Set the default for later on, but don't actually open the logs like this for
2746 * now. Note that if we are transitioning from the initrd there might still be
2747 * journal fd open, and we shouldn't attempt opening that before we parsed
2748 * /proc/cmdline which might redirect output elsewhere. */
2749 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2750
2751 } else {
2752 /* Running inside a container, as PID 1 */
2753 log_set_target(LOG_TARGET_CONSOLE);
2754 log_open();
2755
2756 /* For later on, see above... */
2757 log_set_target(LOG_TARGET_JOURNAL);
2758
2759 /* clear the kernel timestamp, because we are in a container */
2760 kernel_timestamp = DUAL_TIMESTAMP_NULL;
2761 }
2762
2763 initialize_coredump(skip_setup);
2764
2765 r = fixup_environment();
2766 if (r < 0) {
2767 log_emergency_errno(r, "Failed to fix up PID 1 environment: %m");
2768 error_message = "Failed to fix up PID1 environment";
2769 goto finish;
2770 }
2771
2772 /* Try to figure out if we can use colors with the console. No need to do that for user
2773 * instances since they never log into the console. */
2774 log_show_color(colors_enabled());
2775
2776 r = make_null_stdio();
2777 if (r < 0)
2778 log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2779
2780 /* Load the kernel modules early. */
2781 if (!skip_setup)
2782 kmod_setup();
2783
2784 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
2785 r = mount_setup(loaded_policy, skip_setup);
2786 if (r < 0) {
2787 error_message = "Failed to mount API filesystems";
2788 goto finish;
2789 }
2790
2791 /* The efivarfs is now mounted, let's read the random seed off it */
2792 (void) efi_take_random_seed();
2793
2794 /* Cache command-line options passed from EFI variables */
2795 if (!skip_setup)
2796 (void) cache_efi_options_variable();
2797 } else {
2798 /* Running as user instance */
2799 arg_system = false;
2800 log_set_target(LOG_TARGET_AUTO);
2801 log_open();
2802
2803 /* clear the kernel timestamp, because we are not PID 1 */
2804 kernel_timestamp = DUAL_TIMESTAMP_NULL;
2805
2806 if (mac_selinux_init() < 0) {
2807 error_message = "Failed to initialize SELinux support";
2808 goto finish;
2809 }
2810 }
2811
2812 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2813 * transitioning from the initrd to the main systemd or suchlike. */
2814 save_rlimits(&saved_rlimit_nofile, &saved_rlimit_memlock);
2815
2816 /* Reset all signal handlers. */
2817 (void) reset_all_signal_handlers();
2818 (void) ignore_signals(SIGNALS_IGNORE);
2819
2820 (void) parse_configuration(&saved_rlimit_nofile, &saved_rlimit_memlock);
2821
2822 r = parse_argv(argc, argv);
2823 if (r < 0) {
2824 error_message = "Failed to parse commandline arguments";
2825 goto finish;
2826 }
2827
2828 r = safety_checks();
2829 if (r < 0)
2830 goto finish;
2831
2832 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES, ACTION_BUS_INTROSPECT))
2833 pager_open(arg_pager_flags);
2834
2835 if (arg_action != ACTION_RUN)
2836 skip_setup = true;
2837
2838 if (arg_action == ACTION_HELP) {
2839 retval = help() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
2840 goto finish;
2841 } else if (arg_action == ACTION_VERSION) {
2842 retval = version();
2843 goto finish;
2844 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
2845 unit_dump_config_items(stdout);
2846 retval = EXIT_SUCCESS;
2847 goto finish;
2848 } else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
2849 dump_bus_properties(stdout);
2850 retval = EXIT_SUCCESS;
2851 goto finish;
2852 } else if (arg_action == ACTION_BUS_INTROSPECT) {
2853 r = bus_manager_introspect_implementations(stdout, arg_bus_introspect);
2854 retval = r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
2855 goto finish;
2856 }
2857
2858 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
2859
2860 /* Move out of the way, so that we won't block unmounts */
2861 assert_se(chdir("/") == 0);
2862
2863 if (arg_action == ACTION_RUN) {
2864 if (!skip_setup) {
2865 /* Apply the systemd.clock_usec= kernel command line switch */
2866 apply_clock_update();
2867
2868 /* Apply random seed from kernel command line */
2869 cmdline_take_random_seed();
2870 }
2871
2872 /* A core pattern might have been specified via the cmdline. */
2873 initialize_core_pattern(skip_setup);
2874
2875 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
2876 log_close();
2877
2878 /* Remember open file descriptors for later deserialization */
2879 r = collect_fds(&fds, &error_message);
2880 if (r < 0)
2881 goto finish;
2882
2883 /* Give up any control of the console, but make sure its initialized. */
2884 setup_console_terminal(skip_setup);
2885
2886 /* Open the logging devices, if possible and necessary */
2887 log_open();
2888 }
2889
2890 log_execution_mode(&first_boot);
2891
2892 r = initialize_runtime(skip_setup,
2893 first_boot,
2894 &saved_rlimit_nofile,
2895 &saved_rlimit_memlock,
2896 &error_message);
2897 if (r < 0)
2898 goto finish;
2899
2900 r = manager_new(arg_system ? LOOKUP_SCOPE_SYSTEM : LOOKUP_SCOPE_USER,
2901 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
2902 &m);
2903 if (r < 0) {
2904 log_emergency_errno(r, "Failed to allocate manager object: %m");
2905 error_message = "Failed to allocate manager object";
2906 goto finish;
2907 }
2908
2909 m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
2910 m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
2911 m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
2912 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START)] = security_start_timestamp;
2913 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH)] = security_finish_timestamp;
2914
2915 set_manager_defaults(m);
2916 set_manager_settings(m);
2917 manager_set_first_boot(m, first_boot);
2918
2919 /* Remember whether we should queue the default job */
2920 queue_default_job = !arg_serialization || arg_switched_root;
2921
2922 before_startup = now(CLOCK_MONOTONIC);
2923
2924 r = manager_startup(m, arg_serialization, fds, /* root= */ NULL);
2925 if (r < 0) {
2926 error_message = "Failed to start up manager";
2927 goto finish;
2928 }
2929
2930 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2931 fds = fdset_free(fds);
2932 arg_serialization = safe_fclose(arg_serialization);
2933
2934 if (queue_default_job) {
2935 r = do_queue_default_job(m, &error_message);
2936 if (r < 0)
2937 goto finish;
2938 }
2939
2940 after_startup = now(CLOCK_MONOTONIC);
2941
2942 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
2943 "Loaded units and determined initial transaction in %s.",
2944 FORMAT_TIMESPAN(after_startup - before_startup, 100 * USEC_PER_MSEC));
2945
2946 if (arg_action == ACTION_TEST) {
2947 manager_test_summary(m);
2948 retval = EXIT_SUCCESS;
2949 goto finish;
2950 }
2951
2952 r = invoke_main_loop(m,
2953 &saved_rlimit_nofile,
2954 &saved_rlimit_memlock,
2955 &retval,
2956 &shutdown_verb,
2957 &fds,
2958 &switch_root_dir,
2959 &switch_root_init,
2960 &error_message);
2961 assert(r < 0 || IN_SET(r, MANAGER_EXIT, /* MANAGER_OK is not expected here. */
2962 MANAGER_RELOAD,
2963 MANAGER_REEXECUTE,
2964 MANAGER_REBOOT,
2965 MANAGER_POWEROFF,
2966 MANAGER_HALT,
2967 MANAGER_KEXEC,
2968 MANAGER_SWITCH_ROOT));
2969
2970 finish:
2971 pager_close();
2972
2973 if (m) {
2974 arg_reboot_watchdog = manager_get_watchdog(m, WATCHDOG_REBOOT);
2975 arg_kexec_watchdog = manager_get_watchdog(m, WATCHDOG_KEXEC);
2976 m = manager_free(m);
2977 }
2978
2979 mac_selinux_finish();
2980
2981 if (IN_SET(r, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT))
2982 r = do_reexecute(r,
2983 argc, argv,
2984 &saved_rlimit_nofile,
2985 &saved_rlimit_memlock,
2986 fds,
2987 switch_root_dir,
2988 switch_root_init,
2989 &error_message); /* This only returns if reexecution failed */
2990
2991 arg_serialization = safe_fclose(arg_serialization);
2992 fds = fdset_free(fds);
2993
2994 saved_env = strv_free(saved_env);
2995
2996 #if HAVE_VALGRIND_VALGRIND_H
2997 /* If we are PID 1 and running under valgrind, then let's exit
2998 * here explicitly. valgrind will only generate nice output on
2999 * exit(), not on exec(), hence let's do the former not the
3000 * latter here. */
3001 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
3002 /* Cleanup watchdog_device strings for valgrind. We need them
3003 * in become_shutdown() so normally we cannot free them yet. */
3004 watchdog_free_device();
3005 arg_watchdog_device = mfree(arg_watchdog_device);
3006 reset_arguments();
3007 return retval;
3008 }
3009 #endif
3010
3011 #if HAS_FEATURE_ADDRESS_SANITIZER
3012 __lsan_do_leak_check();
3013 #endif
3014
3015 /* Try to invoke the shutdown binary unless we already failed.
3016 * If we failed above, we want to freeze after finishing cleanup. */
3017 if (r >= 0 && shutdown_verb) {
3018 r = become_shutdown(shutdown_verb, retval);
3019 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3020 error_message = "Failed to execute shutdown binary";
3021 }
3022
3023 watchdog_free_device();
3024 arg_watchdog_device = mfree(arg_watchdog_device);
3025
3026 if (getpid_cached() == 1) {
3027 if (error_message)
3028 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
3029 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
3030 "%s.", error_message);
3031 freeze_or_exit_or_reboot();
3032 }
3033
3034 reset_arguments();
3035 return retval;
3036 }