xref: /freebsd/sys/kern/kern_shutdown.c (revision 4cf49a43559ed9fdad601bdcccd2c55963008675)
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$
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
83 int debugger_on_panic = 0;
84 #else
85 int debugger_on_panic = 1;
86 #endif
87 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic, CTLFLAG_RW,
88 	&debugger_on_panic, 0, "Run debugger on kernel panic");
89 #endif
90 
91 SYSCTL_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  */
101 watchdog_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  */
108 const char *panicstr;
109 
110 static void boot __P((int)) __dead2;
111 static void dumpsys __P((void));
112 static int setdumpdev __P((dev_t dev));
113 static void poweroff_wait __P((void *, int));
114 static void shutdown_halt __P((void *junk, int howto));
115 static void shutdown_panic __P((void *junk, int howto));
116 static void shutdown_reset __P((void *junk, int howto));
117 
118 /* register various local shutdown events */
119 static void
120 shutdown_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 
128 SYSINIT(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  */
135 int
136 reboot(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  */
152 void
153 shutdown_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 }
164 static int	waittime = -1;
165 static 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  */
172 static void
173 boot(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 		/*
223 		 * Count only busy local buffers to prevent forcing
224 		 * a fsck if we're just a client of a wedged NFS server
225 		 */
226 		nbusy = 0;
227 		for (bp = &buf[nbuf]; --bp >= buf; ) {
228 			if (((bp->b_flags&B_INVAL) == 0 && BUF_REFCNT(bp)) ||
229 			    ((bp->b_flags & (B_DELWRI|B_INVAL)) == B_DELWRI)) {
230 				if (bp->b_dev == NODEV)
231 					CIRCLEQ_REMOVE(&mountlist,
232 					    bp->b_vp->v_mount, mnt_list);
233 				else
234 					nbusy++;
235 			}
236 
237 
238 		}
239 		if (nbusy) {
240 			/*
241 			 * Failed to sync all blocks. Indicate this and don't
242 			 * unmount filesystems (thus forcing an fsck on reboot).
243 			 */
244 			printf("giving up\n");
245 #ifdef SHOW_BUSYBUFS
246 			nbusy = 0;
247 			for (bp = &buf[nbuf]; --bp >= buf; ) {
248 				if ((bp->b_flags & B_INVAL) == 0 &&
249 				    BUF_REFCNT(bp) > 0) {
250 					nbusy++;
251 					printf(
252 			"%d: dev:%s, flags:%08lx, blkno:%ld, lblkno:%ld\n",
253 					    nbusy, devtoname(bp->b_dev),
254 					    bp->b_flags, (long)bp->b_blkno,
255 					    (long)bp->b_lblkno);
256 				}
257 			}
258 			DELAY(5000000);	/* 5 seconds */
259 #endif
260 		} else {
261 			printf("done\n");
262 			/*
263 			 * Unmount filesystems
264 			 */
265 			if (panicstr == 0)
266 				vfs_unmountall();
267 		}
268 		DELAY(100000);		/* wait for console output to finish */
269 	}
270 
271 	/*
272 	 * Ok, now do things that assume all filesystem activity has
273 	 * been completed.
274 	 */
275 	EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
276 	splhigh();
277 	if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold) {
278 		savectx(&dumppcb);
279 #ifdef __i386__
280 		dumppcb.pcb_cr3 = rcr3();
281 #endif
282 		dumpsys();
283 	}
284 
285 	/* Now that we're going to really halt the system... */
286 	EVENTHANDLER_INVOKE(shutdown_final, howto);
287 
288 	for(;;) ;	/* safety against shutdown_reset not working */
289 	/* NOTREACHED */
290 }
291 
292 /*
293  * If the shutdown was a clean halt, behave accordingly.
294  */
295 static void
296 shutdown_halt(void *junk, int howto)
297 {
298 	if (howto & RB_HALT) {
299 		printf("\n");
300 		printf("The operating system has halted.\n");
301 		printf("Please press any key to reboot.\n\n");
302 		switch (cngetc()) {
303 		case -1:		/* No console, just die */
304 			cpu_halt();
305 			/* NOTREACHED */
306 		default:
307 			howto &= ~RB_HALT;
308 			break;
309 		}
310 	}
311 }
312 
313 /*
314  * Check to see if the system paniced, pause and then reboot
315  * according to the specified delay.
316  */
317 static void
318 shutdown_panic(void *junk, int howto)
319 {
320 	int loop;
321 
322 	if (howto & RB_DUMP) {
323 		if (PANIC_REBOOT_WAIT_TIME != 0) {
324 			if (PANIC_REBOOT_WAIT_TIME != -1) {
325 				printf("Automatic reboot in %d seconds - "
326 				       "press a key on the console to abort\n",
327 					PANIC_REBOOT_WAIT_TIME);
328 				for (loop = PANIC_REBOOT_WAIT_TIME * 10;
329 				     loop > 0; --loop) {
330 					DELAY(1000 * 100); /* 1/10th second */
331 					/* Did user type a key? */
332 					if (cncheckc() != -1)
333 						break;
334 				}
335 				if (!loop)
336 					return;
337 			}
338 		} else { /* zero time specified - reboot NOW */
339 			return;
340 		}
341 		printf("--> Press a key on the console to reboot <--\n");
342 		cngetc();
343 	}
344 }
345 
346 /*
347  * Everything done, now reset
348  */
349 static void
350 shutdown_reset(void *junk, int howto)
351 {
352 	printf("Rebooting...\n");
353 	DELAY(1000000);	/* wait 1 sec for printf's to complete and be read */
354 	/* cpu_boot(howto); */ /* doesn't do anything at the moment */
355 	cpu_reset();
356 	/* NOTREACHED */ /* assuming reset worked */
357 }
358 
359 /*
360  * Magic number for savecore
361  *
362  * exported (symorder) and used at least by savecore(8)
363  *
364  */
365 static u_long const	dumpmag = 0x8fca0101UL;
366 
367 static int	dumpsize = 0;		/* also for savecore */
368 
369 static int	dodump = 1;
370 
371 SYSCTL_INT(_machdep, OID_AUTO, do_dump, CTLFLAG_RW, &dodump, 0,
372     "Try to perform coredump on kernel panic");
373 
374 static int
375 setdumpdev(dev)
376 	dev_t dev;
377 {
378 	int psize;
379 	long newdumplo;
380 
381 	if (dev == NODEV) {
382 		dumpdev = dev;
383 		return (0);
384 	}
385 	if (devsw(dev) == NULL)
386 		return (ENXIO);		/* XXX is this right? */
387 	if (devsw(dev)->d_psize == NULL)
388 		return (ENXIO);		/* XXX should be ENODEV ? */
389 	psize = devsw(dev)->d_psize(dev);
390 	if (psize == -1)
391 		return (ENXIO);		/* XXX should be ENODEV ? */
392 	/*
393 	 * XXX should clean up checking in dumpsys() to be more like this.
394 	 */
395 	newdumplo = psize - Maxmem * PAGE_SIZE / DEV_BSIZE;
396 	if (newdumplo < 0)
397 		return (ENOSPC);
398 	dumpdev = dev;
399 	dumplo = newdumplo;
400 	return (0);
401 }
402 
403 
404 /* ARGSUSED */
405 static void dump_conf __P((void *dummy));
406 static void
407 dump_conf(dummy)
408 	void *dummy;
409 {
410 	if (setdumpdev(dumpdev) != 0)
411 		dumpdev = NODEV;
412 }
413 
414 SYSINIT(dump_conf, SI_SUB_DUMP_CONF, SI_ORDER_FIRST, dump_conf, NULL)
415 
416 static int
417 sysctl_kern_dumpdev SYSCTL_HANDLER_ARGS
418 {
419 	int error;
420 	udev_t ndumpdev;
421 
422 	ndumpdev = dev2budev(dumpdev);
423 	error = sysctl_handle_opaque(oidp, &ndumpdev, sizeof ndumpdev, req);
424 	if (error == 0 && req->newptr != NULL)
425 		error = setdumpdev(udev2dev(ndumpdev, 1));
426 	return (error);
427 }
428 
429 SYSCTL_PROC(_kern, KERN_DUMPDEV, dumpdev, CTLTYPE_OPAQUE|CTLFLAG_RW,
430 	0, sizeof dumpdev, sysctl_kern_dumpdev, "T,dev_t", "");
431 
432 /*
433  * Doadump comes here after turning off memory management and
434  * getting on the dump stack, either when called above, or by
435  * the auto-restart code.
436  */
437 static void
438 dumpsys(void)
439 {
440 	int	error;
441 	static int dumping;
442 
443 	if (dumping++) {
444 		printf("Dump already in progress, bailing...\n");
445 		return;
446 	}
447 	if (!dodump)
448 		return;
449 	if (dumpdev == NODEV)
450 		return;
451 	if (!(devsw(dumpdev)))
452 		return;
453 	if (!(devsw(dumpdev)->d_dump))
454 		return;
455 	dumpsize = Maxmem;
456 	printf("\ndumping to dev %s, offset %ld\n", devtoname(dumpdev), dumplo);
457 	printf("dump ");
458 	error = (*devsw(dumpdev)->d_dump)(dumpdev);
459 	if (error == 0) {
460 		printf("succeeded\n");
461 		return;
462 	}
463 	printf("failed, reason: ");
464 	switch (error) {
465 	case ENODEV:
466 		printf("device doesn't support a dump routine\n");
467 		break;
468 
469 	case ENXIO:
470 		printf("device bad\n");
471 		break;
472 
473 	case EFAULT:
474 		printf("device not ready\n");
475 		break;
476 
477 	case EINVAL:
478 		printf("area improper\n");
479 		break;
480 
481 	case EIO:
482 		printf("i/o error\n");
483 		break;
484 
485 	case EINTR:
486 		printf("aborted from console\n");
487 		break;
488 
489 	default:
490 		printf("unknown, error = %d\n", error);
491 		break;
492 	}
493 }
494 
495 /*
496  * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
497  * and then reboots.  If we are called twice, then we avoid trying to sync
498  * the disks as this often leads to recursive panics.
499  */
500 void
501 panic(const char *fmt, ...)
502 {
503 	int bootopt;
504 	va_list ap;
505 	static char buf[256];
506 
507 	bootopt = RB_AUTOBOOT | RB_DUMP;
508 	if (panicstr)
509 		bootopt |= RB_NOSYNC;
510 	else
511 		panicstr = fmt;
512 
513 	va_start(ap, fmt);
514 	(void)vsnprintf(buf, sizeof(buf), fmt, ap);
515 	if (panicstr == fmt)
516 		panicstr = buf;
517 	va_end(ap);
518 	printf("panic: %s\n", buf);
519 #ifdef SMP
520 	/* three seperate prints in case of an unmapped page and trap */
521 	printf("mp_lock = %08x; ", mp_lock);
522 	printf("cpuid = %d; ", cpuid);
523 	printf("lapic.id = %08x\n", lapic.id);
524 #endif
525 
526 #if defined(DDB)
527 	if (debugger_on_panic)
528 		Debugger ("panic");
529 #endif
530 	boot(bootopt);
531 }
532 
533 /*
534  * Support for poweroff delay.
535  */
536 static int poweroff_delay = 0;
537 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
538 	&poweroff_delay, 0, "");
539 
540 static void
541 poweroff_wait(void *junk, int howto)
542 {
543 	if(!(howto & RB_POWEROFF) || poweroff_delay <= 0)
544 		return;
545 	DELAY(poweroff_delay * 1000);
546 }
547