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