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 			lpdp = i;
244 			lpdpttl = 0;
245 		}
246 
247 		/*
248 		 * Calculate the PD index in the PDP.  Each PD represents 1GB.
249 		 * KVA space can cover multiple PDP pages.  The PDP array
250 		 * has been initialized for the entire kernel address space.
251 		 *
252 		 * We include the PD entries in the PDP in the dump
253 		 */
254 		i = ((va - VM_MIN_KERNEL_ADDRESS) >> PDPSHIFT) &
255 		    (NPML4EPG * NPDPEPG - 1);
256 		if ((pdp[i] & kernel_pmap.pmap_bits[PG_V_IDX]) == 0)
257 			continue;
258 
259 		/*
260 		 * Add the PD page from the PDP to the dump
261 		 */
262 		dump_add_page(pdp[i] & PG_FRAME);
263 		lpdpttl += PAGE_SIZE;
264 
265 		pd = (uint64_t *)PHYS_TO_DMAP(pdp[i] & PG_FRAME);
266 		j = ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
267 		if ((pd[j] & (kernel_pmap.pmap_bits[PG_PS_IDX] | kernel_pmap.pmap_bits[PG_V_IDX])) ==
268 		    (kernel_pmap.pmap_bits[PG_PS_IDX] | kernel_pmap.pmap_bits[PG_V_IDX]))  {
269 			/* This is an entire 2M page. */
270 			lpdpttl += PAGE_SIZE * NPTEPG;
271 			pa = pd[j] & PG_PS_FRAME;
272 			for (k = 0; k < NPTEPG; k++) {
273 				if (is_dumpable(pa))
274 					dump_add_page(pa);
275 				pa += PAGE_SIZE;
276 			}
277 		} else if ((pd[j] & kernel_pmap.pmap_bits[PG_V_IDX]) ==
278 			   kernel_pmap.pmap_bits[PG_V_IDX]) {
279 			/*
280 			 * Add the PT page from the PD to the dump (it is no
281 			 * longer included in the ptemap.
282 			 */
283 			dump_add_page(pd[j] & PG_FRAME);
284 			lpdpttl += PAGE_SIZE;
285 
286 			/* set bit for each valid page in this 2MB block */
287 			pt = (uint64_t *)PHYS_TO_DMAP(pd[j] & PG_FRAME);
288 			for (k = 0; k < NPTEPG; k++) {
289 				if ((pt[k] & kernel_pmap.pmap_bits[PG_V_IDX]) == kernel_pmap.pmap_bits[PG_V_IDX]) {
290 					pa = pt[k] & PG_FRAME;
291 					lpdpttl += PAGE_SIZE;
292 					if (is_dumpable(pa))
293 						dump_add_page(pa);
294 				}
295 			}
296 		} else {
297 			/* nothing, we're going to dump a null page */
298 		}
299 	}
300 
301 	/* Calculate dump size. */
302 	dumpsize = ptesize;
303 	dumpsize += round_page(msgbufp->msg_size);
304 	dumpsize += round_page(vm_page_dump_size);
305 
306 	for (i = 0; i < vm_page_dump_size / sizeof(*vm_page_dump); i++) {
307 		bits = vm_page_dump[i];
308 		while (bits) {
309 			bit = bsfq(bits);
310 			pa = (((uint64_t)i * sizeof(*vm_page_dump) * NBBY) + bit) * PAGE_SIZE;
311 			/* Clear out undumpable pages now if needed */
312 			if (is_dumpable(pa)) {
313 				dumpsize += PAGE_SIZE;
314 			} else {
315 				dump_drop_page(pa);
316 			}
317 			bits &= ~(1ul << bit);
318 		}
319 	}
320 	dumpsize += PAGE_SIZE;
321 
322 	/* Determine dump offset on device. */
323 	if (di->mediasize < SIZEOF_METADATA + dumpsize + sizeof(kdh) * 2) {
324 		error = ENOSPC;
325 		goto fail;
326 	}
327 	dumplo = di->mediaoffset + di->mediasize - dumpsize;
328 	dumplo -= sizeof(kdh) * 2;
329 	progress = dumpsize;
330 
331 	/* Initialize mdhdr */
332 	bzero(&mdhdr, sizeof(mdhdr));
333 	strcpy(mdhdr.magic, MINIDUMP2_MAGIC);
334 	mdhdr.version = MINIDUMP2_VERSION;
335 	mdhdr.msgbufsize = msgbufp->msg_size;
336 	mdhdr.bitmapsize = vm_page_dump_size;
337 	mdhdr.ptesize = ptesize;
338 	mdhdr.kernbase = VM_MIN_KERNEL_ADDRESS;
339 	mdhdr.dmapbase = DMAP_MIN_ADDRESS;
340 	mdhdr.dmapend = DMAP_MAX_ADDRESS;
341 
342 	mkdumpheader(&kdh, KERNELDUMPMAGIC, KERNELDUMP_AMD64_VERSION,
343 		     dumpsize, di->blocksize);
344 
345 	kprintf("Physical memory: %jd MB\n", (intmax_t)ptoa(physmem) / 1048576);
346 	kprintf("Dumping %jd MB:", (intmax_t)dumpsize >> 20);
347 
348 	/* Dump leader */
349 	error = dev_ddump(di->priv, &kdh, 0, dumplo, sizeof(kdh));
350 	if (error)
351 		goto fail;
352 	dumplo += sizeof(kdh);
353 
354 	/* Dump my header */
355 	bzero(fakept, sizeof(fakept));
356 	bcopy(&mdhdr, fakept, sizeof(mdhdr));
357 	error = blk_write(di, (char *)fakept, 0, PAGE_SIZE);
358 	if (error)
359 		goto fail;
360 
361 	/* Dump msgbuf up front */
362 	error = blk_write(di, (char *)msgbufp->msg_ptr, 0, round_page(msgbufp->msg_size));
363 	if (error)
364 		goto fail;
365 
366 	/* Dump bitmap */
367 	error = blk_write(di, (char *)vm_page_dump, 0, round_page(vm_page_dump_size));
368 	if (error)
369 		goto fail;
370 
371 	/*
372 	 * Dump a full PDP array for the entire KVM space, user and kernel.
373 	 * This is 512*512 1G PD entries (512*512*8 = 2MB).
374 	 *
375 	 * The minidump only dumps PD entries related to KVA space.  Also
376 	 * note that pdp[] (aka KPDPphys[]) only covers VM_MIN_KERNEL_ADDRESS
377 	 * to VM_MAX_KERNEL_ADDRESS.
378 	 *
379 	 * The actual KPDPphys[] array covers a KVA space starting at KVA
380 	 * KPDPPHYS_KVA.
381 	 *
382 	 * By dumping a PDP[] array of PDs representing the entire virtual
383 	 * address space we can expand what we dump in the future.
384 	 */
385 	pdp = (uint64_t *)PHYS_TO_DMAP(KPDPphys);
386 	kpdp = (KPDPPHYS_KVA >> PDPSHIFT) &
387 		    (NPML4EPG * NPDPEPG - 1);
388 	klo = (int)(VM_MIN_KERNEL_ADDRESS >> PDPSHIFT) &
389 		    (NPML4EPG * NPDPEPG - 1);
390 	khi = (int)(VM_MAX_KERNEL_ADDRESS >> PDPSHIFT) &
391 		    (NPML4EPG * NPDPEPG - 1);
392 
393 	for (i = 0; i < NPML4EPG * NPDPEPG; ++i) {
394 		if (i < klo || i > khi) {
395 			fakept[i & (NPDPEPG - 1)] = 0;
396 		} else {
397 			fakept[i & (NPDPEPG - 1)] = pdp[i - kpdp];
398 		}
399 		if ((i & (NPDPEPG - 1)) == (NPDPEPG - 1)) {
400 			error = blk_write(di, (char *)fakept, 0, PAGE_SIZE);
401 			if (error)
402 				goto fail;
403 			error = blk_flush(di);
404 			if (error)
405 				goto fail;
406 		}
407 	}
408 
409 	/* Dump memory chunks */
410 	/* XXX cluster it up and use blk_dump() */
411 	for (i = 0; i < vm_page_dump_size / sizeof(*vm_page_dump); i++) {
412 		bits = vm_page_dump[i];
413 		while (bits) {
414 			bit = bsfq(bits);
415 			pa = (((uint64_t)i * sizeof(*vm_page_dump) * NBBY) + bit) * PAGE_SIZE;
416 			error = blk_write(di, 0, pa, PAGE_SIZE);
417 			if (error)
418 				goto fail;
419 			bits &= ~(1ul << bit);
420 		}
421 	}
422 
423 	error = blk_flush(di);
424 	if (error)
425 		goto fail;
426 
427 	/* Dump trailer */
428 	error = dev_ddump(di->priv, &kdh, 0, dumplo, sizeof(kdh));
429 	if (error)
430 		goto fail;
431 	dumplo += sizeof(kdh);
432 
433 	/* Signal completion, signoff and exit stage left. */
434 	dev_ddump(di->priv, NULL, 0, 0, 0);
435 	kprintf("\nDump complete\n");
436 	cnpoll(FALSE);
437 	return;
438 
439  fail:
440 	cnpoll(FALSE);
441 	if (error < 0)
442 		error = -error;
443 
444 	if (error == ECANCELED)
445 		kprintf("\nDump aborted\n");
446 	else if (error == ENOSPC)
447 		kprintf("\nDump failed. Partition too small.\n");
448 	else
449 		kprintf("\n** DUMP FAILED (ERROR %d) **\n", error);
450 }
451 
452 void
453 dump_add_page(vm_paddr_t pa)
454 {
455 	int idx, bit;
456 
457 	pa >>= PAGE_SHIFT;
458 	idx = pa >> 6;		/* 2^6 = 64 */
459 	bit = pa & 63;
460 	atomic_set_long(&vm_page_dump[idx], 1ul << bit);
461 }
462 
463 void
464 dump_drop_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_clear_long(&vm_page_dump[idx], 1ul << bit);
472 }
473