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