xref: /freebsd/sys/kern/kern_shutdown.c (revision 262e143bd46171a6415a5b28af260a5efa2a3db8)
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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_shutdown.c	8.3 (Berkeley) 1/21/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_kdb.h"
41 #include "opt_mac.h"
42 #include "opt_panic.h"
43 #include "opt_show_busybufs.h"
44 #include "opt_sched.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/bio.h>
49 #include <sys/buf.h>
50 #include <sys/conf.h>
51 #include <sys/cons.h>
52 #include <sys/eventhandler.h>
53 #include <sys/kdb.h>
54 #include <sys/kernel.h>
55 #include <sys/kthread.h>
56 #include <sys/mac.h>
57 #include <sys/malloc.h>
58 #include <sys/mount.h>
59 #include <sys/proc.h>
60 #include <sys/reboot.h>
61 #include <sys/resourcevar.h>
62 #include <sys/sched.h>
63 #include <sys/smp.h>		/* smp_active */
64 #include <sys/sysctl.h>
65 #include <sys/sysproto.h>
66 
67 #include <machine/cpu.h>
68 #include <machine/pcb.h>
69 #include <machine/smp.h>
70 
71 #include <sys/signalvar.h>
72 
73 #ifndef PANIC_REBOOT_WAIT_TIME
74 #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
75 #endif
76 
77 /*
78  * Note that stdarg.h and the ANSI style va_start macro is used for both
79  * ANSI and traditional C compilers.
80  */
81 #include <machine/stdarg.h>
82 
83 #ifdef KDB
84 #ifdef KDB_UNATTENDED
85 int debugger_on_panic = 0;
86 #else
87 int debugger_on_panic = 1;
88 #endif
89 SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic, CTLFLAG_RW,
90 	&debugger_on_panic, 0, "Run debugger on kernel panic");
91 
92 #ifdef KDB_TRACE
93 int trace_on_panic = 1;
94 #else
95 int trace_on_panic = 0;
96 #endif
97 SYSCTL_INT(_debug, OID_AUTO, trace_on_panic, CTLFLAG_RW,
98 	&trace_on_panic, 0, "Print stack trace on kernel panic");
99 #endif /* KDB */
100 
101 int sync_on_panic = 0;
102 SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RW,
103 	&sync_on_panic, 0, "Do a sync before rebooting from a panic");
104 
105 SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0, "Shutdown environment");
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  */
111 const char *panicstr;
112 
113 int dumping;				/* system is dumping */
114 static struct dumperinfo dumper;	/* our selected dumper */
115 
116 /* Context information for dump-debuggers. */
117 static struct pcb dumppcb;		/* Registers. */
118 static lwpid_t dumptid;			/* Thread ID. */
119 
120 static void boot(int) __dead2;
121 static void poweroff_wait(void *, int);
122 static void shutdown_halt(void *junk, int howto);
123 static void shutdown_panic(void *junk, int howto);
124 static void shutdown_reset(void *junk, int howto);
125 
126 /* register various local shutdown events */
127 static void
128 shutdown_conf(void *unused)
129 {
130 
131 	EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
132 	    SHUTDOWN_PRI_FIRST);
133 	EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
134 	    SHUTDOWN_PRI_LAST + 100);
135 	EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
136 	    SHUTDOWN_PRI_LAST + 100);
137 	EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
138 	    SHUTDOWN_PRI_LAST + 200);
139 }
140 
141 SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL)
142 
143 /*
144  * The system call that results in a reboot
145  *
146  * MPSAFE
147  */
148 /* ARGSUSED */
149 int
150 reboot(struct thread *td, struct reboot_args *uap)
151 {
152 	int error;
153 
154 	error = 0;
155 #ifdef MAC
156 	error = mac_check_system_reboot(td->td_ucred, uap->opt);
157 #endif
158 	if (error == 0)
159 		error = suser(td);
160 	if (error == 0) {
161 		mtx_lock(&Giant);
162 		boot(uap->opt);
163 		mtx_unlock(&Giant);
164 	}
165 	return (error);
166 }
167 
168 /*
169  * Called by events that want to shut down.. e.g  <CTL><ALT><DEL> on a PC
170  */
171 static int shutdown_howto = 0;
172 
173 void
174 shutdown_nice(int howto)
175 {
176 
177 	shutdown_howto = howto;
178 
179 	/* Send a signal to init(8) and have it shutdown the world */
180 	if (initproc != NULL) {
181 		PROC_LOCK(initproc);
182 		psignal(initproc, SIGINT);
183 		PROC_UNLOCK(initproc);
184 	} else {
185 		/* No init(8) running, so simply reboot */
186 		boot(RB_NOSYNC);
187 	}
188 	return;
189 }
190 static int	waittime = -1;
191 
192 static void
193 print_uptime(void)
194 {
195 	int f;
196 	struct timespec ts;
197 
198 	getnanouptime(&ts);
199 	printf("Uptime: ");
200 	f = 0;
201 	if (ts.tv_sec >= 86400) {
202 		printf("%ldd", (long)ts.tv_sec / 86400);
203 		ts.tv_sec %= 86400;
204 		f = 1;
205 	}
206 	if (f || ts.tv_sec >= 3600) {
207 		printf("%ldh", (long)ts.tv_sec / 3600);
208 		ts.tv_sec %= 3600;
209 		f = 1;
210 	}
211 	if (f || ts.tv_sec >= 60) {
212 		printf("%ldm", (long)ts.tv_sec / 60);
213 		ts.tv_sec %= 60;
214 		f = 1;
215 	}
216 	printf("%lds\n", (long)ts.tv_sec);
217 }
218 
219 static void
220 doadump(void)
221 {
222 
223 	/*
224 	 * Sometimes people have to call this from the kernel debugger.
225 	 * (if 'panic' can not dump)
226 	 * Give them a clue as to why they can't dump.
227 	 */
228 	if (dumper.dumper == NULL) {
229 		printf("Cannot dump. No dump device defined.\n");
230 		return;
231 	}
232 
233 	savectx(&dumppcb);
234 	dumptid = curthread->td_tid;
235 	dumping++;
236 	dumpsys(&dumper);
237 }
238 
239 static int
240 isbufbusy(struct buf *bp)
241 {
242 	if (((bp->b_flags & (B_INVAL | B_PERSISTENT)) == 0 &&
243 	    BUF_REFCNT(bp) > 0) ||
244 	    ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
245 		return (1);
246 	return (0);
247 }
248 
249 /*
250  * Shutdown the system cleanly to prepare for reboot, halt, or power off.
251  */
252 static void
253 boot(int howto)
254 {
255 	static int first_buf_printf = 1;
256 
257 #if defined(SMP)
258 	/*
259 	 * Bind us to CPU 0 so that all shutdown code runs there.  Some
260 	 * systems don't shutdown properly (i.e., ACPI power off) if we
261 	 * run on another processor.
262 	 */
263 	mtx_lock_spin(&sched_lock);
264 	sched_bind(curthread, 0);
265 	mtx_unlock_spin(&sched_lock);
266 	KASSERT(PCPU_GET(cpuid) == 0, ("boot: not running on cpu 0"));
267 #endif
268 
269 	/* collect extra flags that shutdown_nice might have set */
270 	howto |= shutdown_howto;
271 
272 	/* We are out of the debugger now. */
273 	kdb_active = 0;
274 
275 	/*
276 	 * Do any callouts that should be done BEFORE syncing the filesystems.
277 	 */
278 	EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
279 
280 	/*
281 	 * Now sync filesystems
282 	 */
283 	if (!cold && (howto & RB_NOSYNC) == 0 && waittime < 0) {
284 		register struct buf *bp;
285 		int iter, nbusy, pbusy;
286 #ifndef PREEMPTION
287 		int subiter;
288 #endif
289 
290 		waittime = 0;
291 
292 		sync(curthread, NULL);
293 
294 		/*
295 		 * With soft updates, some buffers that are
296 		 * written will be remarked as dirty until other
297 		 * buffers are written.
298 		 */
299 		for (iter = pbusy = 0; iter < 20; iter++) {
300 			nbusy = 0;
301 			for (bp = &buf[nbuf]; --bp >= buf; )
302 				if (isbufbusy(bp))
303 					nbusy++;
304 			if (nbusy == 0) {
305 				if (first_buf_printf)
306 					printf("All buffers synced.");
307 				break;
308 			}
309 			if (first_buf_printf) {
310 				printf("Syncing disks, buffers remaining... ");
311 				first_buf_printf = 0;
312 			}
313 			printf("%d ", nbusy);
314 			if (nbusy < pbusy)
315 				iter = 0;
316 			pbusy = nbusy;
317 			sync(curthread, NULL);
318 
319 #ifdef PREEMPTION
320 			/*
321 			 * Drop Giant and spin for a while to allow
322 			 * interrupt threads to run.
323 			 */
324 			DROP_GIANT();
325 			DELAY(50000 * iter);
326 			PICKUP_GIANT();
327 #else
328 			/*
329 			 * Drop Giant and context switch several times to
330 			 * allow interrupt threads to run.
331 			 */
332 			DROP_GIANT();
333 			for (subiter = 0; subiter < 50 * iter; subiter++) {
334 				mtx_lock_spin(&sched_lock);
335 				mi_switch(SW_VOL, NULL);
336 				mtx_unlock_spin(&sched_lock);
337 				DELAY(1000);
338 			}
339 			PICKUP_GIANT();
340 #endif
341 		}
342 		printf("\n");
343 		/*
344 		 * Count only busy local buffers to prevent forcing
345 		 * a fsck if we're just a client of a wedged NFS server
346 		 */
347 		nbusy = 0;
348 		for (bp = &buf[nbuf]; --bp >= buf; ) {
349 			if (isbufbusy(bp)) {
350 #if 0
351 /* XXX: This is bogus.  We should probably have a BO_REMOTE flag instead */
352 				if (bp->b_dev == NULL) {
353 					TAILQ_REMOVE(&mountlist,
354 					    bp->b_vp->v_mount, mnt_list);
355 					continue;
356 				}
357 #endif
358 				nbusy++;
359 #if defined(SHOW_BUSYBUFS) || defined(DIAGNOSTIC)
360 				printf(
361 			    "%d: bufobj:%p, flags:%0x, blkno:%ld, lblkno:%ld\n",
362 				    nbusy, bp->b_bufobj,
363 				    bp->b_flags, (long)bp->b_blkno,
364 				    (long)bp->b_lblkno);
365 #endif
366 			}
367 		}
368 		if (nbusy) {
369 			/*
370 			 * Failed to sync all blocks. Indicate this and don't
371 			 * unmount filesystems (thus forcing an fsck on reboot).
372 			 */
373 			printf("Giving up on %d buffers\n", nbusy);
374 			DELAY(5000000);	/* 5 seconds */
375 		} else {
376 			if (!first_buf_printf)
377 				printf("Final sync complete\n");
378 			/*
379 			 * Unmount filesystems
380 			 */
381 			if (panicstr == 0)
382 				vfs_unmountall();
383 		}
384 		DELAY(100000);		/* wait for console output to finish */
385 	}
386 
387 	print_uptime();
388 
389 	/*
390 	 * Ok, now do things that assume all filesystem activity has
391 	 * been completed.
392 	 */
393 	EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
394 
395 	/* XXX This doesn't disable interrupts any more.  Reconsider? */
396 	splhigh();
397 
398 	if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
399 		doadump();
400 
401 	/* Now that we're going to really halt the system... */
402 	EVENTHANDLER_INVOKE(shutdown_final, howto);
403 
404 	for(;;) ;	/* safety against shutdown_reset not working */
405 	/* NOTREACHED */
406 }
407 
408 /*
409  * If the shutdown was a clean halt, behave accordingly.
410  */
411 static void
412 shutdown_halt(void *junk, int howto)
413 {
414 
415 	if (howto & RB_HALT) {
416 		printf("\n");
417 		printf("The operating system has halted.\n");
418 		printf("Please press any key to reboot.\n\n");
419 		switch (cngetc()) {
420 		case -1:		/* No console, just die */
421 			cpu_halt();
422 			/* NOTREACHED */
423 		default:
424 			howto &= ~RB_HALT;
425 			break;
426 		}
427 	}
428 }
429 
430 /*
431  * Check to see if the system paniced, pause and then reboot
432  * according to the specified delay.
433  */
434 static void
435 shutdown_panic(void *junk, int howto)
436 {
437 	int loop;
438 
439 	if (howto & RB_DUMP) {
440 		if (PANIC_REBOOT_WAIT_TIME != 0) {
441 			if (PANIC_REBOOT_WAIT_TIME != -1) {
442 				printf("Automatic reboot in %d seconds - "
443 				       "press a key on the console to abort\n",
444 					PANIC_REBOOT_WAIT_TIME);
445 				for (loop = PANIC_REBOOT_WAIT_TIME * 10;
446 				     loop > 0; --loop) {
447 					DELAY(1000 * 100); /* 1/10th second */
448 					/* Did user type a key? */
449 					if (cncheckc() != -1)
450 						break;
451 				}
452 				if (!loop)
453 					return;
454 			}
455 		} else { /* zero time specified - reboot NOW */
456 			return;
457 		}
458 		printf("--> Press a key on the console to reboot,\n");
459 		printf("--> or switch off the system now.\n");
460 		cngetc();
461 	}
462 }
463 
464 /*
465  * Everything done, now reset
466  */
467 static void
468 shutdown_reset(void *junk, int howto)
469 {
470 
471 	printf("Rebooting...\n");
472 	DELAY(1000000);	/* wait 1 sec for printf's to complete and be read */
473 	/* cpu_boot(howto); */ /* doesn't do anything at the moment */
474 	cpu_reset();
475 	/* NOTREACHED */ /* assuming reset worked */
476 }
477 
478 #ifdef SMP
479 static u_int panic_cpu = NOCPU;
480 #endif
481 
482 /*
483  * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
484  * and then reboots.  If we are called twice, then we avoid trying to sync
485  * the disks as this often leads to recursive panics.
486  *
487  * MPSAFE
488  */
489 void
490 panic(const char *fmt, ...)
491 {
492 	struct thread *td = curthread;
493 	int bootopt, newpanic;
494 	va_list ap;
495 	static char buf[256];
496 
497 #ifdef SMP
498 	/*
499 	 * We don't want multiple CPU's to panic at the same time, so we
500 	 * use panic_cpu as a simple spinlock.  We have to keep checking
501 	 * panic_cpu if we are spinning in case the panic on the first
502 	 * CPU is canceled.
503 	 */
504 	if (panic_cpu != PCPU_GET(cpuid))
505 		while (atomic_cmpset_int(&panic_cpu, NOCPU,
506 		    PCPU_GET(cpuid)) == 0)
507 			while (panic_cpu != NOCPU)
508 				; /* nothing */
509 #endif
510 
511 	bootopt = RB_AUTOBOOT | RB_DUMP;
512 	newpanic = 0;
513 	if (panicstr)
514 		bootopt |= RB_NOSYNC;
515 	else {
516 		panicstr = fmt;
517 		newpanic = 1;
518 	}
519 
520 	va_start(ap, fmt);
521 	if (newpanic) {
522 		(void)vsnprintf(buf, sizeof(buf), fmt, ap);
523 		panicstr = buf;
524 		printf("panic: %s\n", buf);
525 	} else {
526 		printf("panic: ");
527 		vprintf(fmt, ap);
528 		printf("\n");
529 	}
530 	va_end(ap);
531 #ifdef SMP
532 	printf("cpuid = %d\n", PCPU_GET(cpuid));
533 #endif
534 
535 #ifdef KDB
536 	if (newpanic && trace_on_panic)
537 		kdb_backtrace();
538 	if (debugger_on_panic)
539 		kdb_enter("panic");
540 #ifdef RESTARTABLE_PANICS
541 	/* See if the user aborted the panic, in which case we continue. */
542 	if (panicstr == NULL) {
543 #ifdef SMP
544 		atomic_store_rel_int(&panic_cpu, NOCPU);
545 #endif
546 		return;
547 	}
548 #endif
549 #endif
550 	mtx_lock_spin(&sched_lock);
551 	td->td_flags |= TDF_INPANIC;
552 	mtx_unlock_spin(&sched_lock);
553 	if (!sync_on_panic)
554 		bootopt |= RB_NOSYNC;
555 	boot(bootopt);
556 }
557 
558 /*
559  * Support for poweroff delay.
560  */
561 #ifndef POWEROFF_DELAY
562 # define POWEROFF_DELAY 5000
563 #endif
564 static int poweroff_delay = POWEROFF_DELAY;
565 
566 SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
567 	&poweroff_delay, 0, "");
568 
569 static void
570 poweroff_wait(void *junk, int howto)
571 {
572 
573 	if (!(howto & RB_POWEROFF) || poweroff_delay <= 0)
574 		return;
575 	DELAY(poweroff_delay * 1000);
576 }
577 
578 /*
579  * Some system processes (e.g. syncer) need to be stopped at appropriate
580  * points in their main loops prior to a system shutdown, so that they
581  * won't interfere with the shutdown process (e.g. by holding a disk buf
582  * to cause sync to fail).  For each of these system processes, register
583  * shutdown_kproc() as a handler for one of shutdown events.
584  */
585 static int kproc_shutdown_wait = 60;
586 SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
587     &kproc_shutdown_wait, 0, "");
588 
589 void
590 kproc_shutdown(void *arg, int howto)
591 {
592 	struct proc *p;
593 	char procname[MAXCOMLEN + 1];
594 	int error;
595 
596 	if (panicstr)
597 		return;
598 
599 	p = (struct proc *)arg;
600 	strlcpy(procname, p->p_comm, sizeof(procname));
601 	printf("Waiting (max %d seconds) for system process `%s' to stop...",
602 	    kproc_shutdown_wait, procname);
603 	error = kthread_suspend(p, kproc_shutdown_wait * hz);
604 
605 	if (error == EWOULDBLOCK)
606 		printf("timed out\n");
607 	else
608 		printf("done\n");
609 }
610 
611 /* Registration of dumpers */
612 int
613 set_dumper(struct dumperinfo *di)
614 {
615 
616 	if (di == NULL) {
617 		bzero(&dumper, sizeof dumper);
618 		return (0);
619 	}
620 	if (dumper.dumper != NULL)
621 		return (EBUSY);
622 	dumper = *di;
623 	return (0);
624 }
625 
626 #if defined(__powerpc__)
627 void
628 dumpsys(struct dumperinfo *di __unused)
629 {
630 
631 	printf("Kernel dumps not implemented on this architecture\n");
632 }
633 #endif
634