xref: /freebsd/lib/libkvm/kvm_private.c (revision d0b2dbfa)
1 /*-
2  * Copyright (c) 1989, 1992, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software developed by the Computer Systems
6  * Engineering group at Lawrence Berkeley Laboratory under DARPA contract
7  * BG 91-66 and contributed to Berkeley.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 #include <sys/param.h>
36 #include <sys/fnv_hash.h>
37 
38 #define	_WANT_VNET
39 
40 #include <sys/user.h>
41 #include <sys/linker.h>
42 #include <sys/pcpu.h>
43 #include <sys/stat.h>
44 #include <sys/mman.h>
45 
46 #include <stdbool.h>
47 #include <net/vnet.h>
48 
49 #include <assert.h>
50 #include <fcntl.h>
51 #include <vm/vm.h>
52 #include <kvm.h>
53 #include <limits.h>
54 #include <paths.h>
55 #include <stdint.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 #include <stdarg.h>
61 #include <inttypes.h>
62 
63 #include "kvm_private.h"
64 
65 /*
66  * Routines private to libkvm.
67  */
68 
69 /* from src/lib/libc/gen/nlist.c */
70 int __fdnlist(int, struct nlist *);
71 
72 /*
73  * Report an error using printf style arguments.  "program" is kd->program
74  * on hard errors, and 0 on soft errors, so that under sun error emulation,
75  * only hard errors are printed out (otherwise, programs like gdb will
76  * generate tons of error messages when trying to access bogus pointers).
77  */
78 void
79 _kvm_err(kvm_t *kd, const char *program, const char *fmt, ...)
80 {
81 	va_list ap;
82 
83 	va_start(ap, fmt);
84 	if (program != NULL) {
85 		(void)fprintf(stderr, "%s: ", program);
86 		(void)vfprintf(stderr, fmt, ap);
87 		(void)fputc('\n', stderr);
88 	} else
89 		(void)vsnprintf(kd->errbuf,
90 		    sizeof(kd->errbuf), fmt, ap);
91 
92 	va_end(ap);
93 }
94 
95 void
96 _kvm_syserr(kvm_t *kd, const char *program, const char *fmt, ...)
97 {
98 	va_list ap;
99 	int n;
100 
101 	va_start(ap, fmt);
102 	if (program != NULL) {
103 		(void)fprintf(stderr, "%s: ", program);
104 		(void)vfprintf(stderr, fmt, ap);
105 		(void)fprintf(stderr, ": %s\n", strerror(errno));
106 	} else {
107 		char *cp = kd->errbuf;
108 
109 		(void)vsnprintf(cp, sizeof(kd->errbuf), fmt, ap);
110 		n = strlen(cp);
111 		(void)snprintf(&cp[n], sizeof(kd->errbuf) - n, ": %s",
112 		    strerror(errno));
113 	}
114 	va_end(ap);
115 }
116 
117 void *
118 _kvm_malloc(kvm_t *kd, size_t n)
119 {
120 	void *p;
121 
122 	if ((p = calloc(n, sizeof(char))) == NULL)
123 		_kvm_err(kd, kd->program, "can't allocate %zu bytes: %s",
124 			 n, strerror(errno));
125 	return (p);
126 }
127 
128 int
129 _kvm_probe_elf_kernel(kvm_t *kd, int class, int machine)
130 {
131 
132 	return (kd->nlehdr.e_ident[EI_CLASS] == class &&
133 	    ((machine == EM_PPC || machine == EM_PPC64) ?
134 	     kd->nlehdr.e_type == ET_DYN : kd->nlehdr.e_type == ET_EXEC) &&
135 	    kd->nlehdr.e_machine == machine);
136 }
137 
138 int
139 _kvm_is_minidump(kvm_t *kd)
140 {
141 	char minihdr[8];
142 
143 	if (kd->rawdump)
144 		return (0);
145 	if (pread(kd->pmfd, &minihdr, 8, 0) == 8 &&
146 	    memcmp(&minihdr, "minidump", 8) == 0)
147 		return (1);
148 	return (0);
149 }
150 
151 /*
152  * The powerpc backend has a hack to strip a leading kerneldump
153  * header from the core before treating it as an ELF header.
154  *
155  * We can add that here if we can get a change to libelf to support
156  * an initial offset into the file.  Alternatively we could patch
157  * savecore to extract cores from a regular file instead.
158  */
159 int
160 _kvm_read_core_phdrs(kvm_t *kd, size_t *phnump, GElf_Phdr **phdrp)
161 {
162 	GElf_Ehdr ehdr;
163 	GElf_Phdr *phdr;
164 	Elf *elf;
165 	size_t i, phnum;
166 
167 	elf = elf_begin(kd->pmfd, ELF_C_READ, NULL);
168 	if (elf == NULL) {
169 		_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
170 		return (-1);
171 	}
172 	if (elf_kind(elf) != ELF_K_ELF) {
173 		_kvm_err(kd, kd->program, "invalid core");
174 		goto bad;
175 	}
176 	if (gelf_getclass(elf) != kd->nlehdr.e_ident[EI_CLASS]) {
177 		_kvm_err(kd, kd->program, "invalid core");
178 		goto bad;
179 	}
180 	if (gelf_getehdr(elf, &ehdr) == NULL) {
181 		_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
182 		goto bad;
183 	}
184 	if (ehdr.e_type != ET_CORE) {
185 		_kvm_err(kd, kd->program, "invalid core");
186 		goto bad;
187 	}
188 	if (ehdr.e_machine != kd->nlehdr.e_machine) {
189 		_kvm_err(kd, kd->program, "invalid core");
190 		goto bad;
191 	}
192 
193 	if (elf_getphdrnum(elf, &phnum) == -1) {
194 		_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
195 		goto bad;
196 	}
197 
198 	phdr = calloc(phnum, sizeof(*phdr));
199 	if (phdr == NULL) {
200 		_kvm_err(kd, kd->program, "failed to allocate phdrs");
201 		goto bad;
202 	}
203 
204 	for (i = 0; i < phnum; i++) {
205 		if (gelf_getphdr(elf, i, &phdr[i]) == NULL) {
206 			free(phdr);
207 			_kvm_err(kd, kd->program, "%s", elf_errmsg(0));
208 			goto bad;
209 		}
210 	}
211 	elf_end(elf);
212 	*phnump = phnum;
213 	*phdrp = phdr;
214 	return (0);
215 
216 bad:
217 	elf_end(elf);
218 	return (-1);
219 }
220 
221 /*
222  * Transform v such that only bits [bit0, bitN) may be set.  Generates a
223  * bitmask covering the number of bits, then shifts so +bit0+ is the first.
224  */
225 static uint64_t
226 bitmask_range(uint64_t v, uint64_t bit0, uint64_t bitN)
227 {
228 	if (bit0 == 0 && bitN == BITS_IN(v))
229 		return (v);
230 
231 	return (v & (((1ULL << (bitN - bit0)) - 1ULL) << bit0));
232 }
233 
234 /*
235  * Returns the number of bits in a given byte array range starting at a
236  * given base, from bit0 to bitN.  bit0 may be non-zero in the case of
237  * counting backwards from bitN.
238  */
239 static uint64_t
240 popcount_bytes(uint64_t *addr, uint32_t bit0, uint32_t bitN)
241 {
242 	uint32_t res = bitN - bit0;
243 	uint64_t count = 0;
244 	uint32_t bound;
245 
246 	/* Align to 64-bit boundary on the left side if needed. */
247 	if ((bit0 % BITS_IN(*addr)) != 0) {
248 		bound = MIN(bitN, roundup2(bit0, BITS_IN(*addr)));
249 		count += __bitcount64(bitmask_range(*addr, bit0, bound));
250 		res -= (bound - bit0);
251 		addr++;
252 	}
253 
254 	while (res > 0) {
255 		bound = MIN(res, BITS_IN(*addr));
256 		count += __bitcount64(bitmask_range(*addr, 0, bound));
257 		res -= bound;
258 		addr++;
259 	}
260 
261 	return (count);
262 }
263 
264 void *
265 _kvm_pmap_get(kvm_t *kd, u_long idx, size_t len)
266 {
267 	uintptr_t off = idx * len;
268 
269 	if ((off_t)off >= kd->pt_sparse_off)
270 		return (NULL);
271 	return (void *)((uintptr_t)kd->page_map + off);
272 }
273 
274 void *
275 _kvm_map_get(kvm_t *kd, u_long pa, unsigned int page_size)
276 {
277 	off_t off;
278 	uintptr_t addr;
279 
280 	off = _kvm_pt_find(kd, pa, page_size);
281 	if (off == -1)
282 		return NULL;
283 
284 	addr = (uintptr_t)kd->page_map + off;
285 	if (off >= kd->pt_sparse_off)
286 		addr = (uintptr_t)kd->sparse_map + (off - kd->pt_sparse_off);
287 	return (void *)addr;
288 }
289 
290 int
291 _kvm_pt_init(kvm_t *kd, size_t dump_avail_size, off_t dump_avail_off,
292     size_t map_len, off_t map_off, off_t sparse_off, int page_size)
293 {
294 	uint64_t *addr;
295 	uint32_t *popcount_bin;
296 	int bin_popcounts = 0;
297 	uint64_t pc_bins, res;
298 	ssize_t rd;
299 
300 	kd->dump_avail_size = dump_avail_size;
301 	if (dump_avail_size > 0) {
302 		kd->dump_avail = mmap(NULL, kd->dump_avail_size, PROT_READ,
303 		    MAP_PRIVATE, kd->pmfd, dump_avail_off);
304 	} else {
305 		/*
306 		 * Older version minidumps don't provide dump_avail[],
307 		 * so the bitmap is fully populated from 0 to
308 		 * last_pa. Create an implied dump_avail that
309 		 * expresses this.
310 		 */
311 		kd->dump_avail = calloc(4, sizeof(uint64_t));
312 		kd->dump_avail[1] = _kvm64toh(kd, map_len * 8 * page_size);
313 	}
314 
315 	/*
316 	 * Map the bitmap specified by the arguments.
317 	 */
318 	kd->pt_map = _kvm_malloc(kd, map_len);
319 	if (kd->pt_map == NULL) {
320 		_kvm_err(kd, kd->program, "cannot allocate %zu bytes for bitmap",
321 		    map_len);
322 		return (-1);
323 	}
324 	rd = pread(kd->pmfd, kd->pt_map, map_len, map_off);
325 	if (rd < 0 || rd != (ssize_t)map_len) {
326 		_kvm_err(kd, kd->program, "cannot read %zu bytes for bitmap",
327 		    map_len);
328 		return (-1);
329 	}
330 	kd->pt_map_size = map_len;
331 
332 	/*
333 	 * Generate a popcount cache for every POPCOUNT_BITS in the bitmap,
334 	 * so lookups only have to calculate the number of bits set between
335 	 * a cache point and their bit.  This reduces lookups to O(1),
336 	 * without significantly increasing memory requirements.
337 	 *
338 	 * Round up the number of bins so that 'upper half' lookups work for
339 	 * the final bin, if needed.  The first popcount is 0, since no bits
340 	 * precede bit 0, so add 1 for that also.  Without this, extra work
341 	 * would be needed to handle the first PTEs in _kvm_pt_find().
342 	 */
343 	addr = kd->pt_map;
344 	res = map_len;
345 	pc_bins = 1 + (res * NBBY + POPCOUNT_BITS / 2) / POPCOUNT_BITS;
346 	kd->pt_popcounts = calloc(pc_bins, sizeof(uint32_t));
347 	if (kd->pt_popcounts == NULL) {
348 		_kvm_err(kd, kd->program, "cannot allocate popcount bins");
349 		return (-1);
350 	}
351 
352 	for (popcount_bin = &kd->pt_popcounts[1]; res > 0;
353 	    addr++, res -= sizeof(*addr)) {
354 		*popcount_bin += popcount_bytes(addr, 0,
355 		    MIN(res * NBBY, BITS_IN(*addr)));
356 		if (++bin_popcounts == POPCOUNTS_IN(*addr)) {
357 			popcount_bin++;
358 			*popcount_bin = *(popcount_bin - 1);
359 			bin_popcounts = 0;
360 		}
361 	}
362 
363 	assert(pc_bins * sizeof(*popcount_bin) ==
364 	    ((uintptr_t)popcount_bin - (uintptr_t)kd->pt_popcounts));
365 
366 	kd->pt_sparse_off = sparse_off;
367 	kd->pt_sparse_size = (uint64_t)*popcount_bin * page_size;
368 	kd->pt_page_size = page_size;
369 
370 	/*
371 	 * Map the sparse page array.  This is useful for performing point
372 	 * lookups of specific pages, e.g. for kvm_walk_pages.  Generally,
373 	 * this is much larger than is reasonable to read in up front, so
374 	 * mmap it in instead.
375 	 */
376 	kd->sparse_map = mmap(NULL, kd->pt_sparse_size, PROT_READ,
377 	    MAP_PRIVATE, kd->pmfd, kd->pt_sparse_off);
378 	if (kd->sparse_map == MAP_FAILED) {
379 		_kvm_err(kd, kd->program, "cannot map %" PRIu64
380 		    " bytes from fd %d offset %jd for sparse map: %s",
381 		    kd->pt_sparse_size, kd->pmfd,
382 		    (intmax_t)kd->pt_sparse_off, strerror(errno));
383 		return (-1);
384 	}
385 	return (0);
386 }
387 
388 int
389 _kvm_pmap_init(kvm_t *kd, uint32_t pmap_size, off_t pmap_off)
390 {
391 	ssize_t exp_len = pmap_size;
392 
393 	kd->page_map_size = pmap_size;
394 	kd->page_map_off = pmap_off;
395 	kd->page_map = _kvm_malloc(kd, pmap_size);
396 	if (kd->page_map == NULL) {
397 		_kvm_err(kd, kd->program, "cannot allocate %u bytes "
398 		    "for page map", pmap_size);
399 		return (-1);
400 	}
401 	if (pread(kd->pmfd, kd->page_map, pmap_size, pmap_off) != exp_len) {
402 		_kvm_err(kd, kd->program, "cannot read %d bytes from "
403 		    "offset %jd for page map", pmap_size, (intmax_t)pmap_off);
404 		return (-1);
405 	}
406 	return (0);
407 }
408 
409 static inline uint64_t
410 dump_avail_n(kvm_t *kd, long i)
411 {
412 	return (_kvm64toh(kd, kd->dump_avail[i]));
413 }
414 
415 uint64_t
416 _kvm_pa_bit_id(kvm_t *kd, uint64_t pa, unsigned int page_size)
417 {
418 	uint64_t adj;
419 	long i;
420 
421 	adj = 0;
422 	for (i = 0; dump_avail_n(kd, i + 1) != 0; i += 2) {
423 		if (pa >= dump_avail_n(kd, i + 1)) {
424 			adj += howmany(dump_avail_n(kd, i + 1), page_size) -
425 			    dump_avail_n(kd, i) / page_size;
426 		} else {
427 			return (pa / page_size -
428 			    dump_avail_n(kd, i) / page_size + adj);
429 		}
430 	}
431 	return (_KVM_BIT_ID_INVALID);
432 }
433 
434 uint64_t
435 _kvm_bit_id_pa(kvm_t *kd, uint64_t bit_id, unsigned int page_size)
436 {
437 	uint64_t sz;
438 	long i;
439 
440 	for (i = 0; dump_avail_n(kd, i + 1) != 0; i += 2) {
441 		sz = howmany(dump_avail_n(kd, i + 1), page_size) -
442 		    dump_avail_n(kd, i) / page_size;
443 		if (bit_id < sz) {
444 			return (rounddown2(dump_avail_n(kd, i), page_size) +
445 			    bit_id * page_size);
446 		}
447 		bit_id -= sz;
448 	}
449 	return (_KVM_PA_INVALID);
450 }
451 
452 /*
453  * Find the offset for the given physical page address; returns -1 otherwise.
454  *
455  * A page's offset is represented by the sparse page base offset plus the
456  * number of bits set before its bit multiplied by page size.  This means
457  * that if a page exists in the dump, it's necessary to know how many pages
458  * in the dump precede it.  Reduce this O(n) counting to O(1) by caching the
459  * number of bits set at POPCOUNT_BITS intervals.
460  *
461  * Then to find the number of pages before the requested address, simply
462  * index into the cache and count the number of bits set between that cache
463  * bin and the page's bit.  Halve the number of bytes that have to be
464  * checked by also counting down from the next higher bin if it's closer.
465  */
466 off_t
467 _kvm_pt_find(kvm_t *kd, uint64_t pa, unsigned int page_size)
468 {
469 	uint64_t *bitmap = kd->pt_map;
470 	uint64_t pte_bit_id = _kvm_pa_bit_id(kd, pa, page_size);
471 	uint64_t pte_u64 = pte_bit_id / BITS_IN(*bitmap);
472 	uint64_t popcount_id = pte_bit_id / POPCOUNT_BITS;
473 	uint64_t pte_mask = 1ULL << (pte_bit_id % BITS_IN(*bitmap));
474 	uint64_t bitN;
475 	uint32_t count;
476 
477 	/* Check whether the page address requested is in the dump. */
478 	if (pte_bit_id == _KVM_BIT_ID_INVALID ||
479 	    pte_bit_id >= (kd->pt_map_size * NBBY) ||
480 	    (bitmap[pte_u64] & pte_mask) == 0)
481 		return (-1);
482 
483 	/*
484 	 * Add/sub popcounts from the bitmap until the PTE's bit is reached.
485 	 * For bits that are in the upper half between the calculated
486 	 * popcount id and the next one, use the next one and subtract to
487 	 * minimize the number of popcounts required.
488 	 */
489 	if ((pte_bit_id % POPCOUNT_BITS) < (POPCOUNT_BITS / 2)) {
490 		count = kd->pt_popcounts[popcount_id] + popcount_bytes(
491 		    bitmap + popcount_id * POPCOUNTS_IN(*bitmap),
492 		    0, pte_bit_id - popcount_id * POPCOUNT_BITS);
493 	} else {
494 		/*
495 		 * Counting in reverse is trickier, since we must avoid
496 		 * reading from bytes that are not in range, and invert.
497 		 */
498 		uint64_t pte_u64_bit_off = pte_u64 * BITS_IN(*bitmap);
499 
500 		popcount_id++;
501 		bitN = MIN(popcount_id * POPCOUNT_BITS,
502 		    kd->pt_map_size * BITS_IN(uint8_t));
503 		count = kd->pt_popcounts[popcount_id] - popcount_bytes(
504 		    bitmap + pte_u64,
505 		    pte_bit_id - pte_u64_bit_off, bitN - pte_u64_bit_off);
506 	}
507 
508 	/*
509 	 * This can only happen if the core is truncated.  Treat these
510 	 * entries as if they don't exist, since their backing doesn't.
511 	 */
512 	if (count >= (kd->pt_sparse_size / page_size))
513 		return (-1);
514 
515 	return (kd->pt_sparse_off + (uint64_t)count * page_size);
516 }
517 
518 static int
519 kvm_fdnlist(kvm_t *kd, struct kvm_nlist *list)
520 {
521 	kvaddr_t addr;
522 	int error, nfail;
523 
524 	if (kd->resolve_symbol == NULL) {
525 		struct nlist *nl;
526 		int count, i;
527 
528 		for (count = 0; list[count].n_name != NULL &&
529 		     list[count].n_name[0] != '\0'; count++)
530 			;
531 		nl = calloc(count + 1, sizeof(*nl));
532 		for (i = 0; i < count; i++)
533 			nl[i].n_name = list[i].n_name;
534 		nfail = __fdnlist(kd->nlfd, nl);
535 		for (i = 0; i < count; i++) {
536 			list[i].n_type = nl[i].n_type;
537 			list[i].n_value = nl[i].n_value;
538 		}
539 		free(nl);
540 		return (nfail);
541 	}
542 
543 	nfail = 0;
544 	while (list->n_name != NULL && list->n_name[0] != '\0') {
545 		error = kd->resolve_symbol(list->n_name, &addr);
546 		if (error != 0) {
547 			nfail++;
548 			list->n_value = 0;
549 			list->n_type = 0;
550 		} else {
551 			list->n_value = addr;
552 			list->n_type = N_DATA | N_EXT;
553 		}
554 		list++;
555 	}
556 	return (nfail);
557 }
558 
559 /*
560  * Walk the list of unresolved symbols, generate a new list and prefix the
561  * symbol names, try again, and merge back what we could resolve.
562  */
563 static int
564 kvm_fdnlist_prefix(kvm_t *kd, struct kvm_nlist *nl, int missing,
565     const char *prefix, kvaddr_t (*validate_fn)(kvm_t *, kvaddr_t))
566 {
567 	struct kvm_nlist *n, *np, *p;
568 	char *cp, *ce;
569 	const char *ccp;
570 	size_t len;
571 	int slen, unresolved;
572 
573 	/*
574 	 * Calculate the space we need to malloc for nlist and names.
575 	 * We are going to store the name twice for later lookups: once
576 	 * with the prefix and once the unmodified name delmited by \0.
577 	 */
578 	len = 0;
579 	unresolved = 0;
580 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
581 		if (p->n_type != N_UNDF)
582 			continue;
583 		len += sizeof(struct kvm_nlist) + strlen(prefix) +
584 		    2 * (strlen(p->n_name) + 1);
585 		unresolved++;
586 	}
587 	if (unresolved == 0)
588 		return (unresolved);
589 	/* Add space for the terminating nlist entry. */
590 	len += sizeof(struct kvm_nlist);
591 	unresolved++;
592 
593 	/* Alloc one chunk for (nlist, [names]) and setup pointers. */
594 	n = np = malloc(len);
595 	bzero(n, len);
596 	if (n == NULL)
597 		return (missing);
598 	cp = ce = (char *)np;
599 	cp += unresolved * sizeof(struct kvm_nlist);
600 	ce += len;
601 
602 	/* Generate shortened nlist with special prefix. */
603 	unresolved = 0;
604 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
605 		if (p->n_type != N_UNDF)
606 			continue;
607 		*np = *p;
608 		/* Save the new\0orig. name so we can later match it again. */
609 		slen = snprintf(cp, ce - cp, "%s%s%c%s", prefix,
610 		    (prefix[0] != '\0' && p->n_name[0] == '_') ?
611 			(p->n_name + 1) : p->n_name, '\0', p->n_name);
612 		if (slen < 0 || slen >= ce - cp)
613 			continue;
614 		np->n_name = cp;
615 		cp += slen + 1;
616 		np++;
617 		unresolved++;
618 	}
619 
620 	/* Do lookup on the reduced list. */
621 	np = n;
622 	unresolved = kvm_fdnlist(kd, np);
623 
624 	/* Check if we could resolve further symbols and update the list. */
625 	if (unresolved >= 0 && unresolved < missing) {
626 		/* Find the first freshly resolved entry. */
627 		for (; np->n_name && np->n_name[0]; np++)
628 			if (np->n_type != N_UNDF)
629 				break;
630 		/*
631 		 * The lists are both in the same order,
632 		 * so we can walk them in parallel.
633 		 */
634 		for (p = nl; np->n_name && np->n_name[0] &&
635 		    p->n_name && p->n_name[0]; ++p) {
636 			if (p->n_type != N_UNDF)
637 				continue;
638 			/* Skip expanded name and compare to orig. one. */
639 			ccp = np->n_name + strlen(np->n_name) + 1;
640 			if (strcmp(ccp, p->n_name) != 0)
641 				continue;
642 			/* Update nlist with new, translated results. */
643 			p->n_type = np->n_type;
644 			if (validate_fn)
645 				p->n_value = (*validate_fn)(kd, np->n_value);
646 			else
647 				p->n_value = np->n_value;
648 			missing--;
649 			/* Find next freshly resolved entry. */
650 			for (np++; np->n_name && np->n_name[0]; np++)
651 				if (np->n_type != N_UNDF)
652 					break;
653 		}
654 	}
655 	/* We could assert missing = unresolved here. */
656 
657 	free(n);
658 	return (unresolved);
659 }
660 
661 int
662 _kvm_nlist(kvm_t *kd, struct kvm_nlist *nl, int initialize)
663 {
664 	struct kvm_nlist *p;
665 	int nvalid;
666 	struct kld_sym_lookup lookup;
667 	int error;
668 	const char *prefix = "";
669 	char symname[1024]; /* XXX-BZ symbol name length limit? */
670 	int tried_vnet, tried_dpcpu;
671 
672 	/*
673 	 * If we can't use the kld symbol lookup, revert to the
674 	 * slow library call.
675 	 */
676 	if (!ISALIVE(kd)) {
677 		error = kvm_fdnlist(kd, nl);
678 		if (error <= 0)			/* Hard error or success. */
679 			return (error);
680 
681 		if (_kvm_vnet_initialized(kd, initialize))
682 			error = kvm_fdnlist_prefix(kd, nl, error,
683 			    VNET_SYMPREFIX, _kvm_vnet_validaddr);
684 
685 		if (error > 0 && _kvm_dpcpu_initialized(kd, initialize))
686 			error = kvm_fdnlist_prefix(kd, nl, error,
687 			    DPCPU_SYMPREFIX, _kvm_dpcpu_validaddr);
688 
689 		return (error);
690 	}
691 
692 	/*
693 	 * We can use the kld lookup syscall.  Go through each nlist entry
694 	 * and look it up with a kldsym(2) syscall.
695 	 */
696 	nvalid = 0;
697 	tried_vnet = 0;
698 	tried_dpcpu = 0;
699 again:
700 	for (p = nl; p->n_name && p->n_name[0]; ++p) {
701 		if (p->n_type != N_UNDF)
702 			continue;
703 
704 		lookup.version = sizeof(lookup);
705 		lookup.symvalue = 0;
706 		lookup.symsize = 0;
707 
708 		error = snprintf(symname, sizeof(symname), "%s%s", prefix,
709 		    (prefix[0] != '\0' && p->n_name[0] == '_') ?
710 			(p->n_name + 1) : p->n_name);
711 		if (error < 0 || error >= (int)sizeof(symname))
712 			continue;
713 		lookup.symname = symname;
714 		if (lookup.symname[0] == '_')
715 			lookup.symname++;
716 
717 		if (kldsym(0, KLDSYM_LOOKUP, &lookup) != -1) {
718 			p->n_type = N_TEXT;
719 			if (_kvm_vnet_initialized(kd, initialize) &&
720 			    strcmp(prefix, VNET_SYMPREFIX) == 0)
721 				p->n_value =
722 				    _kvm_vnet_validaddr(kd, lookup.symvalue);
723 			else if (_kvm_dpcpu_initialized(kd, initialize) &&
724 			    strcmp(prefix, DPCPU_SYMPREFIX) == 0)
725 				p->n_value =
726 				    _kvm_dpcpu_validaddr(kd, lookup.symvalue);
727 			else
728 				p->n_value = lookup.symvalue;
729 			++nvalid;
730 			/* lookup.symsize */
731 		}
732 	}
733 
734 	/*
735 	 * Check the number of entries that weren't found. If they exist,
736 	 * try again with a prefix for virtualized or DPCPU symbol names.
737 	 */
738 	error = ((p - nl) - nvalid);
739 	if (error && _kvm_vnet_initialized(kd, initialize) && !tried_vnet) {
740 		tried_vnet = 1;
741 		prefix = VNET_SYMPREFIX;
742 		goto again;
743 	}
744 	if (error && _kvm_dpcpu_initialized(kd, initialize) && !tried_dpcpu) {
745 		tried_dpcpu = 1;
746 		prefix = DPCPU_SYMPREFIX;
747 		goto again;
748 	}
749 
750 	/*
751 	 * Return the number of entries that weren't found. If they exist,
752 	 * also fill internal error buffer.
753 	 */
754 	error = ((p - nl) - nvalid);
755 	if (error)
756 		_kvm_syserr(kd, kd->program, "kvm_nlist");
757 	return (error);
758 }
759 
760 int
761 _kvm_bitmap_init(struct kvm_bitmap *bm, u_long bitmapsize, u_long *idx)
762 {
763 
764 	*idx = ULONG_MAX;
765 	bm->map = calloc(bitmapsize, sizeof *bm->map);
766 	if (bm->map == NULL)
767 		return (0);
768 	bm->size = bitmapsize;
769 	return (1);
770 }
771 
772 void
773 _kvm_bitmap_set(struct kvm_bitmap *bm, u_long bm_index)
774 {
775 	uint8_t *byte = &bm->map[bm_index / 8];
776 
777 	if (bm_index / 8 < bm->size)
778 		*byte |= (1UL << (bm_index % 8));
779 }
780 
781 int
782 _kvm_bitmap_next(struct kvm_bitmap *bm, u_long *idx)
783 {
784 	u_long first_invalid = bm->size * CHAR_BIT;
785 
786 	if (*idx == ULONG_MAX)
787 		*idx = 0;
788 	else
789 		(*idx)++;
790 
791 	/* Find the next valid idx. */
792 	for (; *idx < first_invalid; (*idx)++) {
793 		unsigned int mask = 1U << (*idx % CHAR_BIT);
794 		if ((bm->map[*idx / CHAR_BIT] & mask) != 0)
795 			break;
796 	}
797 
798 	return (*idx < first_invalid);
799 }
800 
801 void
802 _kvm_bitmap_deinit(struct kvm_bitmap *bm)
803 {
804 
805 	free(bm->map);
806 }
807 
808 int
809 _kvm_visit_cb(kvm_t *kd, kvm_walk_pages_cb_t *cb, void *arg, u_long pa,
810     u_long kmap_vaddr, u_long dmap_vaddr, vm_prot_t prot, size_t len,
811     unsigned int page_size)
812 {
813 	unsigned int pgsz = page_size ? page_size : len;
814 	struct kvm_page p = {
815 		.kp_version = LIBKVM_WALK_PAGES_VERSION,
816 		.kp_paddr = pa,
817 		.kp_kmap_vaddr = kmap_vaddr,
818 		.kp_dmap_vaddr = dmap_vaddr,
819 		.kp_prot = prot,
820 		.kp_offset = _kvm_pt_find(kd, pa, pgsz),
821 		.kp_len = len,
822 	};
823 
824 	return cb(&p, arg);
825 }
826