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