xref: /freebsd/sys/kern/kern_shutdown.c (revision 0640d357f29fb1c0daaaffadd0416c5981413afd)
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  * $Id: kern_shutdown.c,v 1.40 1998/09/20 16:50:31 dt Exp $
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/buf.h>
50 #include <sys/reboot.h>
51 #include <sys/proc.h>
52 #include <sys/malloc.h>
53 #include <sys/kernel.h>
54 #include <sys/mount.h>
55 #include <sys/queue.h>
56 #include <sys/sysctl.h>
57 #include <sys/conf.h>
58 #include <sys/sysproto.h>
59 
60 #include <machine/pcb.h>
61 #include <machine/clock.h>
62 #include <machine/cons.h>
63 #include <machine/md_var.h>
64 #ifdef SMP
65 #include <machine/smp.h>		/* smp_active, cpuid */
66 #endif
67 
68 #include <sys/signalvar.h>
69 
70 #ifndef PANIC_REBOOT_WAIT_TIME
71 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
72 #endif
73 
74 /*
75  * Note that stdarg.h and the ANSI style va_start macro is used for both
76  * ANSI and traditional C compilers.
77  */
78 #include <machine/stdarg.h>
79 
80 #ifdef DDB
81 #ifdef DDB_UNATTENDED
82 static int debugger_on_panic = 0;
83 #else
84 static int debugger_on_panic = 1;
85 #endif
86 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic, CTLFLAG_RW,
87 	&debugger_on_panic, 0, "");
88 #endif
89 
90 #ifdef	HW_WDOG
91 /*
92  * If there is a hardware watchdog, point this at the function needed to
93  * hold it off.
94  * It's needed when the kernel needs to do some lengthy operations.
95  * e.g. in wd.c when dumping core.. It's most annoying to have
96  * your precious core-dump only half written because the wdog kicked in.
97  */
98 watchdog_tickle_fn wdog_tickler = NULL;
99 #endif	/* HW_WDOG */
100 
101 /*
102  * Variable panicstr contains argument to first call to panic; used as flag
103  * to indicate that the kernel has already called panic.
104  */
105 const char *panicstr;
106 
107 /*
108  * callout list for things to do a shutdown
109  */
110 typedef struct shutdown_list_element {
111 	LIST_ENTRY(shutdown_list_element) links;
112 	bootlist_fn function;
113 	void *arg;
114 	int priority;
115 } *sle_p;
116 
117 /*
118  * There are three shutdown lists. Some things need to be shut down
119  * earlier than others.
120  */
121 LIST_HEAD(shutdown_list, shutdown_list_element);
122 
123 static struct shutdown_list shutdown_lists[SHUTDOWN_FINAL + 1];
124 
125 static void boot __P((int)) __dead2;
126 static void dumpsys __P((void));
127 
128 #ifndef _SYS_SYSPROTO_H_
129 struct reboot_args {
130 	int	opt;
131 };
132 #endif
133 /* ARGSUSED */
134 
135 /*
136  * The system call that results in a reboot
137  */
138 int
139 reboot(p, uap)
140 	struct proc *p;
141 	struct reboot_args *uap;
142 {
143 	int error;
144 
145 	if ((error = suser(p->p_ucred, &p->p_acflag)))
146 		return (error);
147 
148 	boot(uap->opt);
149 	return (0);
150 }
151 
152 /*
153  * Called by events that want to shut down.. e.g  <CTL><ALT><DEL> on a PC
154  */
155 void
156 shutdown_nice()
157 {
158 	/* Send a signal to init(8) and have it shutdown the world */
159 	if (initproc != NULL) {
160 		psignal(initproc, SIGINT);
161 	} else {
162 		/* No init(8) running, so simply reboot */
163 		boot(RB_NOSYNC);
164 	}
165 	return;
166 }
167 static int	waittime = -1;
168 static struct pcb dumppcb;
169 
170 /*
171  *  Go through the rigmarole of shutting down..
172  * this used to be in machdep.c but I'll be dammned if I could see
173  * anything machine dependant in it.
174  */
175 static void
176 boot(howto)
177 	int howto;
178 {
179 	sle_p ep;
180 
181 #ifdef SMP
182 	if (smp_active) {
183 		printf("boot() called on cpu#%d\n", cpuid);
184 	}
185 #endif
186 	/*
187 	 * Do any callouts that should be done BEFORE syncing the filesystems.
188 	 */
189 	LIST_FOREACH(ep, &shutdown_lists[SHUTDOWN_PRE_SYNC], links)
190 		(*ep->function)(howto, ep->arg);
191 
192 	/*
193 	 * Now sync filesystems
194 	 */
195 	if (!cold && (howto & RB_NOSYNC) == 0 && waittime < 0) {
196 		register struct buf *bp;
197 		int iter, nbusy;
198 
199 		waittime = 0;
200 		printf("\nsyncing disks... ");
201 
202 		sync(&proc0, NULL);
203 
204 		/*
205 		 * With soft updates, some buffers that are
206 		 * written will be remarked as dirty until other
207 		 * buffers are written.
208 		 */
209 		for (iter = 0; iter < 20; iter++) {
210 			nbusy = 0;
211 			for (bp = &buf[nbuf]; --bp >= buf; ) {
212 				if ((bp->b_flags & (B_BUSY | B_INVAL))
213 						== B_BUSY) {
214 					nbusy++;
215 				} else if ((bp->b_flags & (B_DELWRI | B_INVAL))
216 						== B_DELWRI) {
217 					/* bawrite(bp);*/
218 					nbusy++;
219 				}
220 			}
221 			if (nbusy == 0)
222 				break;
223 			printf("%d ", nbusy);
224 			sync(&proc0, NULL);
225 			DELAY(50000 * iter);
226 		}
227 		if (nbusy) {
228 			/*
229 			 * Failed to sync all blocks. Indicate this and don't
230 			 * unmount filesystems (thus forcing an fsck on reboot).
231 			 */
232 			printf("giving up\n");
233 #ifdef SHOW_BUSYBUFS
234 			nbusy = 0;
235 			for (bp = &buf[nbuf]; --bp >= buf; ) {
236 				if ((bp->b_flags & (B_BUSY | B_INVAL))
237 						== B_BUSY) {
238 					nbusy++;
239 					printf(
240 			"%d: dev:%08lx, flags:%08lx, blkno:%ld, lblkno:%ld\n",
241 					    nbusy, (u_long)bp->b_dev,
242 					    bp->b_flags, (long)bp->b_blkno,
243 					    (long)bp->b_lblkno);
244 				}
245 			}
246 			DELAY(5000000);	/* 5 seconds */
247 #endif
248 		} else {
249 			printf("done\n");
250 			/*
251 			 * Unmount filesystems
252 			 */
253 			if (panicstr == 0)
254 				vfs_unmountall();
255 		}
256 		DELAY(100000);		/* wait for console output to finish */
257 	}
258 
259 	/*
260 	 * Ok, now do things that assume all filesystem activity has
261 	 * been completed.
262 	 */
263 	LIST_FOREACH(ep, &shutdown_lists[SHUTDOWN_POST_SYNC], links)
264 		(*ep->function)(howto, ep->arg);
265 	splhigh();
266 	if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold) {
267 		savectx(&dumppcb);
268 #ifdef __i386__
269 		dumppcb.pcb_cr3 = rcr3();
270 #endif
271 		dumpsys();
272 	}
273 
274 	/* Now that we're going to really halt the system... */
275 	LIST_FOREACH(ep, &shutdown_lists[SHUTDOWN_FINAL], links)
276 		(*ep->function)(howto, ep->arg);
277 
278 	if (howto & RB_HALT) {
279 		printf("\n");
280 		printf("The operating system has halted.\n");
281 		printf("Please press any key to reboot.\n\n");
282 		switch (cngetc()) {
283 		case -1:		/* No console, just die */
284 			cpu_halt();
285 			/* NOTREACHED */
286 		default:
287 			howto &= ~RB_HALT;
288 			break;
289 		}
290 	} else if (howto & RB_DUMP) {
291 		/* System Paniced */
292 
293 		if (PANIC_REBOOT_WAIT_TIME != 0) {
294 			if (PANIC_REBOOT_WAIT_TIME != -1) {
295 				int loop;
296 				printf("Automatic reboot in %d seconds - "
297 				       "press a key on the console to abort\n",
298 					PANIC_REBOOT_WAIT_TIME);
299 				for (loop = PANIC_REBOOT_WAIT_TIME * 10;
300 				     loop > 0; --loop) {
301 					DELAY(1000 * 100); /* 1/10th second */
302 					/* Did user type a key? */
303 					if (cncheckc() != -1)
304 						break;
305 				}
306 				if (!loop)
307 					goto die;
308 			}
309 		} else { /* zero time specified - reboot NOW */
310 			goto die;
311 		}
312 		printf("--> Press a key on the console to reboot <--\n");
313 		cngetc();
314 	}
315 die:
316 	printf("Rebooting...\n");
317 	DELAY(1000000);	/* wait 1 sec for printf's to complete and be read */
318 	/* cpu_boot(howto); */ /* doesn't do anything at the moment */
319 	cpu_reset();
320 	for(;;) ;
321 	/* NOTREACHED */
322 }
323 
324 /*
325  * Magic number for savecore
326  *
327  * exported (symorder) and used at least by savecore(8)
328  *
329  */
330 static u_long const	dumpmag = 0x8fca0101UL;
331 
332 static int	dumpsize = 0;		/* also for savecore */
333 
334 static int	dodump = 1;
335 SYSCTL_INT(_machdep, OID_AUTO, do_dump, CTLFLAG_RW, &dodump, 0, "");
336 
337 /* ARGSUSED */
338 static void dump_conf __P((void *dummy));
339 static void
340 dump_conf(dummy)
341 	void *dummy;
342 {
343 	cpu_dumpconf();
344 }
345 SYSINIT(dump_conf, SI_SUB_DUMP_CONF, SI_ORDER_FIRST, dump_conf, NULL)
346 
347 /*
348  * Doadump comes here after turning off memory management and
349  * getting on the dump stack, either when called above, or by
350  * the auto-restart code.
351  */
352 static void
353 dumpsys(void)
354 {
355 
356 	if (!dodump)
357 		return;
358 	if (dumpdev == NODEV)
359 		return;
360 	if (!(bdevsw[major(dumpdev)]))
361 		return;
362 	if (!(bdevsw[major(dumpdev)]->d_dump))
363 		return;
364 	dumpsize = Maxmem;
365 	printf("\ndumping to dev %lx, offset %ld\n", (u_long)dumpdev, dumplo);
366 	printf("dump ");
367 	switch ((*bdevsw[major(dumpdev)]->d_dump)(dumpdev)) {
368 
369 	case ENXIO:
370 		printf("device bad\n");
371 		break;
372 
373 	case EFAULT:
374 		printf("device not ready\n");
375 		break;
376 
377 	case EINVAL:
378 		printf("area improper\n");
379 		break;
380 
381 	case EIO:
382 		printf("i/o error\n");
383 		break;
384 
385 	case EINTR:
386 		printf("aborted from console\n");
387 		break;
388 
389 	default:
390 		printf("succeeded\n");
391 		break;
392 	}
393 }
394 
395 /*
396  * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
397  * and then reboots.  If we are called twice, then we avoid trying to sync
398  * the disks as this often leads to recursive panics.
399  */
400 void
401 panic(const char *fmt, ...)
402 {
403 	int bootopt;
404 	va_list ap;
405 	static char buf[256];
406 
407 	bootopt = RB_AUTOBOOT | RB_DUMP;
408 	if (panicstr)
409 		bootopt |= RB_NOSYNC;
410 	else
411 		panicstr = fmt;
412 
413 	va_start(ap, fmt);
414 	(void)vsprintf(buf, fmt, ap);
415 	if (panicstr == fmt)
416 		panicstr = buf;
417 	va_end(ap);
418 	printf("panic: %s\n", buf);
419 #ifdef SMP
420 	/* three seperate prints in case of an unmapped page and trap */
421 	printf("mp_lock = %08x; ", mp_lock);
422 	printf("cpuid = %d; ", cpuid);
423 	printf("lapic.id = %08x\n", lapic.id);
424 #endif
425 
426 #if defined(DDB)
427 	if (debugger_on_panic)
428 		Debugger ("panic");
429 #endif
430 	boot(bootopt);
431 }
432 
433 /*
434  * Three routines to handle adding/deleting items on the
435  * shutdown callout lists
436  *
437  * at_shutdown():
438  * Take the arguments given and put them onto the shutdown callout list.
439  * However first make sure that it's not already there.
440  * returns 0 on success.
441  */
442 int
443 at_shutdown(bootlist_fn function, void *arg, int queue)
444 {
445 	return(at_shutdown_pri(function, arg, queue, SHUTDOWN_PRI_DEFAULT));
446 }
447 
448 /*
449  * at_shutdown_pri():
450  * Take the arguments given and put them onto the shutdown callout list
451  * with the given execution priority.
452  * returns 0 on success.
453  */
454 int
455 at_shutdown_pri(bootlist_fn function, void *arg, int queue, int pri)
456 {
457 	sle_p ep, ip;
458 
459 	if (queue < SHUTDOWN_PRE_SYNC
460 	 || queue > SHUTDOWN_FINAL) {
461 		printf("at_shutdown: bad exit callout queue %d specified\n",
462 		       queue);
463 		return (EINVAL);
464 	}
465 	if (rm_at_shutdown(function, arg))
466 		printf("at_shutdown: exit callout entry was already present\n");
467 	ep = malloc(sizeof(*ep), M_TEMP, M_NOWAIT);
468 	if (ep == NULL)
469 		return (ENOMEM);
470 	ep->function = function;
471 	ep->arg = arg;
472 	ep->priority = pri;
473 
474 	/* Sort into list of items on this queue */
475 	ip = LIST_FIRST(&shutdown_lists[queue]);
476 	if (ip == NULL) {
477 		LIST_INSERT_HEAD(&shutdown_lists[queue], ep, links);
478 	} else {
479 		for (; LIST_NEXT(ip, links) != NULL; ip = LIST_NEXT(ip, links)) {
480 			if (ep->priority < ip->priority) {
481 				LIST_INSERT_BEFORE(ip, ep, links);
482 				ep = NULL;
483 				break;
484 			}
485 		}
486 		if (ep != NULL)
487 			LIST_INSERT_AFTER(ip, ep, links);
488 	}
489 	return (0);
490 }
491 
492 /*
493  * Scan the exit callout lists for the given items and remove them.
494  * Returns the number of items removed.
495  */
496 int
497 rm_at_shutdown(bootlist_fn function, void *arg)
498 {
499 	sle_p ep;
500 	int   count;
501 	int   queue;
502 
503 	count = 0;
504 	for (queue = SHUTDOWN_PRE_SYNC; queue < SHUTDOWN_FINAL; queue++) {
505 		LIST_FOREACH(ep, &shutdown_lists[queue], links) {
506 			if ((ep->function == function) && (ep->arg == arg)) {
507 				LIST_REMOVE(ep, links);
508 				free(ep, M_TEMP);
509 				count++;
510 			}
511 		}
512 	}
513 	return (count);
514 }
515