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