xref: /freebsd/usr.sbin/pciconf/pciconf.c (revision af23369a6deaaeb612ab266eb88b8bb8d560c322)
1 /*
2  * Copyright 1996 Massachusetts Institute of Technology
3  *
4  * Permission to use, copy, modify, and distribute this software and
5  * its documentation for any purpose and without fee is hereby
6  * granted, provided that both the above copyright notice and this
7  * permission notice appear in all copies, that both the above
8  * copyright notice and this permission notice appear in all
9  * supporting documentation, and that the name of M.I.T. not be used
10  * in advertising or publicity pertaining to distribution of the
11  * software without specific, written prior permission.  M.I.T. makes
12  * no representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied
14  * warranty.
15  *
16  * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
17  * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
18  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
20  * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifndef lint
31 static const char rcsid[] =
32   "$FreeBSD$";
33 #endif /* not lint */
34 
35 #include <sys/types.h>
36 #include <sys/fcntl.h>
37 #include <sys/mman.h>
38 #include <sys/pciio.h>
39 #include <sys/queue.h>
40 
41 #include <vm/vm.h>
42 
43 #include <dev/pci/pcireg.h>
44 
45 #include <assert.h>
46 #include <ctype.h>
47 #include <err.h>
48 #include <inttypes.h>
49 #include <stdbool.h>
50 #include <stdlib.h>
51 #include <stdio.h>
52 #include <string.h>
53 #include <unistd.h>
54 
55 #include "pathnames.h"
56 #include "pciconf.h"
57 
58 struct pci_device_info
59 {
60     TAILQ_ENTRY(pci_device_info)	link;
61     int					id;
62     char				*desc;
63 };
64 
65 struct pci_vendor_info
66 {
67     TAILQ_ENTRY(pci_vendor_info)	link;
68     TAILQ_HEAD(,pci_device_info)	devs;
69     int					id;
70     char				*desc;
71 };
72 
73 static TAILQ_HEAD(,pci_vendor_info)	pci_vendors;
74 
75 static struct pcisel getsel(const char *str);
76 static void list_bridge(int fd, struct pci_conf *p);
77 static void list_bars(int fd, struct pci_conf *p);
78 static void list_devs(const char *name, int verbose, int bars, int bridge,
79     int caps, int errors, int vpd, int listmode);
80 static void list_verbose(struct pci_conf *p);
81 static void list_vpd(int fd, struct pci_conf *p);
82 static const char *guess_class(struct pci_conf *p);
83 static const char *guess_subclass(struct pci_conf *p);
84 static int load_vendors(void);
85 static void readit(const char *, const char *, int);
86 static void writeit(const char *, const char *, const char *, int);
87 static void chkattached(const char *);
88 static void dump_bar(const char *name, const char *reg, const char *bar_start,
89     const char *bar_count, int width, int verbose);
90 
91 static int exitstatus = 0;
92 
93 static void
94 usage(void)
95 {
96 
97 	fprintf(stderr, "%s",
98 		"usage: pciconf -l [-BbcevV] [device]\n"
99 		"       pciconf -a device\n"
100 		"       pciconf -r [-b | -h] device addr[:addr2]\n"
101 		"       pciconf -w [-b | -h] device addr value\n"
102 		"       pciconf -D [-b | -h | -x] device bar [start [count]]"
103 		"\n");
104 	exit(1);
105 }
106 
107 int
108 main(int argc, char **argv)
109 {
110 	int c, width;
111 	int listmode, readmode, writemode, attachedmode, dumpbarmode;
112 	int bars, bridge, caps, errors, verbose, vpd;
113 
114 	listmode = readmode = writemode = attachedmode = dumpbarmode = 0;
115 	bars = bridge = caps = errors = verbose = vpd= 0;
116 	width = 4;
117 
118 	while ((c = getopt(argc, argv, "aBbcDehlrwVv")) != -1) {
119 		switch(c) {
120 		case 'a':
121 			attachedmode = 1;
122 			break;
123 
124 		case 'B':
125 			bridge = 1;
126 			break;
127 
128 		case 'b':
129 			bars = 1;
130 			width = 1;
131 			break;
132 
133 		case 'c':
134 			caps++;
135 			break;
136 
137 		case 'D':
138 			dumpbarmode = 1;
139 			break;
140 
141 		case 'e':
142 			errors = 1;
143 			break;
144 
145 		case 'h':
146 			width = 2;
147 			break;
148 
149 		case 'l':
150 			listmode++;
151 			break;
152 
153 		case 'r':
154 			readmode = 1;
155 			break;
156 
157 		case 'w':
158 			writemode = 1;
159 			break;
160 
161 		case 'v':
162 			verbose = 1;
163 			break;
164 
165 		case 'V':
166 			vpd = 1;
167 			break;
168 
169 		case 'x':
170 			width = 8;
171 			break;
172 
173 		default:
174 			usage();
175 		}
176 	}
177 
178 	if ((listmode && optind >= argc + 1)
179 	    || (writemode && optind + 3 != argc)
180 	    || (readmode && optind + 2 != argc)
181 	    || (attachedmode && optind + 1 != argc)
182 	    || (dumpbarmode && (optind + 2 > argc || optind + 4 < argc))
183 	    || (width == 8 && !dumpbarmode))
184 		usage();
185 
186 	if (listmode) {
187 		list_devs(optind + 1 == argc ? argv[optind] : NULL, verbose,
188 		    bars, bridge, caps, errors, vpd, listmode);
189 	} else if (attachedmode) {
190 		chkattached(argv[optind]);
191 	} else if (readmode) {
192 		readit(argv[optind], argv[optind + 1], width);
193 	} else if (writemode) {
194 		writeit(argv[optind], argv[optind + 1], argv[optind + 2],
195 		    width);
196 	} else if (dumpbarmode) {
197 		dump_bar(argv[optind], argv[optind + 1],
198 		    optind + 2 < argc ? argv[optind + 2] : NULL,
199 		    optind + 3 < argc ? argv[optind + 3] : NULL,
200 		    width, verbose);
201 	} else {
202 		usage();
203 	}
204 
205 	return (exitstatus);
206 }
207 
208 static void
209 list_devs(const char *name, int verbose, int bars, int bridge, int caps,
210     int errors, int vpd, int listmode)
211 {
212 	int fd;
213 	struct pci_conf_io pc;
214 	struct pci_conf conf[255], *p;
215 	struct pci_match_conf patterns[1];
216 	int none_count = 0;
217 
218 	if (verbose)
219 		load_vendors();
220 
221 	fd = open(_PATH_DEVPCI, (bridge || caps || errors) ? O_RDWR : O_RDONLY,
222 	    0);
223 	if (fd < 0)
224 		err(1, "%s", _PATH_DEVPCI);
225 
226 	bzero(&pc, sizeof(struct pci_conf_io));
227 	pc.match_buf_len = sizeof(conf);
228 	pc.matches = conf;
229 	if (name != NULL) {
230 		bzero(&patterns, sizeof(patterns));
231 		patterns[0].pc_sel = getsel(name);
232 		patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN |
233 		    PCI_GETCONF_MATCH_BUS | PCI_GETCONF_MATCH_DEV |
234 		    PCI_GETCONF_MATCH_FUNC;
235 		pc.num_patterns = 1;
236 		pc.pat_buf_len = sizeof(patterns);
237 		pc.patterns = patterns;
238 	}
239 
240 	do {
241 		if (ioctl(fd, PCIOCGETCONF, &pc) == -1)
242 			err(1, "ioctl(PCIOCGETCONF)");
243 
244 		/*
245 		 * 255 entries should be more than enough for most people,
246 		 * but if someone has more devices, and then changes things
247 		 * around between ioctls, we'll do the cheesy thing and
248 		 * just bail.  The alternative would be to go back to the
249 		 * beginning of the list, and print things twice, which may
250 		 * not be desirable.
251 		 */
252 		if (pc.status == PCI_GETCONF_LIST_CHANGED) {
253 			warnx("PCI device list changed, please try again");
254 			exitstatus = 1;
255 			close(fd);
256 			return;
257 		} else if (pc.status ==  PCI_GETCONF_ERROR) {
258 			warnx("error returned from PCIOCGETCONF ioctl");
259 			exitstatus = 1;
260 			close(fd);
261 			return;
262 		}
263 		if (listmode == 2)
264 			printf("drv\tselector\tclass    rev  hdr  "
265 			    "vendor device subven subdev\n");
266 		for (p = conf; p < &conf[pc.num_matches]; p++) {
267 			if (listmode == 2)
268 				printf("%s%d@pci%d:%d:%d:%d:"
269 				    "\t%06x   %02x   %02x   "
270 				    "%04x   %04x   %04x   %04x\n",
271 				    *p->pd_name ? p->pd_name : "none",
272 				    *p->pd_name ? (int)p->pd_unit :
273 				    none_count++, p->pc_sel.pc_domain,
274 				    p->pc_sel.pc_bus, p->pc_sel.pc_dev,
275 				    p->pc_sel.pc_func, (p->pc_class << 16) |
276 				    (p->pc_subclass << 8) | p->pc_progif,
277 				    p->pc_revid, p->pc_hdr,
278 				    p->pc_vendor, p->pc_device,
279 				    p->pc_subvendor, p->pc_subdevice);
280 			else
281 				printf("%s%d@pci%d:%d:%d:%d:"
282 				    "\tclass=0x%06x rev=0x%02x hdr=0x%02x "
283 				    "vendor=0x%04x device=0x%04x "
284 				    "subvendor=0x%04x subdevice=0x%04x\n",
285 				    *p->pd_name ? p->pd_name : "none",
286 				    *p->pd_name ? (int)p->pd_unit :
287 				    none_count++, p->pc_sel.pc_domain,
288 				    p->pc_sel.pc_bus, p->pc_sel.pc_dev,
289 				    p->pc_sel.pc_func, (p->pc_class << 16) |
290 				    (p->pc_subclass << 8) | p->pc_progif,
291 				    p->pc_revid, p->pc_hdr,
292 				    p->pc_vendor, p->pc_device,
293 				    p->pc_subvendor, p->pc_subdevice);
294 			if (verbose)
295 				list_verbose(p);
296 			if (bars)
297 				list_bars(fd, p);
298 			if (bridge)
299 				list_bridge(fd, p);
300 			if (caps)
301 				list_caps(fd, p, caps);
302 			if (errors)
303 				list_errors(fd, p);
304 			if (vpd)
305 				list_vpd(fd, p);
306 		}
307 	} while (pc.status == PCI_GETCONF_MORE_DEVS);
308 
309 	close(fd);
310 }
311 
312 static void
313 print_bus_range(int fd, struct pci_conf *p, int secreg, int subreg)
314 {
315 	uint8_t secbus, subbus;
316 
317 	secbus = read_config(fd, &p->pc_sel, secreg, 1);
318 	subbus = read_config(fd, &p->pc_sel, subreg, 1);
319 	printf("    bus range  = %u-%u\n", secbus, subbus);
320 }
321 
322 static void
323 print_window(int reg, const char *type, int range, uint64_t base,
324     uint64_t limit)
325 {
326 
327 	printf("    window[%02x] = type %s, range %2d, addr %#jx-%#jx, %s\n",
328 	    reg, type, range, (uintmax_t)base, (uintmax_t)limit,
329 	    base < limit ? "enabled" : "disabled");
330 }
331 
332 static void
333 print_special_decode(bool isa, bool vga, bool subtractive)
334 {
335 	bool comma;
336 
337 	if (isa || vga || subtractive) {
338 		comma = false;
339 		printf("    decode     = ");
340 		if (isa) {
341 			printf("ISA");
342 			comma = true;
343 		}
344 		if (vga) {
345 			printf("%sVGA", comma ? ", " : "");
346 			comma = true;
347 		}
348 		if (subtractive)
349 			printf("%ssubtractive", comma ? ", " : "");
350 		printf("\n");
351 	}
352 }
353 
354 static void
355 print_bridge_windows(int fd, struct pci_conf *p)
356 {
357 	uint64_t base, limit;
358 	uint32_t val;
359 	uint16_t bctl;
360 	bool subtractive;
361 	int range;
362 
363 	/*
364 	 * XXX: This assumes that a window with a base and limit of 0
365 	 * is not implemented.  In theory a window might be programmed
366 	 * at the smallest size with a base of 0, but those do not seem
367 	 * common in practice.
368 	 */
369 	val = read_config(fd, &p->pc_sel, PCIR_IOBASEL_1, 1);
370 	if (val != 0 || read_config(fd, &p->pc_sel, PCIR_IOLIMITL_1, 1) != 0) {
371 		if ((val & PCIM_BRIO_MASK) == PCIM_BRIO_32) {
372 			base = PCI_PPBIOBASE(
373 			    read_config(fd, &p->pc_sel, PCIR_IOBASEH_1, 2),
374 			    val);
375 			limit = PCI_PPBIOLIMIT(
376 			    read_config(fd, &p->pc_sel, PCIR_IOLIMITH_1, 2),
377 			    read_config(fd, &p->pc_sel, PCIR_IOLIMITL_1, 1));
378 			range = 32;
379 		} else {
380 			base = PCI_PPBIOBASE(0, val);
381 			limit = PCI_PPBIOLIMIT(0,
382 			    read_config(fd, &p->pc_sel, PCIR_IOLIMITL_1, 1));
383 			range = 16;
384 		}
385 		print_window(PCIR_IOBASEL_1, "I/O Port", range, base, limit);
386 	}
387 
388 	base = PCI_PPBMEMBASE(0,
389 	    read_config(fd, &p->pc_sel, PCIR_MEMBASE_1, 2));
390 	limit = PCI_PPBMEMLIMIT(0,
391 	    read_config(fd, &p->pc_sel, PCIR_MEMLIMIT_1, 2));
392 	print_window(PCIR_MEMBASE_1, "Memory", 32, base, limit);
393 
394 	val = read_config(fd, &p->pc_sel, PCIR_PMBASEL_1, 2);
395 	if (val != 0 || read_config(fd, &p->pc_sel, PCIR_PMLIMITL_1, 2) != 0) {
396 		if ((val & PCIM_BRPM_MASK) == PCIM_BRPM_64) {
397 			base = PCI_PPBMEMBASE(
398 			    read_config(fd, &p->pc_sel, PCIR_PMBASEH_1, 4),
399 			    val);
400 			limit = PCI_PPBMEMLIMIT(
401 			    read_config(fd, &p->pc_sel, PCIR_PMLIMITH_1, 4),
402 			    read_config(fd, &p->pc_sel, PCIR_PMLIMITL_1, 2));
403 			range = 64;
404 		} else {
405 			base = PCI_PPBMEMBASE(0, val);
406 			limit = PCI_PPBMEMLIMIT(0,
407 			    read_config(fd, &p->pc_sel, PCIR_PMLIMITL_1, 2));
408 			range = 32;
409 		}
410 		print_window(PCIR_PMBASEL_1, "Prefetchable Memory", range, base,
411 		    limit);
412 	}
413 
414 	/*
415 	 * XXX: This list of bridges that are subtractive but do not set
416 	 * progif to indicate it is copied from pci_pci.c.
417 	 */
418 	subtractive = p->pc_progif == PCIP_BRIDGE_PCI_SUBTRACTIVE;
419 	switch (p->pc_device << 16 | p->pc_vendor) {
420 	case 0xa002177d:		/* Cavium ThunderX */
421 	case 0x124b8086:		/* Intel 82380FB Mobile */
422 	case 0x060513d7:		/* Toshiba ???? */
423 		subtractive = true;
424 	}
425 	if (p->pc_vendor == 0x8086 && (p->pc_device & 0xff00) == 0x2400)
426 		subtractive = true;
427 
428 	bctl = read_config(fd, &p->pc_sel, PCIR_BRIDGECTL_1, 2);
429 	print_special_decode(bctl & PCIB_BCR_ISA_ENABLE,
430 	    bctl & PCIB_BCR_VGA_ENABLE, subtractive);
431 }
432 
433 static void
434 print_cardbus_mem_window(int fd, struct pci_conf *p, int basereg, int limitreg,
435     bool prefetch)
436 {
437 
438 	print_window(basereg, prefetch ? "Prefetchable Memory" : "Memory", 32,
439 	    PCI_CBBMEMBASE(read_config(fd, &p->pc_sel, basereg, 4)),
440 	    PCI_CBBMEMLIMIT(read_config(fd, &p->pc_sel, limitreg, 4)));
441 }
442 
443 static void
444 print_cardbus_io_window(int fd, struct pci_conf *p, int basereg, int limitreg)
445 {
446 	uint32_t base, limit;
447 	uint32_t val;
448 	int range;
449 
450 	val = read_config(fd, &p->pc_sel, basereg, 2);
451 	if ((val & PCIM_CBBIO_MASK) == PCIM_CBBIO_32) {
452 		base = PCI_CBBIOBASE(read_config(fd, &p->pc_sel, basereg, 4));
453 		limit = PCI_CBBIOBASE(read_config(fd, &p->pc_sel, limitreg, 4));
454 		range = 32;
455 	} else {
456 		base = PCI_CBBIOBASE(val);
457 		limit = PCI_CBBIOBASE(read_config(fd, &p->pc_sel, limitreg, 2));
458 		range = 16;
459 	}
460 	print_window(basereg, "I/O Port", range, base, limit);
461 }
462 
463 static void
464 print_cardbus_windows(int fd, struct pci_conf *p)
465 {
466 	uint16_t bctl;
467 
468 	bctl = read_config(fd, &p->pc_sel, PCIR_BRIDGECTL_2, 2);
469 	print_cardbus_mem_window(fd, p, PCIR_MEMBASE0_2, PCIR_MEMLIMIT0_2,
470 	    bctl & CBB_BCR_PREFETCH_0_ENABLE);
471 	print_cardbus_mem_window(fd, p, PCIR_MEMBASE1_2, PCIR_MEMLIMIT1_2,
472 	    bctl & CBB_BCR_PREFETCH_1_ENABLE);
473 	print_cardbus_io_window(fd, p, PCIR_IOBASE0_2, PCIR_IOLIMIT0_2);
474 	print_cardbus_io_window(fd, p, PCIR_IOBASE1_2, PCIR_IOLIMIT1_2);
475 	print_special_decode(bctl & CBB_BCR_ISA_ENABLE,
476 	    bctl & CBB_BCR_VGA_ENABLE, false);
477 }
478 
479 static void
480 list_bridge(int fd, struct pci_conf *p)
481 {
482 
483 	switch (p->pc_hdr & PCIM_HDRTYPE) {
484 	case PCIM_HDRTYPE_BRIDGE:
485 		print_bus_range(fd, p, PCIR_SECBUS_1, PCIR_SUBBUS_1);
486 		print_bridge_windows(fd, p);
487 		break;
488 	case PCIM_HDRTYPE_CARDBUS:
489 		print_bus_range(fd, p, PCIR_SECBUS_2, PCIR_SUBBUS_2);
490 		print_cardbus_windows(fd, p);
491 		break;
492 	}
493 }
494 
495 static void
496 list_bars(int fd, struct pci_conf *p)
497 {
498 	int i, max;
499 
500 	switch (p->pc_hdr & PCIM_HDRTYPE) {
501 	case PCIM_HDRTYPE_NORMAL:
502 		max = PCIR_MAX_BAR_0;
503 		break;
504 	case PCIM_HDRTYPE_BRIDGE:
505 		max = PCIR_MAX_BAR_1;
506 		break;
507 	case PCIM_HDRTYPE_CARDBUS:
508 		max = PCIR_MAX_BAR_2;
509 		break;
510 	default:
511 		return;
512 	}
513 
514 	for (i = 0; i <= max; i++)
515 		print_bar(fd, p, "bar   ", PCIR_BAR(i));
516 }
517 
518 void
519 print_bar(int fd, struct pci_conf *p, const char *label, uint16_t bar_offset)
520 {
521 	uint64_t base;
522 	const char *type;
523 	struct pci_bar_io bar;
524 	int range;
525 
526 	bar.pbi_sel = p->pc_sel;
527 	bar.pbi_reg = bar_offset;
528 	if (ioctl(fd, PCIOCGETBAR, &bar) < 0)
529 		return;
530 	if (PCI_BAR_IO(bar.pbi_base)) {
531 		type = "I/O Port";
532 		range = 32;
533 		base = bar.pbi_base & PCIM_BAR_IO_BASE;
534 	} else {
535 		if (bar.pbi_base & PCIM_BAR_MEM_PREFETCH)
536 			type = "Prefetchable Memory";
537 		else
538 			type = "Memory";
539 		switch (bar.pbi_base & PCIM_BAR_MEM_TYPE) {
540 		case PCIM_BAR_MEM_32:
541 			range = 32;
542 			break;
543 		case PCIM_BAR_MEM_1MB:
544 			range = 20;
545 			break;
546 		case PCIM_BAR_MEM_64:
547 			range = 64;
548 			break;
549 		default:
550 			range = -1;
551 		}
552 		base = bar.pbi_base & ~((uint64_t)0xf);
553 	}
554 	printf("    %s[%02x] = type %s, range %2d, base %#jx, ",
555 	    label, bar_offset, type, range, (uintmax_t)base);
556 	printf("size %ju, %s\n", (uintmax_t)bar.pbi_length,
557 	    bar.pbi_enabled ? "enabled" : "disabled");
558 }
559 
560 static void
561 list_verbose(struct pci_conf *p)
562 {
563 	struct pci_vendor_info	*vi;
564 	struct pci_device_info	*di;
565 	const char *dp;
566 
567 	TAILQ_FOREACH(vi, &pci_vendors, link) {
568 		if (vi->id == p->pc_vendor) {
569 			printf("    vendor     = '%s'\n", vi->desc);
570 			break;
571 		}
572 	}
573 	if (vi == NULL) {
574 		di = NULL;
575 	} else {
576 		TAILQ_FOREACH(di, &vi->devs, link) {
577 			if (di->id == p->pc_device) {
578 				printf("    device     = '%s'\n", di->desc);
579 				break;
580 			}
581 		}
582 	}
583 	if ((dp = guess_class(p)) != NULL)
584 		printf("    class      = %s\n", dp);
585 	if ((dp = guess_subclass(p)) != NULL)
586 		printf("    subclass   = %s\n", dp);
587 }
588 
589 static void
590 list_vpd(int fd, struct pci_conf *p)
591 {
592 	struct pci_list_vpd_io list;
593 	struct pci_vpd_element *vpd, *end;
594 
595 	list.plvi_sel = p->pc_sel;
596 	list.plvi_len = 0;
597 	list.plvi_data = NULL;
598 	if (ioctl(fd, PCIOCLISTVPD, &list) < 0 || list.plvi_len == 0)
599 		return;
600 
601 	list.plvi_data = malloc(list.plvi_len);
602 	if (ioctl(fd, PCIOCLISTVPD, &list) < 0) {
603 		free(list.plvi_data);
604 		return;
605 	}
606 
607 	vpd = list.plvi_data;
608 	end = (struct pci_vpd_element *)((char *)vpd + list.plvi_len);
609 	for (; vpd < end; vpd = PVE_NEXT(vpd)) {
610 		if (vpd->pve_flags == PVE_FLAG_IDENT) {
611 			printf("    VPD ident  = '%.*s'\n",
612 			    (int)vpd->pve_datalen, vpd->pve_data);
613 			continue;
614 		}
615 
616 		/* Ignore the checksum keyword. */
617 		if (!(vpd->pve_flags & PVE_FLAG_RW) &&
618 		    memcmp(vpd->pve_keyword, "RV", 2) == 0)
619 			continue;
620 
621 		/* Ignore remaining read-write space. */
622 		if (vpd->pve_flags & PVE_FLAG_RW &&
623 		    memcmp(vpd->pve_keyword, "RW", 2) == 0)
624 			continue;
625 
626 		/* Handle extended capability keyword. */
627 		if (!(vpd->pve_flags & PVE_FLAG_RW) &&
628 		    memcmp(vpd->pve_keyword, "CP", 2) == 0) {
629 			printf("    VPD ro CP  = ID %02x in map 0x%x[0x%x]\n",
630 			    (unsigned int)vpd->pve_data[0],
631 			    PCIR_BAR((unsigned int)vpd->pve_data[1]),
632 			    (unsigned int)vpd->pve_data[3] << 8 |
633 			    (unsigned int)vpd->pve_data[2]);
634 			continue;
635 		}
636 
637 		/* Remaining keywords should all have ASCII values. */
638 		printf("    VPD %s %c%c  = '%.*s'\n",
639 		    vpd->pve_flags & PVE_FLAG_RW ? "rw" : "ro",
640 		    vpd->pve_keyword[0], vpd->pve_keyword[1],
641 		    (int)vpd->pve_datalen, vpd->pve_data);
642 	}
643 	free(list.plvi_data);
644 }
645 
646 /*
647  * This is a direct cut-and-paste from the table in sys/dev/pci/pci.c.
648  */
649 static struct
650 {
651 	int	class;
652 	int	subclass;
653 	const char *desc;
654 } pci_nomatch_tab[] = {
655 	{PCIC_OLD,		-1,			"old"},
656 	{PCIC_OLD,		PCIS_OLD_NONVGA,	"non-VGA display device"},
657 	{PCIC_OLD,		PCIS_OLD_VGA,		"VGA-compatible display device"},
658 	{PCIC_STORAGE,		-1,			"mass storage"},
659 	{PCIC_STORAGE,		PCIS_STORAGE_SCSI,	"SCSI"},
660 	{PCIC_STORAGE,		PCIS_STORAGE_IDE,	"ATA"},
661 	{PCIC_STORAGE,		PCIS_STORAGE_FLOPPY,	"floppy disk"},
662 	{PCIC_STORAGE,		PCIS_STORAGE_IPI,	"IPI"},
663 	{PCIC_STORAGE,		PCIS_STORAGE_RAID,	"RAID"},
664 	{PCIC_STORAGE,		PCIS_STORAGE_ATA_ADMA,	"ATA (ADMA)"},
665 	{PCIC_STORAGE,		PCIS_STORAGE_SATA,	"SATA"},
666 	{PCIC_STORAGE,		PCIS_STORAGE_SAS,	"SAS"},
667 	{PCIC_STORAGE,		PCIS_STORAGE_NVM,	"NVM"},
668 	{PCIC_STORAGE,		PCIS_STORAGE_UFS,	"UFS"},
669 	{PCIC_NETWORK,		-1,			"network"},
670 	{PCIC_NETWORK,		PCIS_NETWORK_ETHERNET,	"ethernet"},
671 	{PCIC_NETWORK,		PCIS_NETWORK_TOKENRING,	"token ring"},
672 	{PCIC_NETWORK,		PCIS_NETWORK_FDDI,	"fddi"},
673 	{PCIC_NETWORK,		PCIS_NETWORK_ATM,	"ATM"},
674 	{PCIC_NETWORK,		PCIS_NETWORK_ISDN,	"ISDN"},
675 	{PCIC_NETWORK,		PCIS_NETWORK_WORLDFIP,	"WorldFip"},
676 	{PCIC_NETWORK,		PCIS_NETWORK_PICMG,	"PICMG"},
677 	{PCIC_NETWORK,		PCIS_NETWORK_INFINIBAND,	"InfiniBand"},
678 	{PCIC_NETWORK,		PCIS_NETWORK_HFC,	"host fabric"},
679 	{PCIC_DISPLAY,		-1,			"display"},
680 	{PCIC_DISPLAY,		PCIS_DISPLAY_VGA,	"VGA"},
681 	{PCIC_DISPLAY,		PCIS_DISPLAY_XGA,	"XGA"},
682 	{PCIC_DISPLAY,		PCIS_DISPLAY_3D,	"3D"},
683 	{PCIC_MULTIMEDIA,	-1,			"multimedia"},
684 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_VIDEO,	"video"},
685 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_AUDIO,	"audio"},
686 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_TELE,	"telephony"},
687 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_HDA,	"HDA"},
688 	{PCIC_MEMORY,		-1,			"memory"},
689 	{PCIC_MEMORY,		PCIS_MEMORY_RAM,	"RAM"},
690 	{PCIC_MEMORY,		PCIS_MEMORY_FLASH,	"flash"},
691 	{PCIC_BRIDGE,		-1,			"bridge"},
692 	{PCIC_BRIDGE,		PCIS_BRIDGE_HOST,	"HOST-PCI"},
693 	{PCIC_BRIDGE,		PCIS_BRIDGE_ISA,	"PCI-ISA"},
694 	{PCIC_BRIDGE,		PCIS_BRIDGE_EISA,	"PCI-EISA"},
695 	{PCIC_BRIDGE,		PCIS_BRIDGE_MCA,	"PCI-MCA"},
696 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI,	"PCI-PCI"},
697 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCMCIA,	"PCI-PCMCIA"},
698 	{PCIC_BRIDGE,		PCIS_BRIDGE_NUBUS,	"PCI-NuBus"},
699 	{PCIC_BRIDGE,		PCIS_BRIDGE_CARDBUS,	"PCI-CardBus"},
700 	{PCIC_BRIDGE,		PCIS_BRIDGE_RACEWAY,	"PCI-RACEway"},
701 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI_TRANSPARENT,
702 	    "Semi-transparent PCI-to-PCI"},
703 	{PCIC_BRIDGE,		PCIS_BRIDGE_INFINIBAND,	"InfiniBand-PCI"},
704 	{PCIC_BRIDGE,		PCIS_BRIDGE_AS_PCI,
705 	    "AdvancedSwitching-PCI"},
706 	{PCIC_SIMPLECOMM,	-1,			"simple comms"},
707 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_UART,	"UART"},	/* could detect 16550 */
708 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_PAR,	"parallel port"},
709 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MULSER,	"multiport serial"},
710 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MODEM,	"generic modem"},
711 	{PCIC_BASEPERIPH,	-1,			"base peripheral"},
712 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PIC,	"interrupt controller"},
713 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_DMA,	"DMA controller"},
714 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_TIMER,	"timer"},
715 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RTC,	"realtime clock"},
716 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PCIHOT,	"PCI hot-plug controller"},
717 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_SDHC,	"SD host controller"},
718 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_IOMMU,	"IOMMU"},
719 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RCEC,
720 	    "Root Complex Event Collector"},
721 	{PCIC_INPUTDEV,		-1,			"input device"},
722 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_KEYBOARD,	"keyboard"},
723 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_DIGITIZER,"digitizer"},
724 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_MOUSE,	"mouse"},
725 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_SCANNER,	"scanner"},
726 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_GAMEPORT,	"gameport"},
727 	{PCIC_DOCKING,		-1,			"docking station"},
728 	{PCIC_PROCESSOR,	-1,			"processor"},
729 	{PCIC_SERIALBUS,	-1,			"serial bus"},
730 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FW,	"FireWire"},
731 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_ACCESS,	"AccessBus"},
732 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SSA,	"SSA"},
733 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_USB,	"USB"},
734 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FC,	"Fibre Channel"},
735 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SMBUS,	"SMBus"},
736 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_INFINIBAND,	"InfiniBand"},
737 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_IPMI,	"IPMI"},
738 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SERCOS,	"SERCOS"},
739 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_CANBUS,	"CANbus"},
740 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_MIPI_I3C,	"MIPI I3C"},
741 	{PCIC_WIRELESS,		-1,			"wireless controller"},
742 	{PCIC_WIRELESS,		PCIS_WIRELESS_IRDA,	"iRDA"},
743 	{PCIC_WIRELESS,		PCIS_WIRELESS_IR,	"IR"},
744 	{PCIC_WIRELESS,		PCIS_WIRELESS_RF,	"RF"},
745 	{PCIC_WIRELESS,		PCIS_WIRELESS_BLUETOOTH,	"bluetooth"},
746 	{PCIC_WIRELESS,		PCIS_WIRELESS_BROADBAND,	"broadband"},
747 	{PCIC_WIRELESS,		PCIS_WIRELESS_80211A,	"ethernet 802.11a"},
748 	{PCIC_WIRELESS,		PCIS_WIRELESS_80211B,	"ethernet 802.11b"},
749 	{PCIC_WIRELESS,		PCIS_WIRELESS_CELL,
750 	    "cellular controller/modem"},
751 	{PCIC_WIRELESS,		PCIS_WIRELESS_CELL_E,
752 	    "cellular controller/modem plus ethernet"},
753 	{PCIC_INTELLIIO,	-1,			"intelligent I/O controller"},
754 	{PCIC_INTELLIIO,	PCIS_INTELLIIO_I2O,	"I2O"},
755 	{PCIC_SATCOM,		-1,			"satellite communication"},
756 	{PCIC_SATCOM,		PCIS_SATCOM_TV,		"sat TV"},
757 	{PCIC_SATCOM,		PCIS_SATCOM_AUDIO,	"sat audio"},
758 	{PCIC_SATCOM,		PCIS_SATCOM_VOICE,	"sat voice"},
759 	{PCIC_SATCOM,		PCIS_SATCOM_DATA,	"sat data"},
760 	{PCIC_CRYPTO,		-1,			"encrypt/decrypt"},
761 	{PCIC_CRYPTO,		PCIS_CRYPTO_NETCOMP,	"network/computer crypto"},
762 	{PCIC_CRYPTO,		PCIS_CRYPTO_ENTERTAIN,	"entertainment crypto"},
763 	{PCIC_DASP,		-1,			"dasp"},
764 	{PCIC_DASP,		PCIS_DASP_DPIO,		"DPIO module"},
765 	{PCIC_DASP,		PCIS_DASP_PERFCNTRS,	"performance counters"},
766 	{PCIC_DASP,		PCIS_DASP_COMM_SYNC,	"communication synchronizer"},
767 	{PCIC_DASP,		PCIS_DASP_MGMT_CARD,	"signal processing management"},
768 	{PCIC_ACCEL,		-1,			"processing accelerators"},
769 	{PCIC_ACCEL,		PCIS_ACCEL_PROCESSING,	"processing accelerators"},
770 	{PCIC_INSTRUMENT,	-1,			"non-essential instrumentation"},
771 	{0, 0,		NULL}
772 };
773 
774 static const char *
775 guess_class(struct pci_conf *p)
776 {
777 	int	i;
778 
779 	for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
780 		if (pci_nomatch_tab[i].class == p->pc_class)
781 			return(pci_nomatch_tab[i].desc);
782 	}
783 	return(NULL);
784 }
785 
786 static const char *
787 guess_subclass(struct pci_conf *p)
788 {
789 	int	i;
790 
791 	for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
792 		if ((pci_nomatch_tab[i].class == p->pc_class) &&
793 		    (pci_nomatch_tab[i].subclass == p->pc_subclass))
794 			return(pci_nomatch_tab[i].desc);
795 	}
796 	return(NULL);
797 }
798 
799 static int
800 load_vendors(void)
801 {
802 	const char *dbf;
803 	FILE *db;
804 	struct pci_vendor_info *cv;
805 	struct pci_device_info *cd;
806 	char buf[1024], str[1024];
807 	char *ch;
808 	int id, error;
809 
810 	/*
811 	 * Locate the database and initialise.
812 	 */
813 	TAILQ_INIT(&pci_vendors);
814 	if ((dbf = getenv("PCICONF_VENDOR_DATABASE")) == NULL)
815 		dbf = _PATH_LPCIVDB;
816 	if ((db = fopen(dbf, "r")) == NULL) {
817 		dbf = _PATH_PCIVDB;
818 		if ((db = fopen(dbf, "r")) == NULL)
819 			return(1);
820 	}
821 	cv = NULL;
822 	cd = NULL;
823 	error = 0;
824 
825 	/*
826 	 * Scan input lines from the database
827 	 */
828 	for (;;) {
829 		if (fgets(buf, sizeof(buf), db) == NULL)
830 			break;
831 
832 		if ((ch = strchr(buf, '#')) != NULL)
833 			*ch = '\0';
834 		ch = strchr(buf, '\0') - 1;
835 		while (ch > buf && isspace(*ch))
836 			*ch-- = '\0';
837 		if (ch <= buf)
838 			continue;
839 
840 		/* Can't handle subvendor / subdevice entries yet */
841 		if (buf[0] == '\t' && buf[1] == '\t')
842 			continue;
843 
844 		/* Check for vendor entry */
845 		if (buf[0] != '\t' && sscanf(buf, "%04x %[^\n]", &id, str) == 2) {
846 			if ((id == 0) || (strlen(str) < 1))
847 				continue;
848 			if ((cv = malloc(sizeof(struct pci_vendor_info))) == NULL) {
849 				warn("allocating vendor entry");
850 				error = 1;
851 				break;
852 			}
853 			if ((cv->desc = strdup(str)) == NULL) {
854 				free(cv);
855 				warn("allocating vendor description");
856 				error = 1;
857 				break;
858 			}
859 			cv->id = id;
860 			TAILQ_INIT(&cv->devs);
861 			TAILQ_INSERT_TAIL(&pci_vendors, cv, link);
862 			continue;
863 		}
864 
865 		/* Check for device entry */
866 		if (buf[0] == '\t' && sscanf(buf + 1, "%04x %[^\n]", &id, str) == 2) {
867 			if ((id == 0) || (strlen(str) < 1))
868 				continue;
869 			if (cv == NULL) {
870 				warnx("device entry with no vendor!");
871 				continue;
872 			}
873 			if ((cd = malloc(sizeof(struct pci_device_info))) == NULL) {
874 				warn("allocating device entry");
875 				error = 1;
876 				break;
877 			}
878 			if ((cd->desc = strdup(str)) == NULL) {
879 				free(cd);
880 				warn("allocating device description");
881 				error = 1;
882 				break;
883 			}
884 			cd->id = id;
885 			TAILQ_INSERT_TAIL(&cv->devs, cd, link);
886 			continue;
887 		}
888 
889 		/* It's a comment or junk, ignore it */
890 	}
891 	if (ferror(db))
892 		error = 1;
893 	fclose(db);
894 
895 	return(error);
896 }
897 
898 uint32_t
899 read_config(int fd, struct pcisel *sel, long reg, int width)
900 {
901 	struct pci_io pi;
902 
903 	pi.pi_sel = *sel;
904 	pi.pi_reg = reg;
905 	pi.pi_width = width;
906 
907 	if (ioctl(fd, PCIOCREAD, &pi) < 0)
908 		err(1, "ioctl(PCIOCREAD)");
909 
910 	return (pi.pi_data);
911 }
912 
913 static struct pcisel
914 getdevice(const char *name)
915 {
916 	struct pci_conf_io pc;
917 	struct pci_conf conf[1];
918 	struct pci_match_conf patterns[1];
919 	char *cp;
920 	int fd;
921 
922 	fd = open(_PATH_DEVPCI, O_RDONLY, 0);
923 	if (fd < 0)
924 		err(1, "%s", _PATH_DEVPCI);
925 
926 	bzero(&pc, sizeof(struct pci_conf_io));
927 	pc.match_buf_len = sizeof(conf);
928 	pc.matches = conf;
929 
930 	bzero(&patterns, sizeof(patterns));
931 
932 	/*
933 	 * The pattern structure requires the unit to be split out from
934 	 * the driver name.  Walk backwards from the end of the name to
935 	 * find the start of the unit.
936 	 */
937 	if (name[0] == '\0')
938 		errx(1, "Empty device name");
939 	cp = strchr(name, '\0');
940 	assert(cp != NULL && cp != name);
941 	cp--;
942 	while (cp != name && isdigit(cp[-1]))
943 		cp--;
944 	if (cp == name || !isdigit(*cp))
945 		errx(1, "Invalid device name");
946 	if ((size_t)(cp - name) + 1 > sizeof(patterns[0].pd_name))
947 		errx(1, "Device name is too long");
948 	memcpy(patterns[0].pd_name, name, cp - name);
949 	patterns[0].pd_unit = strtol(cp, &cp, 10);
950 	if (*cp != '\0')
951 		errx(1, "Invalid device name");
952 	patterns[0].flags = PCI_GETCONF_MATCH_NAME | PCI_GETCONF_MATCH_UNIT;
953 	pc.num_patterns = 1;
954 	pc.pat_buf_len = sizeof(patterns);
955 	pc.patterns = patterns;
956 
957 	if (ioctl(fd, PCIOCGETCONF, &pc) == -1)
958 		err(1, "ioctl(PCIOCGETCONF)");
959 	if (pc.status != PCI_GETCONF_LAST_DEVICE &&
960 	    pc.status != PCI_GETCONF_MORE_DEVS)
961 		errx(1, "error returned from PCIOCGETCONF ioctl");
962 	close(fd);
963 	if (pc.num_matches == 0)
964 		errx(1, "Device not found");
965 	return (conf[0].pc_sel);
966 }
967 
968 static struct pcisel
969 parsesel(const char *str)
970 {
971 	const char *ep;
972 	char *eppos;
973 	struct pcisel sel;
974 	unsigned long selarr[4];
975 	int i;
976 
977 	ep = strchr(str, '@');
978 	if (ep != NULL)
979 		ep++;
980 	else
981 		ep = str;
982 
983 	if (strncmp(ep, "pci", 3) == 0) {
984 		ep += 3;
985 		i = 0;
986 		while (isdigit(*ep) && i < 4) {
987 			selarr[i++] = strtoul(ep, &eppos, 10);
988 			ep = eppos;
989 			if (*ep == ':')
990 				ep++;
991 		}
992 		if (i > 0 && *ep == '\0') {
993 			sel.pc_func = (i > 2) ? selarr[--i] : 0;
994 			sel.pc_dev = (i > 0) ? selarr[--i] : 0;
995 			sel.pc_bus = (i > 0) ? selarr[--i] : 0;
996 			sel.pc_domain = (i > 0) ? selarr[--i] : 0;
997 			return (sel);
998 		}
999 	}
1000 	errx(1, "cannot parse selector %s", str);
1001 }
1002 
1003 static struct pcisel
1004 getsel(const char *str)
1005 {
1006 
1007 	/*
1008 	 * No device names contain colons and selectors always contain
1009 	 * at least one colon.
1010 	 */
1011 	if (strchr(str, ':') == NULL)
1012 		return (getdevice(str));
1013 	else
1014 		return (parsesel(str));
1015 }
1016 
1017 static void
1018 readone(int fd, struct pcisel *sel, long reg, int width)
1019 {
1020 
1021 	printf("%0*x", width*2, read_config(fd, sel, reg, width));
1022 }
1023 
1024 static void
1025 readit(const char *name, const char *reg, int width)
1026 {
1027 	long rstart;
1028 	long rend;
1029 	long r;
1030 	char *end;
1031 	int i;
1032 	int fd;
1033 	struct pcisel sel;
1034 
1035 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
1036 	if (fd < 0)
1037 		err(1, "%s", _PATH_DEVPCI);
1038 
1039 	rend = rstart = strtol(reg, &end, 0);
1040 	if (end && *end == ':') {
1041 		end++;
1042 		rend = strtol(end, (char **) 0, 0);
1043 	}
1044 	sel = getsel(name);
1045 	for (i = 1, r = rstart; r <= rend; i++, r += width) {
1046 		readone(fd, &sel, r, width);
1047 		if (i && !(i % 8))
1048 			putchar(' ');
1049 		putchar(i % (16/width) ? ' ' : '\n');
1050 	}
1051 	if (i % (16/width) != 1)
1052 		putchar('\n');
1053 	close(fd);
1054 }
1055 
1056 static void
1057 writeit(const char *name, const char *reg, const char *data, int width)
1058 {
1059 	int fd;
1060 	struct pci_io pi;
1061 
1062 	pi.pi_sel = getsel(name);
1063 	pi.pi_reg = strtoul(reg, (char **)0, 0); /* XXX error check */
1064 	pi.pi_width = width;
1065 	pi.pi_data = strtoul(data, (char **)0, 0); /* XXX error check */
1066 
1067 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
1068 	if (fd < 0)
1069 		err(1, "%s", _PATH_DEVPCI);
1070 
1071 	if (ioctl(fd, PCIOCWRITE, &pi) < 0)
1072 		err(1, "ioctl(PCIOCWRITE)");
1073 	close(fd);
1074 }
1075 
1076 static void
1077 chkattached(const char *name)
1078 {
1079 	int fd;
1080 	struct pci_io pi;
1081 
1082 	pi.pi_sel = getsel(name);
1083 
1084 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
1085 	if (fd < 0)
1086 		err(1, "%s", _PATH_DEVPCI);
1087 
1088 	if (ioctl(fd, PCIOCATTACHED, &pi) < 0)
1089 		err(1, "ioctl(PCIOCATTACHED)");
1090 
1091 	exitstatus = pi.pi_data ? 0 : 2; /* exit(2), if NOT attached */
1092 	printf("%s: %s%s\n", name, pi.pi_data == 0 ? "not " : "", "attached");
1093 	close(fd);
1094 }
1095 
1096 static void
1097 dump_bar(const char *name, const char *reg, const char *bar_start,
1098     const char *bar_count, int width, int verbose)
1099 {
1100 	struct pci_bar_mmap pbm;
1101 	uint32_t *dd;
1102 	uint16_t *dh;
1103 	uint8_t *db;
1104 	uint64_t *dx, a, start, count;
1105 	char *el;
1106 	size_t res;
1107 	int fd;
1108 
1109 	start = 0;
1110 	if (bar_start != NULL) {
1111 		start = strtoul(bar_start, &el, 0);
1112 		if (*el != '\0')
1113 			errx(1, "Invalid bar start specification %s",
1114 			    bar_start);
1115 	}
1116 	count = 0;
1117 	if (bar_count != NULL) {
1118 		count = strtoul(bar_count, &el, 0);
1119 		if (*el != '\0')
1120 			errx(1, "Invalid count specification %s",
1121 			    bar_count);
1122 	}
1123 
1124 	pbm.pbm_sel = getsel(name);
1125 	pbm.pbm_reg = strtoul(reg, &el, 0);
1126 	if (*reg == '\0' || *el != '\0')
1127 		errx(1, "Invalid bar specification %s", reg);
1128 	pbm.pbm_flags = 0;
1129 	pbm.pbm_memattr = VM_MEMATTR_DEVICE;
1130 
1131 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
1132 	if (fd < 0)
1133 		err(1, "%s", _PATH_DEVPCI);
1134 
1135 	if (ioctl(fd, PCIOCBARMMAP, &pbm) < 0)
1136 		err(1, "ioctl(PCIOCBARMMAP)");
1137 
1138 	if (count == 0)
1139 		count = pbm.pbm_bar_length / width;
1140 	if (start + count < start || (start + count) * width < (uint64_t)width)
1141 		errx(1, "(start + count) x width overflow");
1142 	if ((start + count) * width > pbm.pbm_bar_length) {
1143 		if (start * width > pbm.pbm_bar_length)
1144 			count = 0;
1145 		else
1146 			count = (pbm.pbm_bar_length - start * width) / width;
1147 	}
1148 	if (verbose) {
1149 		fprintf(stderr,
1150 		    "Dumping pci%d:%d:%d:%d BAR %x mapped base %p "
1151 		    "off %#x length %#jx from %#jx count %#jx in %d-bytes\n",
1152 		    pbm.pbm_sel.pc_domain, pbm.pbm_sel.pc_bus,
1153 		    pbm.pbm_sel.pc_dev, pbm.pbm_sel.pc_func,
1154 		    pbm.pbm_reg, pbm.pbm_map_base, pbm.pbm_bar_off,
1155 		    pbm.pbm_bar_length, start, count, width);
1156 	}
1157 	switch (width) {
1158 	case 1:
1159 		db = (uint8_t *)(uintptr_t)((uintptr_t)pbm.pbm_map_base +
1160 		    pbm.pbm_bar_off + start * width);
1161 		for (a = 0; a < count; a += width, db++) {
1162 			res = fwrite(db, width, 1, stdout);
1163 			if (res != 1) {
1164 				errx(1, "error writing to stdout");
1165 				break;
1166 			}
1167 		}
1168 		break;
1169 	case 2:
1170 		dh = (uint16_t *)(uintptr_t)((uintptr_t)pbm.pbm_map_base +
1171 		    pbm.pbm_bar_off + start * width);
1172 		for (a = 0; a < count; a += width, dh++) {
1173 			res = fwrite(dh, width, 1, stdout);
1174 			if (res != 1) {
1175 				errx(1, "error writing to stdout");
1176 				break;
1177 			}
1178 		}
1179 		break;
1180 	case 4:
1181 		dd = (uint32_t *)(uintptr_t)((uintptr_t)pbm.pbm_map_base +
1182 		    pbm.pbm_bar_off + start * width);
1183 		for (a = 0; a < count; a += width, dd++) {
1184 			res = fwrite(dd, width, 1, stdout);
1185 			if (res != 1) {
1186 				errx(1, "error writing to stdout");
1187 				break;
1188 			}
1189 		}
1190 		break;
1191 	case 8:
1192 		dx = (uint64_t *)(uintptr_t)((uintptr_t)pbm.pbm_map_base +
1193 		    pbm.pbm_bar_off + start * width);
1194 		for (a = 0; a < count; a += width, dx++) {
1195 			res = fwrite(dx, width, 1, stdout);
1196 			if (res != 1) {
1197 				errx(1, "error writing to stdout");
1198 				break;
1199 			}
1200 		}
1201 		break;
1202 	default:
1203 		errx(1, "invalid access width");
1204 	}
1205 
1206 	munmap((void *)pbm.pbm_map_base, pbm.pbm_map_length);
1207 	close(fd);
1208 }
1209