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