1 /*-
2  * Copyright (c) 2006 Peter Wemm
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/amd64/amd64/minidump_machdep.c,v 1.10 2009/05/29 21:27:12 jamie Exp $
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/conf.h>
32 #include <sys/cons.h>
33 #include <sys/device.h>
34 #include <sys/globaldata.h>
35 #include <sys/kernel.h>
36 #include <sys/kerneldump.h>
37 #include <sys/msgbuf.h>
38 #include <sys/kbio.h>
39 #include <vm/vm.h>
40 #include <vm/vm_kern.h>
41 #include <vm/pmap.h>
42 #include <machine/atomic.h>
43 #include <machine/elf.h>
44 #include <machine/globaldata.h>
45 #include <machine/md_var.h>
46 #include <machine/vmparam.h>
47 #include <machine/minidump.h>
48 
49 CTASSERT(sizeof(struct kerneldumpheader) == 512);
50 
51 /*
52  * Don't touch the first SIZEOF_METADATA bytes on the dump device. This
53  * is to protect us from metadata and to protect metadata from us.
54  */
55 #define	SIZEOF_METADATA		(64*1024)
56 
57 #define	MD_ALIGN(x)	(((off_t)(x) + PAGE_MASK) & ~PAGE_MASK)
58 #define	DEV_ALIGN(x)	roundup2((off_t)(x), DEV_BSIZE)
59 
60 extern uint64_t KPDPphys;
61 
62 uint64_t *vm_page_dump;
63 vm_offset_t vm_page_dump_size;
64 
65 static struct kerneldumpheader kdh;
66 static off_t dumplo;
67 
68 /* Handle chunked writes. */
69 static size_t fragsz;
70 static void *dump_va;
71 static size_t counter, progress;
72 
73 CTASSERT(sizeof(*vm_page_dump) == 8);
74 
75 static int
76 is_dumpable(vm_paddr_t pa)
77 {
78 	int i;
79 
80 	for (i = 0; dump_avail[i].phys_beg || dump_avail[i].phys_end; ++i) {
81 		if (pa >= dump_avail[i].phys_beg && pa < dump_avail[i].phys_end)
82 			return (1);
83 	}
84 	return (0);
85 }
86 
87 #define PG2MB(pgs) (((pgs) + (1 << 8) - 1) >> 8)
88 
89 static int
90 blk_flush(struct dumperinfo *di)
91 {
92 	int error;
93 
94 	if (fragsz == 0)
95 		return (0);
96 
97 	error = dev_ddump(di->priv, dump_va, 0, dumplo, fragsz);
98 	dumplo += fragsz;
99 	fragsz = 0;
100 	return (error);
101 }
102 
103 static int
104 blk_write(struct dumperinfo *di, char *ptr, vm_paddr_t pa, size_t sz)
105 {
106 	size_t len;
107 	int error, i, c;
108 	int max_iosize;
109 
110 	error = 0;
111 	if ((sz & PAGE_MASK)) {
112 		kprintf("size not page aligned\n");
113 		return (EINVAL);
114 	}
115 	if (ptr != NULL && pa != 0) {
116 		kprintf("can't have both va and pa!\n");
117 		return (EINVAL);
118 	}
119 	if (pa != 0 && (((uintptr_t)pa) & PAGE_MASK) != 0) {
120 		kprintf("address not page aligned\n");
121 		return (EINVAL);
122 	}
123 	if (ptr != NULL) {
124 		/*
125 		 * If we're doing a virtual dump, flush any
126 		 * pre-existing pa pages
127 		 */
128 		error = blk_flush(di);
129 		if (error)
130 			return (error);
131 	}
132 	max_iosize = min(MAXPHYS, di->maxiosize);
133 	while (sz) {
134 		len = max_iosize - fragsz;
135 		if (len > sz)
136 			len = sz;
137 		counter += len;
138 		progress -= len;
139 		if (counter >> 24) {
140 			kprintf(" %ld", PG2MB(progress >> PAGE_SHIFT));
141 			counter &= (1<<24) - 1;
142 		}
143 		if (ptr) {
144 			/*kprintf("s");*/
145 			error = dev_ddump(di->priv, ptr, 0, dumplo, len);
146 			/* kprintf("t");*/
147 			if (error)
148 				return (error);
149 			dumplo += len;
150 			ptr += len;
151 			sz -= len;
152 		} else {
153 			for (i = 0; i < len; i += PAGE_SIZE) {
154 				dump_va = pmap_kenter_temporary(pa + i,
155 						(i + fragsz) >> PAGE_SHIFT);
156 			}
157 			smp_invltlb();
158 			fragsz += len;
159 			pa += len;
160 			sz -= len;
161 			if (fragsz == max_iosize) {
162 				error = blk_flush(di);
163 				if (error)
164 					return (error);
165 			}
166 		}
167 	}
168 
169 	/* Check for user abort. */
170 	c = cncheckc();
171 	if (c == 0x03)
172 		return (ECANCELED);
173 	if (c != -1 && c != NOKEY)
174 		kprintf(" (CTRL-C to abort) ");
175 
176 	return (0);
177 }
178 
179 /* A fake page table page, to avoid having to handle both 4K and 2M pages */
180 static pt_entry_t fakept[NPTEPG];
181 
182 void
183 minidumpsys(struct dumperinfo *di)
184 {
185 	uint64_t dumpsize;
186 	uint64_t ptesize;
187 	vm_offset_t va;
188 	vm_offset_t kern_end;
189 	int error;
190 	uint64_t bits;
191 	uint64_t *pdp, *pd, *pt, pa;
192 	int i, j, k, bit;
193 	int kpdp, klo, khi;
194 	int lpdp = -1;
195 	long lpdpttl = 0;
196 	struct minidumphdr2 mdhdr;
197 	struct mdglobaldata *md;
198 
199 	cnpoll(TRUE);
200 	counter = 0;
201 
202 	/*
203 	 * minidump page table format is an array of PD entries (1GB pte's),
204 	 * representing the entire user and kernel virtual address space
205 	 * (256TB).
206 	 *
207 	 * However, we will only dump the KVM portion of this space.  And we
208 	 * only copy the PDP pages for direct access, the PD and PT pages
209 	 * will be included in the dump as part of the physical map.
210 	 */
211 	ptesize = NPML4EPG * NPDPEPG * 8;
212 
213 	/*
214 	 * Walk page table pages, set bits in vm_page_dump.
215 	 *
216 	 * NOTE: kernel_vm_end can actually be below KERNBASE.
217 	 * 	 Just use KvaEnd.  Also note that loops which go
218 	 *	 all the way to the end of the address space might
219 	 *	 overflow the loop variable.
220 	 */
221 	md = (struct mdglobaldata *)globaldata_find(0);
222 
223 	kern_end = KvaEnd;
224 	if (kern_end < (vm_offset_t)&(md[ncpus]))
225 		kern_end = (vm_offset_t)&(md[ncpus]);
226 
227 	pdp = (uint64_t *)PHYS_TO_DMAP(KPDPphys);
228 	for (va = VM_MIN_KERNEL_ADDRESS; va < kern_end; va += NBPDR) {
229 		/*
230 		 * The loop probably overflows a 64-bit int due to NBPDR.
231 		 */
232 		if (va < VM_MIN_KERNEL_ADDRESS)
233 			break;
234 
235 		/*
236 		 * KPDPphys[] is relative to VM_MIN_KERNEL_ADDRESS. It
237 		 * contains NKPML4E PDP pages (so we can get to all kernel
238 		 * PD entries from this array).
239 		 */
240 		i = ((va - VM_MIN_KERNEL_ADDRESS) >> PDPSHIFT) &
241 		    (NPML4EPG * NPDPEPG - 1);
242 		if (i != lpdp) {
243 			if (lpdpttl) {
244 				kprintf("pdp %04x ttl %jdMB\n",
245 					lpdp, (intmax_t)lpdpttl / 1024 / 1024);
246 			}
247 			lpdp = i;
248 			lpdpttl = 0;
249 		}
250 
251 		/*
252 		 * Calculate the PD index in the PDP.  Each PD represents 1GB.
253 		 * KVA space can cover multiple PDP pages.  The PDP array
254 		 * has been initialized for the entire kernel address space.
255 		 *
256 		 * We include the PD entries in the PDP in the dump
257 		 */
258 		i = ((va - VM_MIN_KERNEL_ADDRESS) >> PDPSHIFT) &
259 		    (NPML4EPG * NPDPEPG - 1);
260 		if ((pdp[i] & kernel_pmap.pmap_bits[PG_V_IDX]) == 0)
261 			continue;
262 
263 		/*
264 		 * Add the PD page from the PDP to the dump
265 		 */
266 		dump_add_page(pdp[i] & PG_FRAME);
267 		lpdpttl += PAGE_SIZE;
268 
269 		pd = (uint64_t *)PHYS_TO_DMAP(pdp[i] & PG_FRAME);
270 		j = ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
271 		if ((pd[j] & (kernel_pmap.pmap_bits[PG_PS_IDX] | kernel_pmap.pmap_bits[PG_V_IDX])) ==
272 		    (kernel_pmap.pmap_bits[PG_PS_IDX] | kernel_pmap.pmap_bits[PG_V_IDX]))  {
273 			/* This is an entire 2M page. */
274 			lpdpttl += PAGE_SIZE * NPTEPG;
275 			pa = pd[j] & PG_PS_FRAME;
276 			for (k = 0; k < NPTEPG; k++) {
277 				if (is_dumpable(pa))
278 					dump_add_page(pa);
279 				pa += PAGE_SIZE;
280 			}
281 			continue;
282 		}
283 		if ((pd[j] & kernel_pmap.pmap_bits[PG_V_IDX]) ==
284 		    kernel_pmap.pmap_bits[PG_V_IDX]) {
285 			/*
286 			 * Add the PT page from the PD to the dump (it is no
287 			 * longer included in the ptemap.
288 			 */
289 			dump_add_page(pd[j] & PG_FRAME);
290 			lpdpttl += PAGE_SIZE;
291 
292 			/* set bit for each valid page in this 2MB block */
293 			pt = (uint64_t *)PHYS_TO_DMAP(pd[j] & PG_FRAME);
294 			for (k = 0; k < NPTEPG; k++) {
295 				if ((pt[k] & kernel_pmap.pmap_bits[PG_V_IDX]) == kernel_pmap.pmap_bits[PG_V_IDX]) {
296 					pa = pt[k] & PG_FRAME;
297 					lpdpttl += PAGE_SIZE;
298 					if (is_dumpable(pa))
299 						dump_add_page(pa);
300 				}
301 			}
302 		} else {
303 			/* nothing, we're going to dump a null page */
304 		}
305 	}
306 
307 	if (lpdpttl) {
308 		kprintf("pdp %04x ttl %jdMB\n",
309 			lpdp, (intmax_t)lpdpttl / 1024 / 1024);
310 	}
311 
312 	/* Calculate dump size. */
313 	dumpsize = ptesize;
314 	dumpsize += round_page(msgbufp->msg_size);
315 	dumpsize += round_page(vm_page_dump_size);
316 
317 	for (i = 0; i < vm_page_dump_size / sizeof(*vm_page_dump); i++) {
318 		bits = vm_page_dump[i];
319 		while (bits) {
320 			bit = bsfq(bits);
321 			pa = (((uint64_t)i * sizeof(*vm_page_dump) * NBBY) + bit) * PAGE_SIZE;
322 			/* Clear out undumpable pages now if needed */
323 			if (is_dumpable(pa)) {
324 				dumpsize += PAGE_SIZE;
325 			} else {
326 				dump_drop_page(pa);
327 			}
328 			bits &= ~(1ul << bit);
329 		}
330 	}
331 	dumpsize += PAGE_SIZE;
332 
333 	/* Determine dump offset on device. */
334 	if (di->mediasize < SIZEOF_METADATA + dumpsize + sizeof(kdh) * 2) {
335 		error = ENOSPC;
336 		goto fail;
337 	}
338 	dumplo = di->mediaoffset + di->mediasize - dumpsize;
339 	dumplo -= sizeof(kdh) * 2;
340 	progress = dumpsize;
341 
342 	/* Initialize mdhdr */
343 	bzero(&mdhdr, sizeof(mdhdr));
344 	strcpy(mdhdr.magic, MINIDUMP2_MAGIC);
345 	mdhdr.version = MINIDUMP2_VERSION;
346 	mdhdr.msgbufsize = msgbufp->msg_size;
347 	mdhdr.bitmapsize = vm_page_dump_size;
348 	mdhdr.ptesize = ptesize;
349 	mdhdr.kernbase = VM_MIN_KERNEL_ADDRESS;
350 	mdhdr.dmapbase = DMAP_MIN_ADDRESS;
351 	mdhdr.dmapend = DMAP_MAX_ADDRESS;
352 
353 	mkdumpheader(&kdh, KERNELDUMPMAGIC, KERNELDUMP_AMD64_VERSION,
354 		     dumpsize, di->blocksize);
355 
356 	kprintf("Physical memory: %jd MB\n", (intmax_t)ptoa(physmem) / 1048576);
357 	kprintf("Dumping %jd MB:", (intmax_t)dumpsize >> 20);
358 
359 	/* Dump leader */
360 	error = dev_ddump(di->priv, &kdh, 0, dumplo, sizeof(kdh));
361 	if (error)
362 		goto fail;
363 	dumplo += sizeof(kdh);
364 
365 	/* Dump my header */
366 	bzero(fakept, sizeof(fakept));
367 	bcopy(&mdhdr, fakept, sizeof(mdhdr));
368 	error = blk_write(di, (char *)fakept, 0, PAGE_SIZE);
369 	if (error)
370 		goto fail;
371 
372 	/* Dump msgbuf up front */
373 	error = blk_write(di, (char *)msgbufp->msg_ptr, 0, round_page(msgbufp->msg_size));
374 	if (error)
375 		goto fail;
376 
377 	/* Dump bitmap */
378 	error = blk_write(di, (char *)vm_page_dump, 0, round_page(vm_page_dump_size));
379 	if (error)
380 		goto fail;
381 
382 	/*
383 	 * Dump a full PDP array for the entire KVM space, user and kernel.
384 	 * This is 512*512 1G PD entries (512*512*8 = 2MB).
385 	 *
386 	 * The minidump only dumps PD entries related to KVA space.  Also
387 	 * note that pdp[] (aka KPDPphys[]) only covers VM_MIN_KERNEL_ADDRESS
388 	 * to VM_MAX_KERNEL_ADDRESS.
389 	 *
390 	 * The actual KPDPphys[] array covers a KVA space starting at KVA
391 	 * KPDPPHYS_KVA.
392 	 *
393 	 * By dumping a PDP[] array of PDs representing the entire virtual
394 	 * address space we can expand what we dump in the future.
395 	 */
396 	pdp = (uint64_t *)PHYS_TO_DMAP(KPDPphys);
397 	kpdp = (KPDPPHYS_KVA >> PDPSHIFT) &
398 		    (NPML4EPG * NPDPEPG - 1);
399 	klo = (int)(VM_MIN_KERNEL_ADDRESS >> PDPSHIFT) &
400 		    (NPML4EPG * NPDPEPG - 1);
401 	khi = (int)(VM_MAX_KERNEL_ADDRESS >> PDPSHIFT) &
402 		    (NPML4EPG * NPDPEPG - 1);
403 
404 	for (i = 0; i < NPML4EPG * NPDPEPG; ++i) {
405 		if (i < klo || i > khi) {
406 			fakept[i & (NPDPEPG - 1)] = 0;
407 		} else {
408 			fakept[i & (NPDPEPG - 1)] = pdp[i - kpdp];
409 		}
410 		if ((i & (NPDPEPG - 1)) == (NPDPEPG - 1)) {
411 			error = blk_write(di, (char *)fakept, 0, PAGE_SIZE);
412 			if (error)
413 				goto fail;
414 			error = blk_flush(di);
415 			if (error)
416 				goto fail;
417 		}
418 	}
419 
420 	/* Dump memory chunks */
421 	/* XXX cluster it up and use blk_dump() */
422 	for (i = 0; i < vm_page_dump_size / sizeof(*vm_page_dump); i++) {
423 		bits = vm_page_dump[i];
424 		while (bits) {
425 			bit = bsfq(bits);
426 			pa = (((uint64_t)i * sizeof(*vm_page_dump) * NBBY) + bit) * PAGE_SIZE;
427 			error = blk_write(di, 0, pa, PAGE_SIZE);
428 			if (error)
429 				goto fail;
430 			bits &= ~(1ul << bit);
431 		}
432 	}
433 
434 	error = blk_flush(di);
435 	if (error)
436 		goto fail;
437 
438 	/* Dump trailer */
439 	error = dev_ddump(di->priv, &kdh, 0, dumplo, sizeof(kdh));
440 	if (error)
441 		goto fail;
442 	dumplo += sizeof(kdh);
443 
444 	/* Signal completion, signoff and exit stage left. */
445 	dev_ddump(di->priv, NULL, 0, 0, 0);
446 	kprintf("\nDump complete\n");
447 	cnpoll(FALSE);
448 	return;
449 
450  fail:
451 	cnpoll(FALSE);
452 	if (error < 0)
453 		error = -error;
454 
455 	if (error == ECANCELED)
456 		kprintf("\nDump aborted\n");
457 	else if (error == ENOSPC)
458 		kprintf("\nDump failed. Partition too small.\n");
459 	else
460 		kprintf("\n** DUMP FAILED (ERROR %d) **\n", error);
461 }
462 
463 void
464 dump_add_page(vm_paddr_t pa)
465 {
466 	int idx, bit;
467 
468 	pa >>= PAGE_SHIFT;
469 	idx = pa >> 6;		/* 2^6 = 64 */
470 	bit = pa & 63;
471 	atomic_set_long(&vm_page_dump[idx], 1ul << bit);
472 }
473 
474 void
475 dump_drop_page(vm_paddr_t pa)
476 {
477 	int idx, bit;
478 
479 	pa >>= PAGE_SHIFT;
480 	idx = pa >> 6;		/* 2^6 = 64 */
481 	bit = pa & 63;
482 	atomic_clear_long(&vm_page_dump[idx], 1ul << bit);
483 }
484