* The diskslice abstraction now stores offsets/sizes as 64 bit quantities.
[dragonfly.git] / sys / kern / kern_shutdown.c
1 /*-
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.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)kern_shutdown.c     8.3 (Berkeley) 1/21/94
39  * $FreeBSD: src/sys/kern/kern_shutdown.c,v 1.72.2.12 2002/02/21 19:15:10 dillon Exp $
40  * $DragonFly: src/sys/kern/kern_shutdown.c,v 1.52 2007/05/15 22:44:14 dillon Exp $
41  */
42
43 #include "opt_ddb.h"
44 #include "opt_ddb_trace.h"
45 #include "opt_hw_wdog.h"
46 #include "opt_panic.h"
47 #include "opt_show_busybufs.h"
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/eventhandler.h>
52 #include <sys/buf.h>
53 #include <sys/disklabel.h>
54 #include <sys/reboot.h>
55 #include <sys/proc.h>
56 #include <sys/vnode.h>
57 #include <sys/kernel.h>
58 #include <sys/kthread.h>
59 #include <sys/malloc.h>
60 #include <sys/mount.h>
61 #include <sys/queue.h>
62 #include <sys/sysctl.h>
63 #include <sys/vkernel.h>
64 #include <sys/conf.h>
65 #include <sys/sysproto.h>
66 #include <sys/device.h>
67 #include <sys/cons.h>
68 #include <sys/shm.h>
69 #include <sys/kern_syscall.h>
70 #include <vm/vm_map.h>
71 #include <vm/pmap.h>
72
73 #include <sys/thread2.h>
74 #include <sys/buf2.h>
75
76 #include <machine/pcb.h>
77 #include <machine/clock.h>
78 #include <machine/md_var.h>
79 #include <machine/smp.h>                /* smp_active_mask, cpuid */
80 #include <machine/vmparam.h>
81
82 #include <sys/signalvar.h>
83
84 #ifndef PANIC_REBOOT_WAIT_TIME
85 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
86 #endif
87
88 /*
89  * Note that stdarg.h and the ANSI style va_start macro is used for both
90  * ANSI and traditional C compilers.  We use the machine version to stay
91  * within the confines of the kernel header files.
92  */
93 #include <machine/stdarg.h>
94
95 #ifdef DDB
96 #ifdef DDB_UNATTENDED
97 int debugger_on_panic = 0;
98 #else
99 int debugger_on_panic = 1;
100 #endif
101 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic, CTLFLAG_RW,
102         &debugger_on_panic, 0, "Run debugger on kernel panic");
103
104 extern void db_print_backtrace(void);
105
106 #ifdef DDB_TRACE
107 int trace_on_panic = 1;
108 #else
109 int trace_on_panic = 0;
110 #endif
111 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic, CTLFLAG_RW,
112         &trace_on_panic, 0, "Print stack trace on kernel panic");
113 #endif
114
115 static int sync_on_panic = 1;
116 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RW,
117         &sync_on_panic, 0, "Do a sync before rebooting from a panic");
118
119 SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0, "Shutdown environment");
120
121 #ifdef  HW_WDOG
122 /*
123  * If there is a hardware watchdog, point this at the function needed to
124  * hold it off.
125  * It's needed when the kernel needs to do some lengthy operations.
126  * e.g. in wd.c when dumping core.. It's most annoying to have
127  * your precious core-dump only half written because the wdog kicked in.
128  */
129 watchdog_tickle_fn wdog_tickler = NULL;
130 #endif  /* HW_WDOG */
131
132 /*
133  * Variable panicstr contains argument to first call to panic; used as flag
134  * to indicate that the kernel has already called panic.
135  */
136 const char *panicstr;
137
138 int dumping;                            /* system is dumping */
139 #ifdef SMP
140 u_int panic_cpu_interlock;              /* panic interlock */
141 globaldata_t panic_cpu_gd;              /* which cpu took the panic */
142 #endif
143
144 int bootverbose = 0;                    /* note: assignment to force non-bss */
145 int cold = 1;                           /* note: assignment to force non-bss */
146 int dumplo;                             /* OBSOLETE - savecore compat */
147 u_int64_t dumplo64;
148
149 static void boot (int) __dead2;
150 static void dumpsys (void);
151 static int setdumpdev (cdev_t dev);
152 static void poweroff_wait (void *, int);
153 static void print_uptime (void);
154 static void shutdown_halt (void *junk, int howto);
155 static void shutdown_panic (void *junk, int howto);
156 static void shutdown_reset (void *junk, int howto);
157 static int shutdown_busycount1(struct buf *bp, void *info);
158 static int shutdown_busycount2(struct buf *bp, void *info);
159 static void shutdown_cleanup_proc(struct proc *p);
160
161 /* register various local shutdown events */
162 static void 
163 shutdown_conf(void *unused)
164 {
165         EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL, SHUTDOWN_PRI_FIRST);
166         EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL, SHUTDOWN_PRI_LAST + 100);
167         EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL, SHUTDOWN_PRI_LAST + 100);
168         EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL, SHUTDOWN_PRI_LAST + 200);
169 }
170
171 SYSINIT(shutdown_conf, SI_BOOT2_MACHDEP, SI_ORDER_ANY, shutdown_conf, NULL)
172
173 /* ARGSUSED */
174
175 /*
176  * The system call that results in a reboot
177  */
178 int
179 sys_reboot(struct reboot_args *uap)
180 {
181         struct thread *td = curthread;
182         int error;
183
184         if ((error = suser(td)))
185                 return (error);
186
187         boot(uap->opt);
188         return (0);
189 }
190
191 /*
192  * Called by events that want to shut down.. e.g  <CTL><ALT><DEL> on a PC
193  */
194 static int shutdown_howto = 0;
195
196 void
197 shutdown_nice(int howto)
198 {
199         shutdown_howto = howto;
200         
201         /* Send a signal to init(8) and have it shutdown the world */
202         if (initproc != NULL) {
203                 ksignal(initproc, SIGINT);
204         } else {
205                 /* No init(8) running, so simply reboot */
206                 boot(RB_NOSYNC);
207         }
208         return;
209 }
210 static int      waittime = -1;
211 static struct thread *dumpthread;
212 static struct pcb dumppcb;
213
214 static void
215 print_uptime(void)
216 {
217         int f;
218         struct timespec ts;
219
220         getnanouptime(&ts);
221         kprintf("Uptime: ");
222         f = 0;
223         if (ts.tv_sec >= 86400) {
224                 kprintf("%ldd", ts.tv_sec / 86400);
225                 ts.tv_sec %= 86400;
226                 f = 1;
227         }
228         if (f || ts.tv_sec >= 3600) {
229                 kprintf("%ldh", ts.tv_sec / 3600);
230                 ts.tv_sec %= 3600;
231                 f = 1;
232         }
233         if (f || ts.tv_sec >= 60) {
234                 kprintf("%ldm", ts.tv_sec / 60);
235                 ts.tv_sec %= 60;
236                 f = 1;
237         }
238         kprintf("%lds\n", ts.tv_sec);
239 }
240
241 /*
242  *  Go through the rigmarole of shutting down..
243  * this used to be in machdep.c but I'll be dammned if I could see
244  * anything machine dependant in it.
245  */
246 static void
247 boot(int howto)
248 {
249         /*
250          * Get rid of any user scheduler baggage and then give
251          * us a high priority.
252          */
253         if (curthread->td_release)
254                 curthread->td_release(curthread);
255         lwkt_setpri_self(TDPRI_MAX);
256
257         /* collect extra flags that shutdown_nice might have set */
258         howto |= shutdown_howto;
259
260 #ifdef SMP
261         /*
262          * We really want to shutdown on the BSP.  Subsystems such as ACPI
263          * can't power-down the box otherwise.
264          */
265         if (smp_active_mask > 1) {
266                 kprintf("boot() called on cpu#%d\n", mycpu->gd_cpuid);
267         }
268         if (panicstr == NULL && mycpu->gd_cpuid != 0) {
269                 kprintf("Switching to cpu #0 for shutdown\n");
270                 lwkt_setcpu_self(globaldata_find(0));
271         }
272 #endif
273         /*
274          * Do any callouts that should be done BEFORE syncing the filesystems.
275          */
276         EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
277
278         /*
279          * Try to get rid of any remaining FS references.  The calling
280          * process, proc0, and init may still hold references.  The
281          * VFS cache subsystem may still hold a root reference to root.
282          *
283          * XXX this needs work.  We really need to SIGSTOP all remaining
284          * processes in order to avoid blowups due to proc0's filesystem
285          * references going away.  For now just make sure that the init
286          * process is stopped.
287          */
288         if (panicstr == NULL) {
289                 shutdown_cleanup_proc(curproc);
290                 shutdown_cleanup_proc(&proc0);
291                 if (initproc) {
292                         if (initproc != curproc) {
293                                 ksignal(initproc, SIGSTOP);
294                                 tsleep(boot, 0, "shutdn", hz / 20);
295                         }
296                         shutdown_cleanup_proc(initproc);
297                 }
298                 vfs_cache_setroot(NULL, NULL);
299         }
300
301         /* 
302          * Now sync filesystems
303          */
304         if (!cold && (howto & RB_NOSYNC) == 0 && waittime < 0) {
305                 int iter, nbusy, pbusy;
306
307                 waittime = 0;
308                 kprintf("\nsyncing disks... ");
309
310                 sys_sync(NULL); /* YYY was sync(&proc0, NULL). why proc0 ? */
311
312                 /*
313                  * With soft updates, some buffers that are
314                  * written will be remarked as dirty until other
315                  * buffers are written.
316                  */
317                 for (iter = pbusy = 0; iter < 20; iter++) {
318                         nbusy = scan_all_buffers(shutdown_busycount1, NULL);
319                         if (nbusy == 0)
320                                 break;
321                         kprintf("%d ", nbusy);
322                         if (nbusy < pbusy)
323                                 iter = 0;
324                         pbusy = nbusy;
325                         /*
326                          * XXX:
327                          * Process soft update work queue if buffers don't sync
328                          * after 6 iterations by permitting the syncer to run.
329                          */
330                         if (iter > 5 && bioops.io_sync)
331                                 (*bioops.io_sync)(NULL);
332                         sys_sync(NULL); /* YYY was sync(&proc0, NULL). why proc0 ? */
333                         tsleep(boot, 0, "shutdn", hz * iter / 20 + 1);
334                 }
335                 kprintf("\n");
336                 /*
337                  * Count only busy local buffers to prevent forcing 
338                  * a fsck if we're just a client of a wedged NFS server
339                  */
340                 nbusy = scan_all_buffers(shutdown_busycount2, NULL);
341                 if (nbusy) {
342                         /*
343                          * Failed to sync all blocks. Indicate this and don't
344                          * unmount filesystems (thus forcing an fsck on reboot).
345                          */
346                         kprintf("giving up on %d buffers\n", nbusy);
347 #ifdef DDB
348                         Debugger("busy buffer problem");
349 #endif /* DDB */
350                         tsleep(boot, 0, "shutdn", hz * 5 + 1);
351                 } else {
352                         kprintf("done\n");
353                         /*
354                          * Unmount filesystems
355                          */
356                         if (panicstr == NULL)
357                                 vfs_unmountall();
358                 }
359                 tsleep(boot, 0, "shutdn", hz / 10 + 1);
360         }
361
362         print_uptime();
363
364         /*
365          * Ok, now do things that assume all filesystem activity has
366          * been completed.
367          */
368         EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
369         crit_enter();
370         if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold)
371                 dumpsys();
372
373         /* Now that we're going to really halt the system... */
374         EVENTHANDLER_INVOKE(shutdown_final, howto);
375
376         for(;;) ;       /* safety against shutdown_reset not working */
377         /* NOTREACHED */
378 }
379
380 static int
381 shutdown_busycount1(struct buf *bp, void *info)
382 {
383         if ((bp->b_flags & B_INVAL) == 0 && BUF_REFCNT(bp) > 0)
384                 return(1);
385         if ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI)
386                 return (1);
387         return (0);
388 }
389
390 static int
391 shutdown_busycount2(struct buf *bp, void *info)
392 {
393         if (((bp->b_flags & B_INVAL) == 0 && BUF_REFCNT(bp)) ||
394             ((bp->b_flags & (B_DELWRI|B_INVAL)) == B_DELWRI)) {
395                 /*
396                  * Only count buffers undergoing write I/O
397                  * on the related vnode.
398                  */
399                 if (bp->b_vp == NULL || 
400                     bp->b_vp->v_track_write.bk_active == 0) {
401                         return (0);
402                 }
403 #if defined(SHOW_BUSYBUFS) || defined(DIAGNOSTIC)
404                 kprintf(
405             "%p dev:?, flags:%08x, loffset:%lld, doffset:%lld\n",
406                     bp, 
407                     bp->b_flags, bp->b_loffset,
408                     bp->b_bio2.bio_offset);
409 #endif
410                 return(1);
411         }
412         return(0);
413 }
414
415 /*
416  * If the shutdown was a clean halt, behave accordingly.
417  */
418 static void
419 shutdown_halt(void *junk, int howto)
420 {
421         if (howto & RB_HALT) {
422                 kprintf("\n");
423                 kprintf("The operating system has halted.\n");
424                 kprintf("Please press any key to reboot.\n\n");
425                 switch (cngetc()) {
426                 case -1:                /* No console, just die */
427                         cpu_halt();
428                         /* NOTREACHED */
429                 default:
430                         howto &= ~RB_HALT;
431                         break;
432                 }
433         }
434 }
435
436 /*
437  * Check to see if the system paniced, pause and then reboot
438  * according to the specified delay.
439  */
440 static void
441 shutdown_panic(void *junk, int howto)
442 {
443         int loop;
444
445         if (howto & RB_DUMP) {
446                 if (PANIC_REBOOT_WAIT_TIME != 0) {
447                         if (PANIC_REBOOT_WAIT_TIME != -1) {
448                                 kprintf("Automatic reboot in %d seconds - "
449                                        "press a key on the console to abort\n",
450                                         PANIC_REBOOT_WAIT_TIME);
451                                 for (loop = PANIC_REBOOT_WAIT_TIME * 10;
452                                      loop > 0; --loop) {
453                                         DELAY(1000 * 100); /* 1/10th second */
454                                         /* Did user type a key? */
455                                         if (cncheckc() != -1)
456                                                 break;
457                                 }
458                                 if (!loop)
459                                         return;
460                         }
461                 } else { /* zero time specified - reboot NOW */
462                         return;
463                 }
464                 kprintf("--> Press a key on the console to reboot,\n");
465                 kprintf("--> or switch off the system now.\n");
466                 cngetc();
467         }
468 }
469
470 /*
471  * Everything done, now reset
472  */
473 static void
474 shutdown_reset(void *junk, int howto)
475 {
476         kprintf("Rebooting...\n");
477         DELAY(1000000); /* wait 1 sec for kprintf's to complete and be read */
478         /* cpu_boot(howto); */ /* doesn't do anything at the moment */
479         cpu_reset();
480         /* NOTREACHED */ /* assuming reset worked */
481 }
482
483 /*
484  * Try to remove FS references in the specified process.  This function
485  * is used during shutdown
486  */
487 static
488 void
489 shutdown_cleanup_proc(struct proc *p)
490 {
491         struct filedesc *fdp;
492         struct vmspace *vm;
493
494         if (p == NULL)
495                 return;
496         if ((fdp = p->p_fd) != NULL) {
497                 kern_closefrom(0);
498                 if (fdp->fd_cdir) {
499                         cache_drop(&fdp->fd_ncdir);
500                         vrele(fdp->fd_cdir);
501                         fdp->fd_cdir = NULL;
502                 }
503                 if (fdp->fd_rdir) {
504                         cache_drop(&fdp->fd_nrdir);
505                         vrele(fdp->fd_rdir);
506                         fdp->fd_rdir = NULL;
507                 }
508                 if (fdp->fd_jdir) {
509                         cache_drop(&fdp->fd_njdir);
510                         vrele(fdp->fd_jdir);
511                         fdp->fd_jdir = NULL;
512                 }
513         }
514         if (p->p_vkernel)
515                 vkernel_exit(p);
516         if (p->p_textvp) {
517                 vrele(p->p_textvp);
518                 p->p_textvp = NULL;
519         }
520         vm = p->p_vmspace;
521         if (vm != NULL) {
522                 pmap_remove_pages(vmspace_pmap(vm),
523                                   VM_MIN_USER_ADDRESS,
524                                   VM_MAX_USER_ADDRESS);
525                 vm_map_remove(&vm->vm_map,
526                               VM_MIN_USER_ADDRESS,
527                               VM_MAX_USER_ADDRESS);
528         }
529 }
530
531 /*
532  * Magic number for savecore
533  *
534  * exported (symorder) and used at least by savecore(8)
535  *
536  * Mark it as used so that gcc doesn't optimize it away.
537  */
538 __attribute__((__used__))
539         static u_long const dumpmag = 0x8fca0101UL;     
540
541 static int      dumpsize = 0;           /* also for savecore */
542
543 static int      dodump = 1;
544
545 SYSCTL_INT(_machdep, OID_AUTO, do_dump, CTLFLAG_RW, &dodump, 0,
546     "Try to perform coredump on kernel panic");
547
548 static int
549 setdumpdev(cdev_t dev)
550 {
551         u_int64_t psize;
552         u_int64_t newdumplo;
553
554         if (dev == NULL) {
555                 dumpdev = dev;
556                 return (0);
557         }
558         psize = (u_int64_t)dev_dpsize(dev);
559         if (psize == (u_int64_t)-1)
560                 return (ENXIO);
561         /*
562          * XXX should clean up checking in dumpsys() to be more like this.
563          */
564         newdumplo = psize - Maxmem * (PAGE_SIZE / DEV_BSIZE);
565         if (newdumplo <= LABELSECTOR)
566                 return (ENOSPC);
567         dumpdev = dev;
568         if (newdumplo < 0x80000000ULL)
569                 dumplo = (int)newdumplo;
570         else
571                 dumplo = LABELSECTOR;   /* bleh XXX */
572         dumplo64 = newdumplo;
573         return (0);
574 }
575
576
577 /* ARGSUSED */
578 static void dump_conf (void *dummy);
579 static void
580 dump_conf(void *dummy)
581 {
582         char *path;
583         cdev_t dev;
584
585         path = kmalloc(MNAMELEN, M_TEMP, M_WAITOK);
586         if (TUNABLE_STR_FETCH("dumpdev", path, MNAMELEN) != 0) {
587                 dev = kgetdiskbyname(path);
588                 if (dev != NULL)
589                         dumpdev = dev;
590         }
591         kfree(path, M_TEMP);
592         if (setdumpdev(dumpdev) != 0)
593                 dumpdev = NULL;
594 }
595
596 SYSINIT(dump_conf, SI_SUB_DUMP_CONF, SI_ORDER_FIRST, dump_conf, NULL)
597
598 static int
599 sysctl_kern_dumpdev(SYSCTL_HANDLER_ARGS)
600 {
601         int error;
602         udev_t ndumpdev;
603
604         ndumpdev = dev2udev(dumpdev);
605         error = sysctl_handle_opaque(oidp, &ndumpdev, sizeof ndumpdev, req);
606         if (error == 0 && req->newptr != NULL)
607                 error = setdumpdev(udev2dev(ndumpdev, 0));
608         return (error);
609 }
610
611 SYSCTL_PROC(_kern, KERN_DUMPDEV, dumpdev, CTLTYPE_OPAQUE|CTLFLAG_RW,
612         0, sizeof dumpdev, sysctl_kern_dumpdev, "T,udev_t", "");
613
614 /*
615  * Doadump comes here after turning off memory management and
616  * getting on the dump stack, either when called above, or by
617  * the auto-restart code.
618  */
619 static void
620 dumpsys(void)
621 {
622         int     error;
623
624         savectx(&dumppcb);
625         dumpthread = curthread;
626         if (dumping++) {
627                 kprintf("Dump already in progress, bailing...\n");
628                 return;
629         }
630         if (!dodump)
631                 return;
632         if (dumpdev == NULL)
633                 return;
634         dumpsize = Maxmem;
635         kprintf("\ndumping to dev %s, blockno %lld\n",
636                 devtoname(dumpdev), dumplo64);
637         kprintf("dump ");
638         error = dev_ddump(dumpdev);
639         if (error == 0) {
640                 kprintf("succeeded\n");
641                 return;
642         }
643         kprintf("failed, reason: ");
644         switch (error) {
645         case ENOSYS:
646         case ENODEV:
647                 kprintf("device doesn't support a dump routine\n");
648                 break;
649
650         case ENXIO:
651                 kprintf("device bad\n");
652                 break;
653
654         case EFAULT:
655                 kprintf("device not ready\n");
656                 break;
657
658         case EINVAL:
659                 kprintf("area improper\n");
660                 break;
661
662         case EIO:
663                 kprintf("i/o error\n");
664                 break;
665
666         case EINTR:
667                 kprintf("aborted from console\n");
668                 break;
669
670         default:
671                 kprintf("unknown, error = %d\n", error);
672                 break;
673         }
674 }
675
676 int
677 dumpstatus(vm_offset_t addr, off_t count)
678 {
679         int c;
680
681         if (addr % (1024 * 1024) == 0) {
682 #ifdef HW_WDOG
683                 if (wdog_tickler)
684                         (*wdog_tickler)();
685 #endif   
686                 kprintf("%ld ", (long)(count / (1024 * 1024)));
687         }
688
689         if ((c = cncheckc()) == 0x03)
690                 return -1;
691         else if (c != -1)
692                 kprintf("[CTRL-C to abort] ");
693         
694         return 0;
695 }
696
697 /*
698  * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
699  * and then reboots.  If we are called twice, then we avoid trying to sync
700  * the disks as this often leads to recursive panics.
701  */
702 void
703 panic(const char *fmt, ...)
704 {
705         int bootopt, newpanic;
706         __va_list ap;
707         static char buf[256];
708
709 #ifdef SMP
710         /*
711          * If a panic occurs on multiple cpus before the first is able to
712          * halt the other cpus, only one cpu is allowed to take the panic.
713          * Attempt to be verbose about this situation but if the kprintf() 
714          * itself panics don't let us overrun the kernel stack.
715          *
716          * Be very nasty about descheduling our thread at the lowest
717          * level possible in an attempt to freeze the thread without
718          * inducing further panics.
719          *
720          * Bumping gd_trap_nesting_level will also bypass assertions in
721          * lwkt_switch() and allow us to switch away even if we are a
722          * FAST interrupt or IPI.
723          */
724         if (atomic_poll_acquire_int(&panic_cpu_interlock)) {
725                 panic_cpu_gd = mycpu;
726         } else if (panic_cpu_gd != mycpu) {
727                 crit_enter();
728                 ++mycpu->gd_trap_nesting_level;
729                 if (mycpu->gd_trap_nesting_level < 25) {
730                         kprintf("SECONDARY PANIC ON CPU %d THREAD %p\n",
731                                 mycpu->gd_cpuid, curthread);
732                 }
733                 curthread->td_release = NULL;   /* be a grinch */
734                 for (;;) {
735                         lwkt_deschedule_self(curthread);
736                         lwkt_switch();
737                 }
738                 /* NOT REACHED */
739                 /* --mycpu->gd_trap_nesting_level */
740                 /* crit_exit() */
741         }
742 #endif
743         bootopt = RB_AUTOBOOT | RB_DUMP;
744         if (sync_on_panic == 0)
745                 bootopt |= RB_NOSYNC;
746         newpanic = 0;
747         if (panicstr)
748                 bootopt |= RB_NOSYNC;
749         else {
750                 panicstr = fmt;
751                 newpanic = 1;
752         }
753
754         __va_start(ap, fmt);
755         kvsnprintf(buf, sizeof(buf), fmt, ap);
756         if (panicstr == fmt)
757                 panicstr = buf;
758         __va_end(ap);
759         kprintf("panic: %s\n", buf);
760 #ifdef SMP
761         /* three separate prints in case of an unmapped page and trap */
762         kprintf("mp_lock = %08x; ", mp_lock);
763         kprintf("cpuid = %d; ", mycpu->gd_cpuid);
764         kprintf("lapic.id = %08x\n", lapic.id);
765 #endif
766
767 #if defined(DDB)
768         if (newpanic && trace_on_panic)
769                 db_print_backtrace();
770         if (debugger_on_panic)
771                 Debugger ("panic");
772 #endif
773         boot(bootopt);
774 }
775
776 /*
777  * Support for poweroff delay.
778  */
779 #ifndef POWEROFF_DELAY
780 # define POWEROFF_DELAY 5000
781 #endif
782 static int poweroff_delay = POWEROFF_DELAY;
783
784 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
785         &poweroff_delay, 0, "");
786
787 static void 
788 poweroff_wait(void *junk, int howto)
789 {
790         if(!(howto & RB_POWEROFF) || poweroff_delay <= 0)
791                 return;
792         DELAY(poweroff_delay * 1000);
793 }
794
795 /*
796  * Some system processes (e.g. syncer) need to be stopped at appropriate
797  * points in their main loops prior to a system shutdown, so that they
798  * won't interfere with the shutdown process (e.g. by holding a disk buf
799  * to cause sync to fail).  For each of these system processes, register
800  * shutdown_kproc() as a handler for one of shutdown events.
801  */
802 static int kproc_shutdown_wait = 60;
803 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
804     &kproc_shutdown_wait, 0, "");
805
806 void
807 shutdown_kproc(void *arg, int howto)
808 {
809         struct thread *td;
810         struct proc *p;
811         int error;
812
813         if (panicstr)
814                 return;
815
816         td = (struct thread *)arg;
817         if ((p = td->td_proc) != NULL) {
818             kprintf("Waiting (max %d seconds) for system process `%s' to stop...",
819                 kproc_shutdown_wait, p->p_comm);
820         } else {
821             kprintf("Waiting (max %d seconds) for system thread %s to stop...",
822                 kproc_shutdown_wait, td->td_comm);
823         }
824         error = suspend_kproc(td, kproc_shutdown_wait * hz);
825
826         if (error == EWOULDBLOCK)
827                 kprintf("timed out\n");
828         else
829                 kprintf("stopped\n");
830 }