kern_shutdown.c revision 228424
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: head/sys/kern/kern_shutdown.c 228424 2011-12-11 21:02:01Z avg $");
39
40#include "opt_ddb.h"
41#include "opt_kdb.h"
42#include "opt_panic.h"
43#include "opt_sched.h"
44#include "opt_watchdog.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/jail.h>
54#include <sys/kdb.h>
55#include <sys/kernel.h>
56#include <sys/kerneldump.h>
57#include <sys/kthread.h>
58#include <sys/malloc.h>
59#include <sys/mount.h>
60#include <sys/priv.h>
61#include <sys/proc.h>
62#include <sys/reboot.h>
63#include <sys/resourcevar.h>
64#include <sys/sched.h>
65#include <sys/smp.h>
66#include <sys/sysctl.h>
67#include <sys/sysproto.h>
68#include <sys/vnode.h>
69#ifdef SW_WATCHDOG
70#include <sys/watchdog.h>
71#endif
72
73#include <ddb/ddb.h>
74
75#include <machine/cpu.h>
76#include <machine/pcb.h>
77#include <machine/smp.h>
78
79#include <security/mac/mac_framework.h>
80
81#include <vm/vm.h>
82#include <vm/vm_object.h>
83#include <vm/vm_page.h>
84#include <vm/vm_pager.h>
85#include <vm/swap_pager.h>
86
87#include <sys/signalvar.h>
88
89#ifndef PANIC_REBOOT_WAIT_TIME
90#define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
91#endif
92
93/*
94 * Note that stdarg.h and the ANSI style va_start macro is used for both
95 * ANSI and traditional C compilers.
96 */
97#include <machine/stdarg.h>
98
99#ifdef KDB
100#ifdef KDB_UNATTENDED
101int debugger_on_panic = 0;
102#else
103int debugger_on_panic = 1;
104#endif
105SYSCTL_INT(_debug, OID_AUTO, debugger_on_panic, CTLFLAG_RW | CTLFLAG_TUN,
106	&debugger_on_panic, 0, "Run debugger on kernel panic");
107TUNABLE_INT("debug.debugger_on_panic", &debugger_on_panic);
108
109#ifdef KDB_TRACE
110static int trace_on_panic = 1;
111#else
112static int trace_on_panic = 0;
113#endif
114SYSCTL_INT(_debug, OID_AUTO, trace_on_panic, CTLFLAG_RW | CTLFLAG_TUN,
115	&trace_on_panic, 0, "Print stack trace on kernel panic");
116TUNABLE_INT("debug.trace_on_panic", &trace_on_panic);
117#endif /* KDB */
118
119static int sync_on_panic = 0;
120SYSCTL_INT(_kern, OID_AUTO, sync_on_panic, CTLFLAG_RW | CTLFLAG_TUN,
121	&sync_on_panic, 0, "Do a sync before rebooting from a panic");
122TUNABLE_INT("kern.sync_on_panic", &sync_on_panic);
123
124static int stop_scheduler_on_panic = 0;
125SYSCTL_INT(_kern, OID_AUTO, stop_scheduler_on_panic, CTLFLAG_RW | CTLFLAG_TUN,
126    &stop_scheduler_on_panic, 0, "stop scheduler upon entering panic");
127TUNABLE_INT("kern.stop_scheduler_on_panic", &stop_scheduler_on_panic);
128
129static SYSCTL_NODE(_kern, OID_AUTO, shutdown, CTLFLAG_RW, 0,
130    "Shutdown environment");
131
132#ifndef DIAGNOSTIC
133static int show_busybufs;
134#else
135static int show_busybufs = 1;
136#endif
137SYSCTL_INT(_kern_shutdown, OID_AUTO, show_busybufs, CTLFLAG_RW,
138	&show_busybufs, 0, "");
139
140/*
141 * Variable panicstr contains argument to first call to panic; used as flag
142 * to indicate that the kernel has already called panic.
143 */
144const char *panicstr;
145
146int stop_scheduler;			/* system stopped CPUs for panic */
147int dumping;				/* system is dumping */
148int rebooting;				/* system is rebooting */
149static struct dumperinfo dumper;	/* our selected dumper */
150
151/* Context information for dump-debuggers. */
152static struct pcb dumppcb;		/* Registers. */
153static lwpid_t dumptid;			/* Thread ID. */
154
155static void poweroff_wait(void *, int);
156static void shutdown_halt(void *junk, int howto);
157static void shutdown_panic(void *junk, int howto);
158static void shutdown_reset(void *junk, int howto);
159
160/* register various local shutdown events */
161static void
162shutdown_conf(void *unused)
163{
164
165	EVENTHANDLER_REGISTER(shutdown_final, poweroff_wait, NULL,
166	    SHUTDOWN_PRI_FIRST);
167	EVENTHANDLER_REGISTER(shutdown_final, shutdown_halt, NULL,
168	    SHUTDOWN_PRI_LAST + 100);
169	EVENTHANDLER_REGISTER(shutdown_final, shutdown_panic, NULL,
170	    SHUTDOWN_PRI_LAST + 100);
171	EVENTHANDLER_REGISTER(shutdown_final, shutdown_reset, NULL,
172	    SHUTDOWN_PRI_LAST + 200);
173}
174
175SYSINIT(shutdown_conf, SI_SUB_INTRINSIC, SI_ORDER_ANY, shutdown_conf, NULL);
176
177/*
178 * The system call that results in a reboot.
179 */
180/* ARGSUSED */
181int
182sys_reboot(struct thread *td, struct reboot_args *uap)
183{
184	int error;
185
186	error = 0;
187#ifdef MAC
188	error = mac_system_check_reboot(td->td_ucred, uap->opt);
189#endif
190	if (error == 0)
191		error = priv_check(td, PRIV_REBOOT);
192	if (error == 0) {
193		mtx_lock(&Giant);
194		kern_reboot(uap->opt);
195		mtx_unlock(&Giant);
196	}
197	return (error);
198}
199
200/*
201 * Called by events that want to shut down.. e.g  <CTL><ALT><DEL> on a PC
202 */
203static int shutdown_howto = 0;
204
205void
206shutdown_nice(int howto)
207{
208
209	shutdown_howto = howto;
210
211	/* Send a signal to init(8) and have it shutdown the world */
212	if (initproc != NULL) {
213		PROC_LOCK(initproc);
214		kern_psignal(initproc, SIGINT);
215		PROC_UNLOCK(initproc);
216	} else {
217		/* No init(8) running, so simply reboot */
218		kern_reboot(RB_NOSYNC);
219	}
220	return;
221}
222static int	waittime = -1;
223
224static void
225print_uptime(void)
226{
227	int f;
228	struct timespec ts;
229
230	getnanouptime(&ts);
231	printf("Uptime: ");
232	f = 0;
233	if (ts.tv_sec >= 86400) {
234		printf("%ldd", (long)ts.tv_sec / 86400);
235		ts.tv_sec %= 86400;
236		f = 1;
237	}
238	if (f || ts.tv_sec >= 3600) {
239		printf("%ldh", (long)ts.tv_sec / 3600);
240		ts.tv_sec %= 3600;
241		f = 1;
242	}
243	if (f || ts.tv_sec >= 60) {
244		printf("%ldm", (long)ts.tv_sec / 60);
245		ts.tv_sec %= 60;
246		f = 1;
247	}
248	printf("%lds\n", (long)ts.tv_sec);
249}
250
251int
252doadump(boolean_t textdump)
253{
254	boolean_t coredump;
255
256	if (dumping)
257		return (EBUSY);
258	if (dumper.dumper == NULL)
259		return (ENXIO);
260
261	savectx(&dumppcb);
262	dumptid = curthread->td_tid;
263	dumping++;
264
265	coredump = TRUE;
266#ifdef DDB
267	if (textdump && textdump_pending) {
268		coredump = FALSE;
269		textdump_dumpsys(&dumper);
270	}
271#endif
272	if (coredump)
273		dumpsys(&dumper);
274
275	dumping--;
276	return (0);
277}
278
279static int
280isbufbusy(struct buf *bp)
281{
282	if (((bp->b_flags & (B_INVAL | B_PERSISTENT)) == 0 &&
283	    BUF_ISLOCKED(bp)) ||
284	    ((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI))
285		return (1);
286	return (0);
287}
288
289/*
290 * Shutdown the system cleanly to prepare for reboot, halt, or power off.
291 */
292void
293kern_reboot(int howto)
294{
295	static int first_buf_printf = 1;
296
297#if defined(SMP)
298	/*
299	 * Bind us to CPU 0 so that all shutdown code runs there.  Some
300	 * systems don't shutdown properly (i.e., ACPI power off) if we
301	 * run on another processor.
302	 */
303	if (!SCHEDULER_STOPPED()) {
304		thread_lock(curthread);
305		sched_bind(curthread, 0);
306		thread_unlock(curthread);
307		KASSERT(PCPU_GET(cpuid) == 0, ("boot: not running on cpu 0"));
308	}
309#endif
310	/* We're in the process of rebooting. */
311	rebooting = 1;
312
313	/* collect extra flags that shutdown_nice might have set */
314	howto |= shutdown_howto;
315
316	/* We are out of the debugger now. */
317	kdb_active = 0;
318
319	/*
320	 * Do any callouts that should be done BEFORE syncing the filesystems.
321	 */
322	EVENTHANDLER_INVOKE(shutdown_pre_sync, howto);
323
324	/*
325	 * Now sync filesystems
326	 */
327	if (!cold && (howto & RB_NOSYNC) == 0 && waittime < 0) {
328		register struct buf *bp;
329		int iter, nbusy, pbusy;
330#ifndef PREEMPTION
331		int subiter;
332#endif
333
334		waittime = 0;
335
336#ifdef SW_WATCHDOG
337		wdog_kern_pat(WD_LASTVAL);
338#endif
339		sys_sync(curthread, NULL);
340
341		/*
342		 * With soft updates, some buffers that are
343		 * written will be remarked as dirty until other
344		 * buffers are written.
345		 */
346		for (iter = pbusy = 0; iter < 20; iter++) {
347			nbusy = 0;
348			for (bp = &buf[nbuf]; --bp >= buf; )
349				if (isbufbusy(bp))
350					nbusy++;
351			if (nbusy == 0) {
352				if (first_buf_printf)
353					printf("All buffers synced.");
354				break;
355			}
356			if (first_buf_printf) {
357				printf("Syncing disks, buffers remaining... ");
358				first_buf_printf = 0;
359			}
360			printf("%d ", nbusy);
361			if (nbusy < pbusy)
362				iter = 0;
363			pbusy = nbusy;
364#ifdef SW_WATCHDOG
365			wdog_kern_pat(WD_LASTVAL);
366#endif
367			sys_sync(curthread, NULL);
368
369#ifdef PREEMPTION
370			/*
371			 * Drop Giant and spin for a while to allow
372			 * interrupt threads to run.
373			 */
374			DROP_GIANT();
375			DELAY(50000 * iter);
376			PICKUP_GIANT();
377#else
378			/*
379			 * Drop Giant and context switch several times to
380			 * allow interrupt threads to run.
381			 */
382			DROP_GIANT();
383			for (subiter = 0; subiter < 50 * iter; subiter++) {
384				thread_lock(curthread);
385				mi_switch(SW_VOL, NULL);
386				thread_unlock(curthread);
387				DELAY(1000);
388			}
389			PICKUP_GIANT();
390#endif
391		}
392		printf("\n");
393		/*
394		 * Count only busy local buffers to prevent forcing
395		 * a fsck if we're just a client of a wedged NFS server
396		 */
397		nbusy = 0;
398		for (bp = &buf[nbuf]; --bp >= buf; ) {
399			if (isbufbusy(bp)) {
400#if 0
401/* XXX: This is bogus.  We should probably have a BO_REMOTE flag instead */
402				if (bp->b_dev == NULL) {
403					TAILQ_REMOVE(&mountlist,
404					    bp->b_vp->v_mount, mnt_list);
405					continue;
406				}
407#endif
408				nbusy++;
409				if (show_busybufs > 0) {
410					printf(
411	    "%d: buf:%p, vnode:%p, flags:%0x, blkno:%jd, lblkno:%jd, buflock:",
412					    nbusy, bp, bp->b_vp, bp->b_flags,
413					    (intmax_t)bp->b_blkno,
414					    (intmax_t)bp->b_lblkno);
415					BUF_LOCKPRINTINFO(bp);
416					if (show_busybufs > 1)
417						vn_printf(bp->b_vp,
418						    "vnode content: ");
419				}
420			}
421		}
422		if (nbusy) {
423			/*
424			 * Failed to sync all blocks. Indicate this and don't
425			 * unmount filesystems (thus forcing an fsck on reboot).
426			 */
427			printf("Giving up on %d buffers\n", nbusy);
428			DELAY(5000000);	/* 5 seconds */
429		} else {
430			if (!first_buf_printf)
431				printf("Final sync complete\n");
432			/*
433			 * Unmount filesystems
434			 */
435			if (panicstr == 0)
436				vfs_unmountall();
437		}
438		swapoff_all();
439		DELAY(100000);		/* wait for console output to finish */
440	}
441
442	print_uptime();
443
444	/*
445	 * Ok, now do things that assume all filesystem activity has
446	 * been completed.
447	 */
448	EVENTHANDLER_INVOKE(shutdown_post_sync, howto);
449
450	if ((howto & (RB_HALT|RB_DUMP)) == RB_DUMP && !cold && !dumping)
451		doadump(TRUE);
452
453	/* Now that we're going to really halt the system... */
454	EVENTHANDLER_INVOKE(shutdown_final, howto);
455
456	for(;;) ;	/* safety against shutdown_reset not working */
457	/* NOTREACHED */
458}
459
460/*
461 * If the shutdown was a clean halt, behave accordingly.
462 */
463static void
464shutdown_halt(void *junk, int howto)
465{
466
467	if (howto & RB_HALT) {
468		printf("\n");
469		printf("The operating system has halted.\n");
470		printf("Please press any key to reboot.\n\n");
471		switch (cngetc()) {
472		case -1:		/* No console, just die */
473			cpu_halt();
474			/* NOTREACHED */
475		default:
476			howto &= ~RB_HALT;
477			break;
478		}
479	}
480}
481
482/*
483 * Check to see if the system paniced, pause and then reboot
484 * according to the specified delay.
485 */
486static void
487shutdown_panic(void *junk, int howto)
488{
489	int loop;
490
491	if (howto & RB_DUMP) {
492		if (PANIC_REBOOT_WAIT_TIME != 0) {
493			if (PANIC_REBOOT_WAIT_TIME != -1) {
494				printf("Automatic reboot in %d seconds - "
495				       "press a key on the console to abort\n",
496					PANIC_REBOOT_WAIT_TIME);
497				for (loop = PANIC_REBOOT_WAIT_TIME * 10;
498				     loop > 0; --loop) {
499					DELAY(1000 * 100); /* 1/10th second */
500					/* Did user type a key? */
501					if (cncheckc() != -1)
502						break;
503				}
504				if (!loop)
505					return;
506			}
507		} else { /* zero time specified - reboot NOW */
508			return;
509		}
510		printf("--> Press a key on the console to reboot,\n");
511		printf("--> or switch off the system now.\n");
512		cngetc();
513	}
514}
515
516/*
517 * Everything done, now reset
518 */
519static void
520shutdown_reset(void *junk, int howto)
521{
522
523	printf("Rebooting...\n");
524	DELAY(1000000);	/* wait 1 sec for printf's to complete and be read */
525
526	/*
527	 * Acquiring smp_ipi_mtx here has a double effect:
528	 * - it disables interrupts avoiding CPU0 preemption
529	 *   by fast handlers (thus deadlocking  against other CPUs)
530	 * - it avoids deadlocks against smp_rendezvous() or, more
531	 *   generally, threads busy-waiting, with this spinlock held,
532	 *   and waiting for responses by threads on other CPUs
533	 *   (ie. smp_tlb_shootdown()).
534	 *
535	 * For the !SMP case it just needs to handle the former problem.
536	 */
537#ifdef SMP
538	mtx_lock_spin(&smp_ipi_mtx);
539#else
540	spinlock_enter();
541#endif
542
543	/* cpu_boot(howto); */ /* doesn't do anything at the moment */
544	cpu_reset();
545	/* NOTREACHED */ /* assuming reset worked */
546}
547
548/*
549 * Panic is called on unresolvable fatal errors.  It prints "panic: mesg",
550 * and then reboots.  If we are called twice, then we avoid trying to sync
551 * the disks as this often leads to recursive panics.
552 */
553void
554panic(const char *fmt, ...)
555{
556#ifdef SMP
557	static volatile u_int panic_cpu = NOCPU;
558	cpuset_t other_cpus;
559#endif
560	struct thread *td = curthread;
561	int bootopt, newpanic;
562	va_list ap;
563	static char buf[256];
564
565	if (stop_scheduler_on_panic)
566		spinlock_enter();
567	else
568		critical_enter();
569
570#ifdef SMP
571	/*
572	 * We don't want multiple CPU's to panic at the same time, so we
573	 * use panic_cpu as a simple spinlock.  We have to keep checking
574	 * panic_cpu if we are spinning in case the panic on the first
575	 * CPU is canceled.
576	 */
577	if (panic_cpu != PCPU_GET(cpuid))
578		while (atomic_cmpset_int(&panic_cpu, NOCPU,
579		    PCPU_GET(cpuid)) == 0)
580			while (panic_cpu != NOCPU)
581				; /* nothing */
582
583	if (stop_scheduler_on_panic) {
584		if (panicstr == NULL && !kdb_active) {
585			other_cpus = all_cpus;
586			CPU_CLR(PCPU_GET(cpuid), &other_cpus);
587			stop_cpus_hard(other_cpus);
588		}
589
590		/*
591		 * We set stop_scheduler here and not in the block above,
592		 * because we want to ensure that if panic has been called and
593		 * stop_scheduler_on_panic is true, then stop_scheduler will
594		 * always be set.  Even if panic has been entered from kdb.
595		 */
596		stop_scheduler = 1;
597	}
598#endif
599
600	bootopt = RB_AUTOBOOT;
601	newpanic = 0;
602	if (panicstr)
603		bootopt |= RB_NOSYNC;
604	else {
605		bootopt |= RB_DUMP;
606		panicstr = fmt;
607		newpanic = 1;
608	}
609
610	va_start(ap, fmt);
611	if (newpanic) {
612		(void)vsnprintf(buf, sizeof(buf), fmt, ap);
613		panicstr = buf;
614		printf("panic: %s\n", buf);
615	} else {
616		printf("panic: ");
617		vprintf(fmt, ap);
618		printf("\n");
619	}
620	va_end(ap);
621#ifdef SMP
622	printf("cpuid = %d\n", PCPU_GET(cpuid));
623#endif
624
625#ifdef KDB
626	if (newpanic && trace_on_panic)
627		kdb_backtrace();
628	if (debugger_on_panic)
629		kdb_enter(KDB_WHY_PANIC, "panic");
630#endif
631	/*thread_lock(td); */
632	td->td_flags |= TDF_INPANIC;
633	/* thread_unlock(td); */
634	if (!sync_on_panic)
635		bootopt |= RB_NOSYNC;
636	if (!stop_scheduler_on_panic)
637		critical_exit();
638	kern_reboot(bootopt);
639}
640
641/*
642 * Support for poweroff delay.
643 *
644 * Please note that setting this delay too short might power off your machine
645 * before the write cache on your hard disk has been flushed, leading to
646 * soft-updates inconsistencies.
647 */
648#ifndef POWEROFF_DELAY
649# define POWEROFF_DELAY 5000
650#endif
651static int poweroff_delay = POWEROFF_DELAY;
652
653SYSCTL_INT(_kern_shutdown, OID_AUTO, poweroff_delay, CTLFLAG_RW,
654	&poweroff_delay, 0, "");
655
656static void
657poweroff_wait(void *junk, int howto)
658{
659
660	if (!(howto & RB_POWEROFF) || poweroff_delay <= 0)
661		return;
662	DELAY(poweroff_delay * 1000);
663}
664
665/*
666 * Some system processes (e.g. syncer) need to be stopped at appropriate
667 * points in their main loops prior to a system shutdown, so that they
668 * won't interfere with the shutdown process (e.g. by holding a disk buf
669 * to cause sync to fail).  For each of these system processes, register
670 * shutdown_kproc() as a handler for one of shutdown events.
671 */
672static int kproc_shutdown_wait = 60;
673SYSCTL_INT(_kern_shutdown, OID_AUTO, kproc_shutdown_wait, CTLFLAG_RW,
674    &kproc_shutdown_wait, 0, "");
675
676void
677kproc_shutdown(void *arg, int howto)
678{
679	struct proc *p;
680	int error;
681
682	if (panicstr)
683		return;
684
685	p = (struct proc *)arg;
686	printf("Waiting (max %d seconds) for system process `%s' to stop...",
687	    kproc_shutdown_wait, p->p_comm);
688	error = kproc_suspend(p, kproc_shutdown_wait * hz);
689
690	if (error == EWOULDBLOCK)
691		printf("timed out\n");
692	else
693		printf("done\n");
694}
695
696void
697kthread_shutdown(void *arg, int howto)
698{
699	struct thread *td;
700	int error;
701
702	if (panicstr)
703		return;
704
705	td = (struct thread *)arg;
706	printf("Waiting (max %d seconds) for system thread `%s' to stop...",
707	    kproc_shutdown_wait, td->td_name);
708	error = kthread_suspend(td, kproc_shutdown_wait * hz);
709
710	if (error == EWOULDBLOCK)
711		printf("timed out\n");
712	else
713		printf("done\n");
714}
715
716/* Registration of dumpers */
717int
718set_dumper(struct dumperinfo *di)
719{
720
721	if (di == NULL) {
722		bzero(&dumper, sizeof dumper);
723		return (0);
724	}
725	if (dumper.dumper != NULL)
726		return (EBUSY);
727	dumper = *di;
728	return (0);
729}
730
731/* Call dumper with bounds checking. */
732int
733dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical,
734    off_t offset, size_t length)
735{
736
737	if (length != 0 && (offset < di->mediaoffset ||
738	    offset - di->mediaoffset + length > di->mediasize)) {
739		printf("Attempt to write outside dump device boundaries.\n"
740	    "offset(%jd), mediaoffset(%jd), length(%ju), mediasize(%jd).\n",
741		    (intmax_t)offset, (intmax_t)di->mediaoffset,
742		    (uintmax_t)length, (intmax_t)di->mediasize);
743		return (ENOSPC);
744	}
745	return (di->dumper(di->priv, virtual, physical, offset, length));
746}
747
748void
749mkdumpheader(struct kerneldumpheader *kdh, char *magic, uint32_t archver,
750    uint64_t dumplen, uint32_t blksz)
751{
752
753	bzero(kdh, sizeof(*kdh));
754	strncpy(kdh->magic, magic, sizeof(kdh->magic));
755	strncpy(kdh->architecture, MACHINE_ARCH, sizeof(kdh->architecture));
756	kdh->version = htod32(KERNELDUMPVERSION);
757	kdh->architectureversion = htod32(archver);
758	kdh->dumplength = htod64(dumplen);
759	kdh->dumptime = htod64(time_second);
760	kdh->blocksize = htod32(blksz);
761	strncpy(kdh->hostname, prison0.pr_hostname, sizeof(kdh->hostname));
762	strncpy(kdh->versionstring, version, sizeof(kdh->versionstring));
763	if (panicstr != NULL)
764		strncpy(kdh->panicstring, panicstr, sizeof(kdh->panicstring));
765	kdh->parity = kerneldump_parity(kdh);
766}
767