* Add this nice filesystem testing tool that I've recently
[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.12 2003/09/05 17:46:54 hsu 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/conf.h>
64 #include <sys/sysproto.h>
65 #include <sys/device.h>
66 #include <sys/cons.h>
67 #include <sys/buf2.h>
68
69 #include <machine/pcb.h>
70 #include <machine/clock.h>
71 #include <machine/md_var.h>
72 #include <machine/smp.h>                /* smp_active, cpuid */
73
74 #include <sys/signalvar.h>
75
76 #ifndef PANIC_REBOOT_WAIT_TIME
77 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
78 #endif
79
80 /*
81  * Note that stdarg.h and the ANSI style va_start macro is used for both
82  * ANSI and traditional C compilers.
83  */
84 #include <machine/stdarg.h>
85
86 #ifdef DDB
87 #ifdef DDB_UNATTENDED
88 int debugger_on_panic = 0;
89 #else
90 int debugger_on_panic = 1;
91 #endif
92 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic, CTLFLAG_RW,
93         &debugger_on_panic, 0, "Run debugger on kernel panic");
94
95 extern void db_print_backtrace(void);
96
97 #ifdef DDB_TRACE
98 int trace_on_panic = 1;
99 #else
100 int trace_on_panic = 0;
101 #endif
102 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic, CTLFLAG_RW,
103         &trace_on_panic, 0, "Print stack trace on kernel panic");
104 #endif
105
106 SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0, "Shutdown environment");
107
108 #ifdef  HW_WDOG
109 /*
110  * If there is a hardware watchdog, point this at the function needed to
111  * hold it off.
112  * It's needed when the kernel needs to do some lengthy operations.
113  * e.g. in wd.c when dumping core.. It's most annoying to have
114  * your precious core-dump only half written because the wdog kicked in.
115  */
116 watchdog_tickle_fn wdog_tickler = NULL;
117 #endif  /* HW_WDOG */
118
119 /*
120  * Variable panicstr contains argument to first call to panic; used as flag
121  * to indicate that the kernel has already called panic.
122  */
123 const char *panicstr;
124
125 int dumping;                            /* system is dumping */
126
127 static void boot (int) __dead2;
128 static void dumpsys (void);
129 static int setdumpdev (dev_t dev);
130 static void poweroff_wait (void *, int);
131 static void print_uptime (void);
132 static void shutdown_halt (void *junk, int howto);
133 static void shutdown_panic (void *junk, int howto);
134 static void shutdown_reset (void *junk, int howto);
135
136 /* register various local shutdown events */
137 static void 
138 shutdown_conf(void *unused)
139 {
140         EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL, SHUTDOWN_PRI_FIRST);
141         EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL, SHUTDOWN_PRI_LAST + 100);
142         EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL, SHUTDOWN_PRI_LAST + 100);
143         EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL, SHUTDOWN_PRI_LAST + 200);
144 }
145
146 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL)
147
148 /* ARGSUSED */
149
150 /*
151  * The system call that results in a reboot
152  */
153 int
154 reboot(struct reboot_args *uap)
155 {
156         struct thread *td = curthread;
157         int error;
158
159         if ((error = suser(td)))
160                 return (error);
161
162         boot(uap->opt);
163         return (0);
164 }
165
166 /*
167  * Called by events that want to shut down.. e.g  <CTL><ALT><DEL> on a PC
168  */
169 static int shutdown_howto = 0;
170
171 void
172 shutdown_nice(int howto)
173 {
174         shutdown_howto = howto;
175         
176         /* Send a signal to init(8) and have it shutdown the world */
177         if (initproc != NULL) {
178                 psignal(initproc, SIGINT);
179         } else {
180                 /* No init(8) running, so simply reboot */
181                 boot(RB_NOSYNC);
182         }
183         return;
184 }
185 static int      waittime = -1;
186 static struct pcb dumppcb;
187
188 static void
189 print_uptime()
190 {
191         int f;
192         struct timespec ts;
193
194         getnanouptime(&ts);
195         printf("Uptime: ");
196         f = 0;
197         if (ts.tv_sec >= 86400) {
198                 printf("%ldd", ts.tv_sec / 86400);
199                 ts.tv_sec %= 86400;
200                 f = 1;
201         }
202         if (f || ts.tv_sec >= 3600) {
203                 printf("%ldh", ts.tv_sec / 3600);
204                 ts.tv_sec %= 3600;
205                 f = 1;
206         }
207         if (f || ts.tv_sec >= 60) {
208                 printf("%ldm", ts.tv_sec / 60);
209                 ts.tv_sec %= 60;
210                 f = 1;
211         }
212         printf("%lds\n", ts.tv_sec);
213 }
214
215 /*
216  *  Go through the rigmarole of shutting down..
217  * this used to be in machdep.c but I'll be dammned if I could see
218  * anything machine dependant in it.
219  */
220 static void
221 boot(int howto)
222 {
223
224         /* collect extra flags that shutdown_nice might have set */
225         howto |= shutdown_howto;
226
227 #ifdef SMP
228         if (smp_active) {
229                 printf("boot() called on cpu#%d\n", mycpu->gd_cpuid);
230         }
231 #endif
232         /*
233          * Do any callouts that should be done BEFORE syncing the filesystems.
234          */
235         EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
236
237         /* 
238          * Now sync filesystems
239          */
240         if (!cold && (howto & RB_NOSYNC) == 0 && waittime < 0) {
241                 struct buf *bp;
242                 int iter, nbusy, pbusy;
243
244                 waittime = 0;
245                 printf("\nsyncing disks... ");
246
247                 sync(NULL);     /* YYY was sync(&proc0, NULL). why proc0 ? */
248
249                 /*
250                  * With soft updates, some buffers that are
251                  * written will be remarked as dirty until other
252                  * buffers are written.
253                  */
254                 for (iter = pbusy = 0; iter < 20; iter++) {
255                         nbusy = 0;
256                         for (bp = &buf[nbuf]; --bp >= buf; ) {
257                                 if ((bp->b_flags & B_INVAL) == 0 &&
258                                     BUF_REFCNT(bp) > 0) {
259                                         nbusy++;
260                                 } else if ((bp->b_flags & (B_DELWRI | B_INVAL))
261                                                 == B_DELWRI) {
262                                         /* bawrite(bp);*/
263                                         nbusy++;
264                                 }
265                         }
266                         if (nbusy == 0)
267                                 break;
268                         printf("%d ", nbusy);
269                         if (nbusy < pbusy)
270                                 iter = 0;
271                         pbusy = nbusy;
272                         if (iter > 5 && bioops.io_sync)
273                                 (*bioops.io_sync)(NULL);
274                         sync(NULL); /* YYY was sync(&proc0, NULL). why proc0 ? */
275                         DELAY(50000 * iter);
276                 }
277                 printf("\n");
278                 /*
279                  * Count only busy local buffers to prevent forcing 
280                  * a fsck if we're just a client of a wedged NFS server
281                  */
282                 nbusy = 0;
283                 for (bp = &buf[nbuf]; --bp >= buf; ) {
284                         if (((bp->b_flags&B_INVAL) == 0 && BUF_REFCNT(bp)) ||
285                             ((bp->b_flags & (B_DELWRI|B_INVAL)) == B_DELWRI)) {
286                                 if (bp->b_dev == NODEV) {
287                                         TAILQ_REMOVE(&mountlist,
288                                             bp->b_vp->v_mount, mnt_list);
289                                         continue;
290                                 }
291                                 nbusy++;
292 #if defined(SHOW_BUSYBUFS) || defined(DIAGNOSTIC)
293                                 printf(
294                             "%p %d: dev:%s, flags:%08lx, blkno:%ld, lblkno:%ld\n",
295                                     bp, nbusy, devtoname(bp->b_dev),
296                                     bp->b_flags, (long)bp->b_blkno,
297                                     (long)bp->b_lblkno);
298 #endif
299                         }
300                 }
301                 if (nbusy) {
302                         /*
303                          * Failed to sync all blocks. Indicate this and don't
304                          * unmount filesystems (thus forcing an fsck on reboot).
305                          */
306                         printf("giving up on %d buffers\n", nbusy);
307                         DELAY(5000000); /* 5 seconds */
308                 } else {
309                         printf("done\n");
310                         /*
311                          * Unmount filesystems
312                          */
313                         if (panicstr == 0)
314                                 vfs_unmountall();
315                 }
316                 DELAY(100000);          /* wait for console output to finish */
317         }
318
319         print_uptime();
320
321         /*
322          * Ok, now do things that assume all filesystem activity has
323          * been completed.
324          */
325         EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
326         splhigh();
327         if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold)
328                 dumpsys();
329
330         /* Now that we're going to really halt the system... */
331         EVENTHANDLER_INVOKE(shutdown_final, howto);
332
333         for(;;) ;       /* safety against shutdown_reset not working */
334         /* NOTREACHED */
335 }
336
337 /*
338  * If the shutdown was a clean halt, behave accordingly.
339  */
340 static void
341 shutdown_halt(void *junk, int howto)
342 {
343         if (howto & RB_HALT) {
344                 printf("\n");
345                 printf("The operating system has halted.\n");
346                 printf("Please press any key to reboot.\n\n");
347                 switch (cngetc()) {
348                 case -1:                /* No console, just die */
349                         cpu_halt();
350                         /* NOTREACHED */
351                 default:
352                         howto &= ~RB_HALT;
353                         break;
354                 }
355         }
356 }
357
358 /*
359  * Check to see if the system paniced, pause and then reboot
360  * according to the specified delay.
361  */
362 static void
363 shutdown_panic(void *junk, int howto)
364 {
365         int loop;
366
367         if (howto & RB_DUMP) {
368                 if (PANIC_REBOOT_WAIT_TIME != 0) {
369                         if (PANIC_REBOOT_WAIT_TIME != -1) {
370                                 printf("Automatic reboot in %d seconds - "
371                                        "press a key on the console to abort\n",
372                                         PANIC_REBOOT_WAIT_TIME);
373                                 for (loop = PANIC_REBOOT_WAIT_TIME * 10;
374                                      loop > 0; --loop) {
375                                         DELAY(1000 * 100); /* 1/10th second */
376                                         /* Did user type a key? */
377                                         if (cncheckc() != -1)
378                                                 break;
379                                 }
380                                 if (!loop)
381                                         return;
382                         }
383                 } else { /* zero time specified - reboot NOW */
384                         return;
385                 }
386                 printf("--> Press a key on the console to reboot,\n");
387                 printf("--> or switch off the system now.\n");
388                 cngetc();
389         }
390 }
391
392 /*
393  * Everything done, now reset
394  */
395 static void
396 shutdown_reset(void *junk, int howto)
397 {
398         printf("Rebooting...\n");
399         DELAY(1000000); /* wait 1 sec for printf's to complete and be read */
400         /* cpu_boot(howto); */ /* doesn't do anything at the moment */
401         cpu_reset();
402         /* NOTREACHED */ /* assuming reset worked */
403 }
404
405 /*
406  * Magic number for savecore
407  *
408  * exported (symorder) and used at least by savecore(8)
409  *
410  */
411 static u_long const     dumpmag = 0x8fca0101UL; 
412
413 static int      dumpsize = 0;           /* also for savecore */
414
415 static int      dodump = 1;
416
417 SYSCTL_INT(_machdep, OID_AUTO, do_dump, CTLFLAG_RW, &dodump, 0,
418     "Try to perform coredump on kernel panic");
419
420 static int
421 setdumpdev(dev)
422         dev_t dev;
423 {
424         int psize;
425         long newdumplo;
426
427         if (dev == NODEV) {
428                 dumpdev = dev;
429                 return (0);
430         }
431         psize = dev_dpsize(dev);
432         if (psize == -1)
433                 return (ENXIO);
434         /*
435          * XXX should clean up checking in dumpsys() to be more like this.
436          */
437         newdumplo = psize - Maxmem * (PAGE_SIZE / DEV_BSIZE);
438         if (newdumplo <= LABELSECTOR)
439                 return (ENOSPC);
440         dumpdev = dev;
441         dumplo = newdumplo;
442         return (0);
443 }
444
445
446 /* ARGSUSED */
447 static void dump_conf (void *dummy);
448 static void
449 dump_conf(dummy)
450         void *dummy;
451 {
452         char *path;
453         dev_t dev;
454
455         path = malloc(MNAMELEN, M_TEMP, M_WAITOK);
456         if (TUNABLE_STR_FETCH("dumpdev", path, MNAMELEN) != 0) {
457                 dev = getdiskbyname(path);
458                 if (dev != NODEV)
459                         dumpdev = dev;
460         }
461         free(path, M_TEMP);
462         if (setdumpdev(dumpdev) != 0)
463                 dumpdev = NODEV;
464 }
465
466 SYSINIT(dump_conf, SI_SUB_DUMP_CONF, SI_ORDER_FIRST, dump_conf, NULL)
467
468 static int
469 sysctl_kern_dumpdev(SYSCTL_HANDLER_ARGS)
470 {
471         int error;
472         udev_t ndumpdev;
473
474         ndumpdev = dev2udev(dumpdev);
475         error = sysctl_handle_opaque(oidp, &ndumpdev, sizeof ndumpdev, req);
476         if (error == 0 && req->newptr != NULL)
477                 error = setdumpdev(udev2dev(ndumpdev, 0));
478         return (error);
479 }
480
481 SYSCTL_PROC(_kern, KERN_DUMPDEV, dumpdev, CTLTYPE_OPAQUE|CTLFLAG_RW,
482         0, sizeof dumpdev, sysctl_kern_dumpdev, "T,dev_t", "");
483
484 /*
485  * Doadump comes here after turning off memory management and
486  * getting on the dump stack, either when called above, or by
487  * the auto-restart code.
488  */
489 static void
490 dumpsys(void)
491 {
492         int     error;
493
494         savectx(&dumppcb);
495         if (dumping++) {
496                 printf("Dump already in progress, bailing...\n");
497                 return;
498         }
499         if (!dodump)
500                 return;
501         if (dumpdev == NODEV)
502                 return;
503         dumpsize = Maxmem;
504         printf("\ndumping to dev %s, offset %ld\n", devtoname(dumpdev), dumplo);
505         printf("dump ");
506         error = dev_ddump(dumpdev);
507         if (error == 0) {
508                 printf("succeeded\n");
509                 return;
510         }
511         printf("failed, reason: ");
512         switch (error) {
513         case ENOSYS:
514         case ENODEV:
515                 printf("device doesn't support a dump routine\n");
516                 break;
517
518         case ENXIO:
519                 printf("device bad\n");
520                 break;
521
522         case EFAULT:
523                 printf("device not ready\n");
524                 break;
525
526         case EINVAL:
527                 printf("area improper\n");
528                 break;
529
530         case EIO:
531                 printf("i/o error\n");
532                 break;
533
534         case EINTR:
535                 printf("aborted from console\n");
536                 break;
537
538         default:
539                 printf("unknown, error = %d\n", error);
540                 break;
541         }
542 }
543
544 int
545 dumpstatus(vm_offset_t addr, off_t count)
546 {
547         int c;
548
549         if (addr % (1024 * 1024) == 0) {
550 #ifdef HW_WDOG
551                 if (wdog_tickler)
552                         (*wdog_tickler)();
553 #endif   
554                 printf("%ld ", (long)(count / (1024 * 1024)));
555         }
556
557         if ((c = cncheckc()) == 0x03)
558                 return -1;
559         else if (c != -1)
560                 printf("[CTRL-C to abort] ");
561         
562         return 0;
563 }
564
565 /*
566  * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
567  * and then reboots.  If we are called twice, then we avoid trying to sync
568  * the disks as this often leads to recursive panics.
569  */
570 void
571 panic(const char *fmt, ...)
572 {
573         int bootopt, newpanic;
574         va_list ap;
575         static char buf[256];
576
577         bootopt = RB_AUTOBOOT | RB_DUMP;
578         newpanic = 0;
579         if (panicstr)
580                 bootopt |= RB_NOSYNC;
581         else {
582                 panicstr = fmt;
583                 newpanic = 1;
584         }
585
586         va_start(ap, fmt);
587         (void)vsnprintf(buf, sizeof(buf), fmt, ap);
588         if (panicstr == fmt)
589                 panicstr = buf;
590         va_end(ap);
591         printf("panic: %s\n", buf);
592 #ifdef SMP
593         /* three seperate prints in case of an unmapped page and trap */
594         printf("mp_lock = %08x; ", mp_lock);
595         printf("cpuid = %d; ", mycpu->gd_cpuid);
596         printf("lapic.id = %08x\n", lapic.id);
597 #endif
598
599 #if defined(DDB)
600         if (newpanic && trace_on_panic)
601                 db_print_backtrace();
602         if (debugger_on_panic)
603                 Debugger ("panic");
604 #endif
605         boot(bootopt);
606 }
607
608 /*
609  * Support for poweroff delay.
610  */
611 #ifndef POWEROFF_DELAY
612 # define POWEROFF_DELAY 5000
613 #endif
614 static int poweroff_delay = POWEROFF_DELAY;
615
616 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
617         &poweroff_delay, 0, "");
618
619 static void 
620 poweroff_wait(void *junk, int howto)
621 {
622         if(!(howto & RB_POWEROFF) || poweroff_delay <= 0)
623                 return;
624         DELAY(poweroff_delay * 1000);
625 }
626
627 /*
628  * Some system processes (e.g. syncer) need to be stopped at appropriate
629  * points in their main loops prior to a system shutdown, so that they
630  * won't interfere with the shutdown process (e.g. by holding a disk buf
631  * to cause sync to fail).  For each of these system processes, register
632  * shutdown_kproc() as a handler for one of shutdown events.
633  */
634 static int kproc_shutdown_wait = 60;
635 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
636     &kproc_shutdown_wait, 0, "");
637
638 void
639 shutdown_kproc(void *arg, int howto)
640 {
641         struct thread *td;
642         struct proc *p;
643         int error;
644
645         if (panicstr)
646                 return;
647
648         td = (struct thread *)arg;
649         if ((p = td->td_proc) != NULL) {
650             printf("Waiting (max %d seconds) for system process `%s' to stop...",
651                 kproc_shutdown_wait, p->p_comm);
652         } else {
653             printf("Waiting (max %d seconds) for system thread %s to stop...",
654                 kproc_shutdown_wait, td->td_comm);
655         }
656         error = suspend_kproc(td, kproc_shutdown_wait * hz);
657
658         if (error == EWOULDBLOCK)
659                 printf("timed out\n");
660         else
661                 printf("stopped\n");
662 }