kern_shutdown.c revision 67164
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 67164 2000-10-15 14:19:01Z 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/bio.h>
51#include <sys/buf.h>
52#include <sys/reboot.h>
53#include <sys/proc.h>
54#include <sys/vnode.h>
55#include <sys/kernel.h>
56#include <sys/kthread.h>
57#include <sys/mount.h>
58#include <sys/queue.h>
59#include <sys/sysctl.h>
60#include <sys/conf.h>
61#include <sys/sysproto.h>
62#include <sys/cons.h>
63
64#include <machine/pcb.h>
65#include <machine/lock.h>
66#include <machine/md_var.h>
67#include <machine/mutex.h>
68#include <machine/smp.h>		/* smp_active, cpuid */
69
70#include <sys/signalvar.h>
71
72#ifndef PANIC_REBOOT_WAIT_TIME
73#define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
74#endif
75
76/*
77 * Note that stdarg.h and the ANSI style va_start macro is used for both
78 * ANSI and traditional C compilers.
79 */
80#include <machine/stdarg.h>
81
82#ifdef DDB
83#ifdef DDB_UNATTENDED
84int debugger_on_panic = 0;
85#else
86int debugger_on_panic = 1;
87#endif
88SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic, CTLFLAG_RW,
89	&debugger_on_panic, 0, "Run debugger on kernel panic");
90#endif
91
92SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0, "Shutdown environment");
93
94#ifdef	HW_WDOG
95/*
96 * If there is a hardware watchdog, point this at the function needed to
97 * hold it off.
98 * It's needed when the kernel needs to do some lengthy operations.
99 * e.g. in wd.c when dumping core.. It's most annoying to have
100 * your precious core-dump only half written because the wdog kicked in.
101 */
102watchdog_tickle_fn wdog_tickler = NULL;
103#endif	/* HW_WDOG */
104
105/*
106 * Variable panicstr contains argument to first call to panic; used as flag
107 * to indicate that the kernel has already called panic.
108 */
109const char *panicstr;
110
111int dumping;				 /* system is dumping */
112
113static void boot(int) __dead2;
114static void dumpsys(void);
115static void poweroff_wait(void *, int);
116static void shutdown_halt(void *junk, int howto);
117static void shutdown_panic(void *junk, int howto);
118static void shutdown_reset(void *junk, int howto);
119
120/* register various local shutdown events */
121static void
122shutdown_conf(void *unused)
123{
124	EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL, SHUTDOWN_PRI_FIRST);
125	EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL, SHUTDOWN_PRI_LAST + 100);
126	EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL, SHUTDOWN_PRI_LAST + 100);
127	EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL, SHUTDOWN_PRI_LAST + 200);
128}
129
130SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL)
131
132/* ARGSUSED */
133
134/*
135 * The system call that results in a reboot
136 */
137int
138reboot(struct proc *p, 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 */
152static int shutdown_howto = 0;
153
154void
155shutdown_nice(int howto)
156{
157	shutdown_howto = howto;
158
159	/* Send a signal to init(8) and have it shutdown the world */
160	if (initproc != NULL) {
161		psignal(initproc, SIGINT);
162	} else {
163		/* No init(8) running, so simply reboot */
164		boot(RB_NOSYNC);
165	}
166	return;
167}
168static int	waittime = -1;
169static struct pcb dumppcb;
170
171static void
172print_uptime(void)
173{
174	int f;
175	struct timespec ts;
176
177	getnanouptime(&ts);
178	printf("Uptime: ");
179	f = 0;
180	if (ts.tv_sec >= 86400) {
181		printf("%ldd", (long)ts.tv_sec / 86400);
182		ts.tv_sec %= 86400;
183		f = 1;
184	}
185	if (f || ts.tv_sec >= 3600) {
186		printf("%ldh", (long)ts.tv_sec / 3600);
187		ts.tv_sec %= 3600;
188		f = 1;
189	}
190	if (f || ts.tv_sec >= 60) {
191		printf("%ldm", (long)ts.tv_sec / 60);
192		ts.tv_sec %= 60;
193		f = 1;
194	}
195	printf("%lds\n", (long)ts.tv_sec);
196}
197
198/*
199 *  Go through the rigmarole of shutting down..
200 * this used to be in machdep.c but I'll be dammned if I could see
201 * anything machine dependant in it.
202 */
203static void
204boot(int howto)
205{
206
207	/* collect extra flags that shutdown_nice might have set */
208	howto |= shutdown_howto;
209
210#ifdef SMP
211	if (smp_active)
212		printf("boot() called on cpu#%d\n", cpuid);
213#endif
214	/*
215	 * Do any callouts that should be done BEFORE syncing the filesystems.
216	 */
217	EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
218
219	/*
220	 * Now sync filesystems
221	 */
222	if (!cold && (howto & RB_NOSYNC) == 0 && waittime < 0) {
223		register struct buf *bp;
224		int iter, nbusy, pbusy;
225		int subiter;
226
227		waittime = 0;
228		printf("\nsyncing disks... ");
229
230		sync(&proc0, NULL);
231
232		/*
233		 * With soft updates, some buffers that are
234		 * written will be remarked as dirty until other
235		 * buffers are written.
236		 */
237		for (iter = pbusy = 0; iter < 20; iter++) {
238			nbusy = 0;
239			for (bp = &buf[nbuf]; --bp >= buf; ) {
240				if ((bp->b_flags & B_INVAL) == 0 &&
241				    BUF_REFCNT(bp) > 0) {
242					nbusy++;
243				} else if ((bp->b_flags & (B_DELWRI | B_INVAL))
244						== B_DELWRI) {
245					/* bawrite(bp);*/
246					nbusy++;
247				}
248			}
249			if (nbusy == 0)
250				break;
251			printf("%d ", nbusy);
252			if (nbusy < pbusy)
253				iter = 0;
254			pbusy = nbusy;
255			sync(&proc0, NULL);
256 			if (curproc != NULL) {
257   				for (subiter = 0; subiter < 50 * iter; subiter++) {
258     					mtx_enter(&sched_lock, MTX_SPIN);
259     					setrunqueue(curproc);
260     					mi_switch(); /* Allow interrupt threads to run */
261     					mtx_exit(&sched_lock, MTX_SPIN);
262     					DELAY(1000);
263   				}
264 			} else
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			    "%d: dev:%s, flags:%08lx, blkno:%ld, lblkno:%ld\n",
285				    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 */
330static void
331shutdown_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 */
352static void
353shutdown_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		cngetc();
378	}
379}
380
381/*
382 * Everything done, now reset
383 */
384static void
385shutdown_reset(void *junk, int howto)
386{
387	printf("Rebooting...\n");
388	DELAY(1000000);	/* wait 1 sec for printf's to complete and be read */
389	/* cpu_boot(howto); */ /* doesn't do anything at the moment */
390	cpu_reset();
391	/* NOTREACHED */ /* assuming reset worked */
392}
393
394/*
395 * Magic number for savecore
396 *
397 * exported (symorder) and used at least by savecore(8)
398 *
399 */
400static u_long const	dumpmag = 0x8fca0101UL;
401
402static int	dumpsize = 0;		/* also for savecore */
403
404static int	dodump = 1;
405
406SYSCTL_INT(_machdep, OID_AUTO, do_dump, CTLFLAG_RW, &dodump, 0,
407    "Try to perform coredump on kernel panic");
408
409static int
410setdumpdev(dev_t dev)
411{
412	int psize;
413	long newdumplo;
414
415	if (dev == NODEV) {
416		dumpdev = dev;
417		return (0);
418	}
419	if (devsw(dev) == NULL)
420		return (ENXIO);		/* XXX is this right? */
421	if (devsw(dev)->d_psize == NULL)
422		return (ENXIO);		/* XXX should be ENODEV ? */
423	psize = devsw(dev)->d_psize(dev);
424	if (psize == -1)
425		return (ENXIO);		/* XXX should be ENODEV ? */
426	/*
427	 * XXX should clean up checking in dumpsys() to be more like this.
428	 */
429	newdumplo = psize - Maxmem * PAGE_SIZE / DEV_BSIZE;
430	if (newdumplo < 0)
431		return (ENOSPC);
432	dumpdev = dev;
433	dumplo = newdumplo;
434	return (0);
435}
436
437
438/* ARGSUSED */
439static void
440dump_conf(void *dummy)
441{
442	if (setdumpdev(dumpdev) != 0)
443		dumpdev = NODEV;
444}
445
446SYSINIT(dump_conf, SI_SUB_DUMP_CONF, SI_ORDER_FIRST, dump_conf, NULL)
447
448static int
449sysctl_kern_dumpdev(SYSCTL_HANDLER_ARGS)
450{
451	int error;
452	udev_t ndumpdev;
453
454	ndumpdev = dev2udev(dumpdev);
455	error = sysctl_handle_opaque(oidp, &ndumpdev, sizeof ndumpdev, req);
456	if (error == 0 && req->newptr != NULL)
457		error = setdumpdev(udev2dev(ndumpdev, 0));
458	return (error);
459}
460
461SYSCTL_PROC(_kern, KERN_DUMPDEV, dumpdev, CTLTYPE_OPAQUE|CTLFLAG_RW,
462	0, sizeof dumpdev, sysctl_kern_dumpdev, "T,dev_t", "");
463
464/*
465 * Doadump comes here after turning off memory management and
466 * getting on the dump stack, either when called above, or by
467 * the auto-restart code.
468 */
469static void
470dumpsys(void)
471{
472	int	error;
473
474	savectx(&dumppcb);
475	if (dumping++) {
476		printf("Dump already in progress, bailing...\n");
477		return;
478	}
479	if (!dodump)
480		return;
481	if (dumpdev == NODEV)
482		return;
483	if (!(devsw(dumpdev)))
484		return;
485	if (!(devsw(dumpdev)->d_dump))
486		return;
487	dumpsize = Maxmem;
488	printf("\ndumping to dev %s, offset %ld\n", devtoname(dumpdev), dumplo);
489	printf("dump ");
490	error = (*devsw(dumpdev)->d_dump)(dumpdev);
491	if (error == 0) {
492		printf("succeeded\n");
493		return;
494	}
495	printf("failed, reason: ");
496	switch (error) {
497	case ENODEV:
498		printf("device doesn't support a dump routine\n");
499		break;
500
501	case ENXIO:
502		printf("device bad\n");
503		break;
504
505	case EFAULT:
506		printf("device not ready\n");
507		break;
508
509	case EINVAL:
510		printf("area improper\n");
511		break;
512
513	case EIO:
514		printf("i/o error\n");
515		break;
516
517	case EINTR:
518		printf("aborted from console\n");
519		break;
520
521	default:
522		printf("unknown, error = %d\n", error);
523		break;
524	}
525}
526
527/*
528 * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
529 * and then reboots.  If we are called twice, then we avoid trying to sync
530 * the disks as this often leads to recursive panics.
531 */
532void
533panic(const char *fmt, ...)
534{
535	int bootopt;
536	va_list ap;
537	static char buf[256];
538
539#ifdef SMP
540	/* Only 1 CPU can panic at a time */
541	s_lock(&panic_lock);
542#endif
543
544	bootopt = RB_AUTOBOOT | RB_DUMP;
545	if (panicstr)
546		bootopt |= RB_NOSYNC;
547	else
548		panicstr = fmt;
549
550	va_start(ap, fmt);
551	(void)vsnprintf(buf, sizeof(buf), fmt, ap);
552	if (panicstr == fmt)
553		panicstr = buf;
554	va_end(ap);
555	printf("panic: %s\n", buf);
556#ifdef SMP
557	/* two seperate prints in case of an unmapped page and trap */
558	printf("cpuid = %d; ", cpuid);
559	printf("lapic.id = %08x\n", lapic.id);
560#endif
561
562#if defined(DDB)
563	if (debugger_on_panic)
564		Debugger ("panic");
565#endif
566	boot(bootopt);
567}
568
569/*
570 * Support for poweroff delay.
571 */
572#ifndef POWEROFF_DELAY
573# define POWEROFF_DELAY 5000
574#endif
575static int poweroff_delay = POWEROFF_DELAY;
576
577SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
578	&poweroff_delay, 0, "");
579
580static void
581poweroff_wait(void *junk, int howto)
582{
583	if(!(howto & RB_POWEROFF) || poweroff_delay <= 0)
584		return;
585	DELAY(poweroff_delay * 1000);
586}
587
588/*
589 * Some system processes (e.g. syncer) need to be stopped at appropriate
590 * points in their main loops prior to a system shutdown, so that they
591 * won't interfere with the shutdown process (e.g. by holding a disk buf
592 * to cause sync to fail).  For each of these system processes, register
593 * shutdown_kproc() as a handler for one of shutdown events.
594 */
595static int kproc_shutdown_wait = 60;
596SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
597    &kproc_shutdown_wait, 0, "");
598
599void
600shutdown_kproc(void *arg, int howto)
601{
602	struct proc *p;
603	int error;
604
605	if (panicstr)
606		return;
607
608	p = (struct proc *)arg;
609	printf("Waiting (max %d seconds) for system process `%s' to stop...",
610	    kproc_shutdown_wait, p->p_comm);
611	error = suspend_kproc(p, kproc_shutdown_wait * hz);
612
613	if (error == EWOULDBLOCK)
614		printf("timed out\n");
615	else
616		printf("stopped\n");
617}
618