1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 ProFUSION embedded systems
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
23 #include <sys/types.h>
24 #include <sys/reboot.h>
25 #include <linux/reboot.h>
27 #include <sys/types.h>
29 #include <sys/mount.h>
30 #include <sys/syscall.h>
45 #define TIMEOUT_USEC (5 * USEC_PER_SEC)
46 #define FINALIZE_ATTEMPTS 50
48 static bool ignore_proc(pid_t pid) {
52 /* TODO: add more ignore rules here: device-mapper, etc */
57 static bool is_kernel_thread(pid_t pid)
64 snprintf(buf, sizeof(buf), "/proc/%lu/cmdline", (unsigned long)pid);
67 return true; /* not really, but has the desired effect */
69 count = fread(&c, 1, 1, f);
74 static int killall(int sign) {
77 unsigned int n_processes = 0;
79 if ((dir = opendir("/proc")) == NULL)
82 while ((d = readdir(dir))) {
85 if (parse_pid(d->d_name, &pid) < 0)
88 if (is_kernel_thread(pid))
94 if (kill(pid, sign) == 0)
97 log_warning("Could not kill %d: %m", pid);
105 static void wait_for_children(int n_processes, sigset_t *mask) {
110 until = now(CLOCK_MONOTONIC) + TIMEOUT_USEC;
117 pid_t pid = waitpid(-1, NULL, WNOHANG);
122 if (pid < 0 && errno == ECHILD)
126 if (--n_processes == 0)
130 n = now(CLOCK_MONOTONIC);
134 timespec_store(&ts, until - n);
136 if ((k = sigtimedwait(mask, NULL, &ts)) != SIGCHLD) {
138 if (k < 0 && errno != EAGAIN) {
139 log_error("sigtimedwait() failed: %m");
144 log_warning("sigtimedwait() returned unexpected signal.");
149 static void send_signal(int sign) {
150 sigset_t mask, oldmask;
153 assert_se(sigemptyset(&mask) == 0);
154 assert_se(sigaddset(&mask, SIGCHLD) == 0);
155 assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
157 if (kill(-1, SIGSTOP) < 0 && errno != ESRCH)
158 log_warning("kill(-1, SIGSTOP) failed: %m");
160 n_processes = killall(sign);
162 if (kill(-1, SIGCONT) < 0 && errno != ESRCH)
163 log_warning("kill(-1, SIGCONT) failed: %m");
165 if (n_processes <= 0)
168 wait_for_children(n_processes, &mask);
171 sigprocmask(SIG_SETMASK, &oldmask, NULL);
174 static void ultimate_send_signal(int sign) {
175 sigset_t mask, oldmask;
178 assert_se(sigemptyset(&mask) == 0);
179 assert_se(sigaddset(&mask, SIGCHLD) == 0);
180 assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
182 if (kill(-1, SIGSTOP) < 0 && errno != ESRCH)
183 log_warning("kill(-1, SIGSTOP) failed: %m");
186 if (r < 0 && errno != ESRCH)
187 log_warning("kill(-1, %s) failed: %m", signal_to_string(sign));
189 if (kill(-1, SIGCONT) < 0 && errno != ESRCH)
190 log_warning("kill(-1, SIGCONT) failed: %m");
195 wait_for_children(0, &mask);
198 sigprocmask(SIG_SETMASK, &oldmask, NULL);
201 static int prepare_new_root(void) {
202 static const char dirs[] =
203 "/run/initramfs/oldroot\0"
204 "/run/initramfs/proc\0"
205 "/run/initramfs/sys\0"
206 "/run/initramfs/dev\0"
207 "/run/initramfs/run\0";
211 if (mount("/run/initramfs", "/run/initramfs", NULL, MS_BIND, NULL) < 0) {
212 log_error("Failed to mount bind /run/initramfs on /run/initramfs: %m");
216 if (mount(NULL, "/run/initramfs", NULL, MS_PRIVATE, NULL) < 0) {
217 log_error("Failed to make /run/initramfs private mount: %m");
221 NULSTR_FOREACH(dir, dirs)
222 if (mkdir_p(dir, 0755) < 0 && errno != EEXIST) {
223 log_error("Failed to mkdir %s: %m", dir);
227 if (mount("/sys", "/run/initramfs/sys", NULL, MS_BIND, NULL) < 0) {
228 log_error("Failed to mount bind /sys on /run/initramfs/sys: %m");
232 if (mount("/proc", "/run/initramfs/proc", NULL, MS_BIND, NULL) < 0) {
233 log_error("Failed to mount bind /proc on /run/initramfs/proc: %m");
237 if (mount("/dev", "/run/initramfs/dev", NULL, MS_BIND, NULL) < 0) {
238 log_error("Failed to mount bind /dev on /run/initramfs/dev: %m");
242 if (mount("/run", "/run/initramfs/run", NULL, MS_BIND, NULL) < 0) {
243 log_error("Failed to mount bind /run on /run/initramfs/run: %m");
250 static int pivot_to_new_root(void) {
253 chdir("/run/initramfs");
256 In case some evil process made "/" MS_SHARED
257 It works for pivot_root, but the ref count for the root device
258 is not decreasing :-/
260 if (mount(NULL, "/", NULL, MS_PRIVATE, NULL) < 0) {
261 log_error("Failed to make \"/\" private mount %m");
265 if (pivot_root(".", "oldroot") < 0) {
266 log_error("pivot failed: %m");
267 /* only chroot if pivot root succeded */
272 log_info("Successfully changed into root pivot.");
274 fd = open("/dev/console", O_RDWR);
276 log_error("Failed to open /dev/console: %m");
279 /* initialize the controlling terminal */
281 ioctl(0, TIOCSCTTY, NULL);
287 int main(int argc, char *argv[]) {
290 bool need_umount = true, need_swapoff = true, need_loop_detach = true, need_dm_detach = true;
291 bool killed_everbody = false, in_container;
293 log_parse_environment();
294 log_set_target(LOG_TARGET_CONSOLE); /* syslog will die if not gone yet */
298 log_error("Not executed by init (pid 1).");
304 log_error("Invalid number of arguments.");
309 in_container = detect_container(NULL) > 0;
311 if (streq(argv[1], "reboot"))
313 else if (streq(argv[1], "poweroff"))
315 else if (streq(argv[1], "halt"))
316 cmd = RB_HALT_SYSTEM;
317 else if (streq(argv[1], "kexec"))
318 cmd = LINUX_REBOOT_CMD_KEXEC;
320 log_error("Unknown action '%s'.", argv[1]);
325 /* lock us into memory */
326 if (mlockall(MCL_CURRENT|MCL_FUTURE) != 0)
327 log_warning("Cannot lock process memory: %m");
329 log_info("Sending SIGTERM to remaining processes...");
330 send_signal(SIGTERM);
332 log_info("Sending SIGKILL to remaining processes...");
333 send_signal(SIGKILL);
336 need_swapoff = false;
338 /* Unmount all mountpoints, swaps, and loopback devices */
339 for (retries = 0; retries < FINALIZE_ATTEMPTS; retries++) {
340 bool changed = false;
343 log_info("Unmounting file systems.");
344 r = umount_all(&changed);
348 log_info("Not all file systems unmounted, %d left.", r);
350 log_error("Failed to unmount file systems: %s", strerror(-r));
354 log_info("Disabling swaps.");
355 r = swapoff_all(&changed);
357 need_swapoff = false;
359 log_info("Not all swaps are turned off, %d left.", r);
361 log_error("Failed to turn off swaps: %s", strerror(-r));
364 if (need_loop_detach) {
365 log_info("Detaching loop devices.");
366 r = loopback_detach_all(&changed);
368 need_loop_detach = false;
370 log_info("Not all loop devices detached, %d left.", r);
372 log_error("Failed to detach loop devices: %s", strerror(-r));
375 if (need_dm_detach) {
376 log_info("Detaching DM devices.");
377 r = dm_detach_all(&changed);
379 need_dm_detach = false;
381 log_warning("Not all DM devices detached, %d left.", r);
383 log_error("Failed to detach DM devices: %s", strerror(-r));
386 if (!need_umount && !need_swapoff && !need_loop_detach && !need_dm_detach)
390 /* If in this iteration we didn't manage to
391 * unmount/deactivate anything, we either kill more
392 * processes, or simply give up */
395 if (killed_everbody) {
396 /* Hmm, we already killed everybody,
397 * let's just give up */
398 log_error("Cannot finalize remaining file systems and devices, giving up.");
402 log_warning("Cannot finalize remaining file systems and devices, trying to kill remaining processes.");
403 ultimate_send_signal(SIGTERM);
404 ultimate_send_signal(SIGKILL);
405 killed_everbody = true;
408 log_debug("Couldn't finalize remaining file systems and devices after %u retries, trying again.", retries+1);
411 if (retries >= FINALIZE_ATTEMPTS)
412 log_error("Too many iterations, giving up.");
414 execute_directory(SYSTEM_SHUTDOWN_PATH, NULL, NULL);
416 /* If we are in a container, just exit, this will kill our
417 * container for good. */
419 log_error("Exiting container.");
423 if (access("/run/initramfs/shutdown", X_OK) == 0) {
425 if (prepare_new_root() >= 0 &&
426 pivot_to_new_root() >= 0) {
427 execv("/shutdown", argv);
428 log_error("Failed to execute shutdown binary: %m");
434 if (cmd == LINUX_REBOOT_CMD_KEXEC) {
435 /* We cheat and exec kexec to avoid doing all its work */
439 log_error("Could not fork: %m. Falling back to normal reboot.");
441 wait_for_terminate_and_warn("kexec", pid);
442 log_warning("kexec failed. Falling back to normal reboot.");
445 const char *args[3] = { "/sbin/kexec", "-e", NULL };
446 execv(args[0], (char * const *) args);
454 log_error("Failed to invoke reboot(): %m");
458 log_error("Critical error while doing system shutdown: %s", strerror(-r));