2 * Copyright (c) 1986, 1988, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_shutdown.c 8.3 (Berkeley) 1/21/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
42 #include "opt_panic.h"
43 #include "opt_sched.h"
44 #include "opt_watchdog.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
52 #include <sys/eventhandler.h>
55 #include <sys/kernel.h>
56 #include <sys/kerneldump.h>
57 #include <sys/kthread.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
62 #include <sys/reboot.h>
63 #include <sys/resourcevar.h>
64 #include <sys/sched.h>
66 #include <sys/sysctl.h>
67 #include <sys/sysproto.h>
68 #include <sys/vnode.h>
69 #include <sys/watchdog.h>
73 #include <machine/cpu.h>
74 #include <machine/pcb.h>
75 #include <machine/smp.h>
77 #include <security/mac/mac_framework.h>
80 #include <vm/vm_object.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_pager.h>
83 #include <vm/swap_pager.h>
85 #include <sys/signalvar.h>
87 #ifndef PANIC_REBOOT_WAIT_TIME
88 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
92 * Note that stdarg.h and the ANSI style va_start macro is used for both
93 * ANSI and traditional C compilers.
95 #include <machine/stdarg.h>
99 int debugger_on_panic = 0;
101 int debugger_on_panic = 1;
103 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic, CTLFLAG_RW | CTLFLAG_TUN,
104 &debugger_on_panic, 0, "Run debugger on kernel panic");
105 TUNABLE_INT("debug.debugger_on_panic", &debugger_on_panic);
108 static int trace_on_panic = 1;
110 static int trace_on_panic = 0;
112 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic, CTLFLAG_RW | CTLFLAG_TUN,
113 &trace_on_panic, 0, "Print stack trace on kernel panic");
114 TUNABLE_INT("debug.trace_on_panic", &trace_on_panic);
117 static int sync_on_panic = 0;
118 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RW | CTLFLAG_TUN,
119 &sync_on_panic, 0, "Do a sync before rebooting from a panic");
120 TUNABLE_INT("kern.sync_on_panic", &sync_on_panic);
122 static int stop_scheduler_on_panic = 0;
123 SYSCTL_INT(_kern, OID_AUTO, stop_scheduler_on_panic, CTLFLAG_RW | CTLFLAG_TUN,
124 &stop_scheduler_on_panic, 0, "stop scheduler upon entering panic");
125 TUNABLE_INT("kern.stop_scheduler_on_panic", &stop_scheduler_on_panic);
127 SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0, "Shutdown environment");
130 static int show_busybufs;
132 static int show_busybufs = 1;
134 SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
135 &show_busybufs, 0, "");
138 * Variable panicstr contains argument to first call to panic; used as flag
139 * to indicate that the kernel has already called panic.
141 const char *panicstr;
143 int dumping; /* system is dumping */
144 int rebooting; /* system is rebooting */
145 static struct dumperinfo dumper; /* our selected dumper */
147 /* Context information for dump-debuggers. */
148 static struct pcb dumppcb; /* Registers. */
149 lwpid_t dumptid; /* Thread ID. */
151 static void boot(int) __dead2;
152 static void poweroff_wait(void *, int);
153 static void shutdown_halt(void *junk, int howto);
154 static void shutdown_panic(void *junk, int howto);
155 static void shutdown_reset(void *junk, int howto);
157 /* register various local shutdown events */
159 shutdown_conf(void *unused)
162 EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
164 EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
165 SHUTDOWN_PRI_LAST + 100);
166 EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
167 SHUTDOWN_PRI_LAST + 100);
168 EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
169 SHUTDOWN_PRI_LAST + 200);
172 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
175 * The system call that results in a reboot.
179 reboot(struct thread *td, struct reboot_args *uap)
185 error = mac_system_check_reboot(td->td_ucred, uap->opt);
188 error = priv_check(td, PRIV_REBOOT);
198 * Called by events that want to shut down.. e.g <CTL><ALT><DEL> on a PC
200 static int shutdown_howto = 0;
203 shutdown_nice(int howto)
206 shutdown_howto = howto;
208 /* Send a signal to init(8) and have it shutdown the world */
209 if (initproc != NULL) {
211 psignal(initproc, SIGINT);
212 PROC_UNLOCK(initproc);
214 /* No init(8) running, so simply reboot */
219 static int waittime = -1;
230 if (ts.tv_sec >= 86400) {
231 printf("%ldd", (long)ts.tv_sec / 86400);
235 if (f || ts.tv_sec >= 3600) {
236 printf("%ldh", (long)ts.tv_sec / 3600);
240 if (f || ts.tv_sec >= 60) {
241 printf("%ldm", (long)ts.tv_sec / 60);
245 printf("%lds\n", (long)ts.tv_sec);
253 * Sometimes people have to call this from the kernel debugger.
254 * (if 'panic' can not dump)
255 * Give them a clue as to why they can't dump.
257 if (dumper.dumper == NULL) {
258 printf("Cannot dump. Device not defined or unavailable.\n");
263 dumptid = curthread->td_tid;
266 if (textdump_pending)
267 textdump_dumpsys(&dumper);
275 isbufbusy(struct buf *bp)
277 if (((bp->b_flags & (B_INVAL | B_PERSISTENT)) == 0 &&
279 ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
285 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
290 static int first_buf_printf = 1;
294 * Bind us to CPU 0 so that all shutdown code runs there. Some
295 * systems don't shutdown properly (i.e., ACPI power off) if we
296 * run on another processor.
298 if (!SCHEDULER_STOPPED()) {
299 thread_lock(curthread);
300 sched_bind(curthread, 0);
301 thread_unlock(curthread);
302 KASSERT(PCPU_GET(cpuid) == 0, ("boot: not running on cpu 0"));
305 /* We're in the process of rebooting. */
308 /* collect extra flags that shutdown_nice might have set */
309 howto |= shutdown_howto;
311 /* We are out of the debugger now. */
315 * Do any callouts that should be done BEFORE syncing the filesystems.
317 EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
320 * Now sync filesystems
322 if (!cold && (howto & RB_NOSYNC) == 0 && waittime < 0) {
323 register struct buf *bp;
324 int iter, nbusy, pbusy;
331 wdog_kern_pat(WD_LASTVAL);
332 sync(curthread, NULL);
335 * With soft updates, some buffers that are
336 * written will be remarked as dirty until other
337 * buffers are written.
339 for (iter = pbusy = 0; iter < 20; iter++) {
341 for (bp = &buf[nbuf]; --bp >= buf; )
345 if (first_buf_printf)
346 printf("All buffers synced.");
349 if (first_buf_printf) {
350 printf("Syncing disks, buffers remaining... ");
351 first_buf_printf = 0;
353 printf("%d ", nbusy);
358 wdog_kern_pat(WD_LASTVAL);
359 sync(curthread, NULL);
363 * Drop Giant and spin for a while to allow
364 * interrupt threads to run.
371 * Drop Giant and context switch several times to
372 * allow interrupt threads to run.
375 for (subiter = 0; subiter < 50 * iter; subiter++) {
376 thread_lock(curthread);
377 mi_switch(SW_VOL, NULL);
378 thread_unlock(curthread);
386 * Count only busy local buffers to prevent forcing
387 * a fsck if we're just a client of a wedged NFS server
390 for (bp = &buf[nbuf]; --bp >= buf; ) {
393 /* XXX: This is bogus. We should probably have a BO_REMOTE flag instead */
394 if (bp->b_dev == NULL) {
395 TAILQ_REMOVE(&mountlist,
396 bp->b_vp->v_mount, mnt_list);
401 if (show_busybufs > 0) {
403 "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
404 nbusy, bp, bp->b_vp, bp->b_flags,
405 (intmax_t)bp->b_blkno,
406 (intmax_t)bp->b_lblkno);
407 BUF_LOCKPRINTINFO(bp);
408 if (show_busybufs > 1)
416 * Failed to sync all blocks. Indicate this and don't
417 * unmount filesystems (thus forcing an fsck on reboot).
419 printf("Giving up on %d buffers\n", nbusy);
420 DELAY(5000000); /* 5 seconds */
422 if (!first_buf_printf)
423 printf("Final sync complete\n");
425 * Unmount filesystems
431 DELAY(100000); /* wait for console output to finish */
437 * Ok, now do things that assume all filesystem activity has
440 EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
442 if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
445 /* Now that we're going to really halt the system... */
446 EVENTHANDLER_INVOKE(shutdown_final, howto);
448 for(;;) ; /* safety against shutdown_reset not working */
453 * If the shutdown was a clean halt, behave accordingly.
456 shutdown_halt(void *junk, int howto)
459 if (howto & RB_HALT) {
461 printf("The operating system has halted.\n");
462 printf("Please press any key to reboot.\n\n");
464 case -1: /* No console, just die */
475 * Check to see if the system paniced, pause and then reboot
476 * according to the specified delay.
479 shutdown_panic(void *junk, int howto)
483 if (howto & RB_DUMP) {
484 if (PANIC_REBOOT_WAIT_TIME != 0) {
485 if (PANIC_REBOOT_WAIT_TIME != -1) {
486 printf("Automatic reboot in %d seconds - "
487 "press a key on the console to abort\n",
488 PANIC_REBOOT_WAIT_TIME);
489 for (loop = PANIC_REBOOT_WAIT_TIME * 10;
491 DELAY(1000 * 100); /* 1/10th second */
492 /* Did user type a key? */
493 if (cncheckc() != -1)
499 } else { /* zero time specified - reboot NOW */
502 printf("--> Press a key on the console to reboot,\n");
503 printf("--> or switch off the system now.\n");
509 * Everything done, now reset
512 shutdown_reset(void *junk, int howto)
515 printf("Rebooting...\n");
516 DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
519 * Acquiring smp_ipi_mtx here has a double effect:
520 * - it disables interrupts avoiding CPU0 preemption
521 * by fast handlers (thus deadlocking against other CPUs)
522 * - it avoids deadlocks against smp_rendezvous() or, more
523 * generally, threads busy-waiting, with this spinlock held,
524 * and waiting for responses by threads on other CPUs
525 * (ie. smp_tlb_shootdown()).
527 * For the !SMP case it just needs to handle the former problem.
530 mtx_lock_spin(&smp_ipi_mtx);
535 /* cpu_boot(howto); */ /* doesn't do anything at the moment */
537 /* NOTREACHED */ /* assuming reset worked */
541 * Panic is called on unresolvable fatal errors. It prints "panic: mesg",
542 * and then reboots. If we are called twice, then we avoid trying to sync
543 * the disks as this often leads to recursive panics.
546 panic(const char *fmt, ...)
549 static volatile u_int panic_cpu = NOCPU;
551 struct thread *td = curthread;
552 int bootopt, newpanic;
554 static char buf[256];
556 if (stop_scheduler_on_panic)
563 * We don't want multiple CPU's to panic at the same time, so we
564 * use panic_cpu as a simple spinlock. We have to keep checking
565 * panic_cpu if we are spinning in case the panic on the first
568 if (panic_cpu != PCPU_GET(cpuid))
569 while (atomic_cmpset_int(&panic_cpu, NOCPU,
570 PCPU_GET(cpuid)) == 0)
571 while (panic_cpu != NOCPU)
574 if (stop_scheduler_on_panic) {
575 if (panicstr == NULL && !kdb_active)
576 stop_cpus_hard(PCPU_GET(other_cpus));
579 * We set stop_scheduler here and not in the block above,
580 * because we want to ensure that if panic has been called and
581 * stop_scheduler_on_panic is true, then stop_scheduler will
582 * always be set. Even if panic has been entered from kdb.
584 td->td_stopsched = 1;
588 bootopt = RB_AUTOBOOT | RB_DUMP;
591 bootopt |= RB_NOSYNC;
599 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
601 printf("panic: %s\n", buf);
609 printf("cpuid = %d\n", PCPU_GET(cpuid));
613 if (newpanic && trace_on_panic)
615 if (debugger_on_panic)
616 kdb_enter(KDB_WHY_PANIC, "panic");
617 #ifdef RESTARTABLE_PANICS
618 /* See if the user aborted the panic, in which case we continue. */
619 if (panicstr == NULL) {
621 atomic_store_rel_int(&panic_cpu, NOCPU);
627 /*thread_lock(td); */
628 td->td_flags |= TDF_INPANIC;
629 /* thread_unlock(td); */
631 bootopt |= RB_NOSYNC;
632 if (!stop_scheduler_on_panic)
638 * Support for poweroff delay.
640 #ifndef POWEROFF_DELAY
641 # define POWEROFF_DELAY 5000
643 static int poweroff_delay = POWEROFF_DELAY;
645 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
646 &poweroff_delay, 0, "");
649 poweroff_wait(void *junk, int howto)
652 if (!(howto & RB_POWEROFF) || poweroff_delay <= 0)
654 DELAY(poweroff_delay * 1000);
658 * Some system processes (e.g. syncer) need to be stopped at appropriate
659 * points in their main loops prior to a system shutdown, so that they
660 * won't interfere with the shutdown process (e.g. by holding a disk buf
661 * to cause sync to fail). For each of these system processes, register
662 * shutdown_kproc() as a handler for one of shutdown events.
664 static int kproc_shutdown_wait = 60;
665 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
666 &kproc_shutdown_wait, 0, "");
669 kproc_shutdown(void *arg, int howto)
672 char procname[MAXCOMLEN + 1];
678 p = (struct proc *)arg;
679 strlcpy(procname, p->p_comm, sizeof(procname));
680 printf("Waiting (max %d seconds) for system process `%s' to stop...",
681 kproc_shutdown_wait, procname);
682 error = kproc_suspend(p, kproc_shutdown_wait * hz);
684 if (error == EWOULDBLOCK)
685 printf("timed out\n");
691 kthread_shutdown(void *arg, int howto)
694 char procname[MAXCOMLEN + 1];
700 td = (struct thread *)arg;
701 strlcpy(procname, td->td_name, sizeof(procname));
702 printf("Waiting (max %d seconds) for system thread `%s' to stop...",
703 kproc_shutdown_wait, procname);
704 error = kthread_suspend(td, kproc_shutdown_wait * hz);
706 if (error == EWOULDBLOCK)
707 printf("timed out\n");
712 /* Registration of dumpers */
714 set_dumper(struct dumperinfo *di)
718 bzero(&dumper, sizeof dumper);
721 if (dumper.dumper != NULL)
727 /* Call dumper with bounds checking. */
729 dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
730 off_t offset, size_t length)
733 if (length != 0 && (offset < di->mediaoffset ||
734 offset - di->mediaoffset + length > di->mediasize)) {
735 printf("Attempt to write outside dump device boundaries.\n"
736 "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
737 (intmax_t)offset, (intmax_t)di->mediaoffset,
738 (uintmax_t)length, (intmax_t)di->mediasize);
741 return (di->dumper(di->priv, virtual, physical, offset, length));
745 mkdumpheader(struct kerneldumpheader *kdh, char *magic, uint32_t archver,
746 uint64_t dumplen, uint32_t blksz)
749 bzero(kdh, sizeof(*kdh));
750 strncpy(kdh->magic, magic, sizeof(kdh->magic));
751 strncpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
752 kdh->version = htod32(KERNELDUMPVERSION);
753 kdh->architectureversion = htod32(archver);
754 kdh->dumplength = htod64(dumplen);
755 kdh->dumptime = htod64(time_second);
756 kdh->blocksize = htod32(blksz);
757 strncpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
758 strncpy(kdh->versionstring, version, sizeof(kdh->versionstring));
759 if (panicstr != NULL)
760 strncpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
761 kdh->parity = kerneldump_parity(kdh);