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