xref: /freebsd/usr.sbin/pciconf/pciconf.c (revision e63fbcc69402d4a1e8681a95710f0ec01a6837b4)
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 #include <sys/types.h>
31 #include <sys/fcntl.h>
32 #include <sys/mman.h>
33 #include <sys/pciio.h>
34 #include <sys/queue.h>
35 
36 #include <vm/vm.h>
37 
38 #include <dev/pci/pcireg.h>
39 
40 #include <assert.h>
41 #include <bitstring.h>
42 #include <ctype.h>
43 #include <err.h>
44 #include <inttypes.h>
45 #include <stdbool.h>
46 #include <stdlib.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #include "pathnames.h"
52 #include "pciconf.h"
53 
54 struct pci_device_info
55 {
56     TAILQ_ENTRY(pci_device_info)	link;
57     int					id;
58     char				*desc;
59 };
60 
61 struct pci_vendor_info
62 {
63     TAILQ_ENTRY(pci_vendor_info)	link;
64     TAILQ_HEAD(,pci_device_info)	devs;
65     int					id;
66     char				*desc;
67 };
68 
69 
70 struct pci_tree_entry {
71 	TAILQ_ENTRY(pci_tree_entry)	link;
72 	TAILQ_HEAD(pci_tree_list, pci_tree_entry) children;
73 	struct pci_conf			*p;
74 };
75 
76 static TAILQ_HEAD(,pci_vendor_info)	pci_vendors;
77 
78 static struct pcisel getsel(const char *str);
79 static void list_bridge(int fd, struct pci_conf *p);
80 static void list_bars(int fd, struct pci_conf *p);
81 static void list_devs(const char *name, int verbose, int bars, int bridge,
82     int caps, int errors, int vpd, int compact);
83 static void show_tree(int verbose);
84 static void list_verbose(struct pci_conf *p);
85 static void list_vpd(int fd, struct pci_conf *p);
86 static const char *guess_class(struct pci_conf *p);
87 static const char *guess_subclass(struct pci_conf *p);
88 static int load_vendors(void);
89 static void readit(const char *, const char *, int);
90 static void writeit(const char *, const char *, const char *, int);
91 static void chkattached(const char *);
92 static void dump_bar(const char *name, const char *reg, const char *bar_start,
93     const char *bar_count, int width, int verbose);
94 static void read_bar(const char *name, const char *bar, const char *start_end,
95     int width);
96 static void write_bar(const char *name, const char *bar, const char *offset_str,
97     const char *value_str, int width);
98 
99 static int exitstatus = 0;
100 
101 static void
usage(void)102 usage(void)
103 {
104 
105 	fprintf(stderr, "%s",
106 		"usage: pciconf -l [-BbcevV] [device]\n"
107 		"       pciconf -t [-v]\n"
108 		"       pciconf -a device\n"
109 		"       pciconf -r [-b | -h] device addr[:addr2]\n"
110 		"       pciconf -w [-b | -h] device addr value\n"
111 		"       pciconf -D [-b | -h | -x] device bar [start [count]]\n"
112 		"       pciconf -R [-b | -h | -x] device bar start[:end]\n"
113 		"       pciconf -W [-b | -h | -x] device bar offset value"
114 		"\n");
115 	exit(1);
116 }
117 
118 int
main(int argc,char ** argv)119 main(int argc, char **argv)
120 {
121 	int c, width;
122 	enum { NONE, LIST, TREE, READ, WRITE, ATTACHED, DUMPBAR, READBAR,
123 	    WRITEBAR } mode;
124 	int compact, bars, bridge, caps, errors, verbose, vpd;
125 
126 	mode = NONE;
127 	compact = bars = bridge = caps = errors = verbose = vpd = 0;
128 	width = 4;
129 
130 	while ((c = getopt(argc, argv, "aBbcDehlRrtWwVvx")) != -1) {
131 		switch(c) {
132 		case 'a':
133 			mode = ATTACHED;
134 			break;
135 
136 		case 'B':
137 			bridge = 1;
138 			break;
139 
140 		case 'b':
141 			bars = 1;
142 			width = 1;
143 			break;
144 
145 		case 'c':
146 			caps++;
147 			break;
148 
149 		case 'D':
150 			mode = DUMPBAR;
151 			break;
152 
153 		case 'e':
154 			errors = 1;
155 			break;
156 
157 		case 'h':
158 			width = 2;
159 			break;
160 
161 		case 'l':
162 			if (mode == LIST)
163 				compact = 1;
164 			mode = LIST;
165 			break;
166 
167 		case 'R':
168 			mode = READBAR;
169 			break;
170 
171 		case 'r':
172 			mode = READ;
173 			break;
174 
175 		case 't':
176 			mode = TREE;
177 			break;
178 
179 		case 'W':
180 			mode = WRITEBAR;
181 			break;
182 
183 		case 'w':
184 			mode = WRITE;
185 			break;
186 
187 		case 'v':
188 			verbose = 1;
189 			break;
190 
191 		case 'V':
192 			vpd = 1;
193 			break;
194 
195 		case 'x':
196 			width = 8;
197 			break;
198 
199 		default:
200 			usage();
201 		}
202 	}
203 
204 	switch (mode) {
205 	case LIST:
206 		if (optind >= argc + 1)
207 			usage();
208 		list_devs(optind + 1 == argc ? argv[optind] : NULL, verbose,
209 		    bars, bridge, caps, errors, vpd, compact);
210 		break;
211 	case TREE:
212 		if (optind != argc)
213 			usage();
214 		show_tree(verbose);
215 		break;
216 	case ATTACHED:
217 		if (optind + 1 != argc)
218 			usage();
219 		chkattached(argv[optind]);
220 		break;
221 	case READ:
222 		if (optind + 2 != argc || width == 8)
223 			usage();
224 		readit(argv[optind], argv[optind + 1], width);
225 		break;
226 	case WRITE:
227 		if (optind + 3 != argc || width == 8)
228 			usage();
229 		writeit(argv[optind], argv[optind + 1], argv[optind + 2],
230 		    width);
231 		break;
232 	case DUMPBAR:
233 		if (optind + 2 > argc || optind + 4 < argc)
234 			usage();
235 		dump_bar(argv[optind], argv[optind + 1],
236 		    optind + 2 < argc ? argv[optind + 2] : NULL,
237 		    optind + 3 < argc ? argv[optind + 3] : NULL,
238 		    width, verbose);
239 		break;
240 	case READBAR:
241 		if (optind + 3 != argc)
242 			usage();
243 		read_bar(argv[optind], argv[optind + 1], argv[optind + 2],
244 		    width);
245 		break;
246 	case WRITEBAR:
247 		if (optind + 4 != argc)
248 			usage();
249 		write_bar(argv[optind], argv[optind + 1], argv[optind + 2],
250 		    argv[optind + 3], width);
251 		break;
252 	default:
253 		usage();
254 	}
255 
256 	return (exitstatus);
257 }
258 
259 static bool
fetch_devs(int fd,const char * name,struct pci_conf ** confp,size_t * countp)260 fetch_devs(int fd, const char *name, struct pci_conf **confp, size_t *countp)
261 {
262 	struct pci_conf_io pc;
263 	struct pci_conf conf[255], *p;
264 	struct pci_match_conf patterns[1];
265 	size_t count;
266 
267 	bzero(&pc, sizeof(struct pci_conf_io));
268 	pc.match_buf_len = sizeof(conf);
269 	pc.matches = conf;
270 	if (name != NULL) {
271 		bzero(&patterns, sizeof(patterns));
272 		patterns[0].pc_sel = getsel(name);
273 		patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN |
274 		    PCI_GETCONF_MATCH_BUS | PCI_GETCONF_MATCH_DEV |
275 		    PCI_GETCONF_MATCH_FUNC;
276 		pc.num_patterns = 1;
277 		pc.pat_buf_len = sizeof(patterns);
278 		pc.patterns = patterns;
279 	}
280 
281 	p = NULL;
282 	count = 0;
283 	do {
284 		if (ioctl(fd, PCIOCGETCONF, &pc) == -1)
285 			err(1, "ioctl(PCIOCGETCONF)");
286 
287 		if (pc.status == PCI_GETCONF_LIST_CHANGED) {
288 			free(p);
289 			p = NULL;
290 			count = 0;
291 			pc.offset = 0;
292 			continue;
293 		}
294 
295 		if (pc.status == PCI_GETCONF_ERROR) {
296 			warnx("error returned from PCIOCGETCONF ioctl");
297 			return (false);
298 		}
299 
300 		p = reallocf(p, (count + pc.num_matches) * sizeof(*p));
301 		if (p == NULL) {
302 			warnx("failed to allocate buffer for PCIOCGETCONF results");
303 			return (false);
304 		}
305 
306 		memcpy(p + count, conf, pc.num_matches * sizeof(*p));
307 		count += pc.num_matches;
308 	} while (pc.status == PCI_GETCONF_MORE_DEVS);
309 
310 	*confp = p;
311 	*countp = count;
312 	return (true);
313 }
314 
315 static void
list_devs(const char * name,int verbose,int bars,int bridge,int caps,int errors,int vpd,int compact)316 list_devs(const char *name, int verbose, int bars, int bridge, int caps,
317     int errors, int vpd, int compact)
318 {
319 	int fd;
320 	struct pci_conf *conf, *p;
321 	size_t count;
322 	int none_count = 0;
323 
324 	if (verbose)
325 		load_vendors();
326 
327 	fd = open(_PATH_DEVPCI, (bridge || caps || errors) ? O_RDWR : O_RDONLY,
328 	    0);
329 	if (fd < 0)
330 		err(1, "%s", _PATH_DEVPCI);
331 
332 	if (!fetch_devs(fd, name, &conf, &count)) {
333 		exitstatus = 1;
334 		close(fd);
335 		return;
336 	}
337 
338 	if (compact)
339 		printf("drv\tselector\tclass    rev  hdr  "
340 		    "vendor device subven subdev\n");
341 	for (p = conf; p < conf + count; p++) {
342 		if (compact)
343 			printf("%s%d@pci%d:%d:%d:%d:"
344 			    "\t%06x   %02x   %02x   "
345 			    "%04x   %04x   %04x   %04x\n",
346 			    *p->pd_name ? p->pd_name : "none",
347 			    *p->pd_name ? (int)p->pd_unit :
348 			    none_count++, p->pc_sel.pc_domain,
349 			    p->pc_sel.pc_bus, p->pc_sel.pc_dev,
350 			    p->pc_sel.pc_func, (p->pc_class << 16) |
351 			    (p->pc_subclass << 8) | p->pc_progif,
352 			    p->pc_revid, p->pc_hdr,
353 			    p->pc_vendor, p->pc_device,
354 			    p->pc_subvendor, p->pc_subdevice);
355 		else
356 			printf("%s%d@pci%d:%d:%d:%d:"
357 			    "\tclass=0x%06x rev=0x%02x hdr=0x%02x "
358 			    "vendor=0x%04x device=0x%04x "
359 			    "subvendor=0x%04x subdevice=0x%04x\n",
360 			    *p->pd_name ? p->pd_name : "none",
361 			    *p->pd_name ? (int)p->pd_unit :
362 			    none_count++, p->pc_sel.pc_domain,
363 			    p->pc_sel.pc_bus, p->pc_sel.pc_dev,
364 			    p->pc_sel.pc_func, (p->pc_class << 16) |
365 			    (p->pc_subclass << 8) | p->pc_progif,
366 			    p->pc_revid, p->pc_hdr,
367 			    p->pc_vendor, p->pc_device,
368 			    p->pc_subvendor, p->pc_subdevice);
369 		if (verbose)
370 			list_verbose(p);
371 		if (bars)
372 			list_bars(fd, p);
373 		if (bridge)
374 			list_bridge(fd, p);
375 		if (caps)
376 			list_caps(fd, p, caps);
377 		if (errors)
378 			list_errors(fd, p);
379 		if (vpd)
380 			list_vpd(fd, p);
381 	}
382 
383 	free(conf);
384 	close(fd);
385 }
386 
387 static int
pci_conf_compar(const void * lhs,const void * rhs)388 pci_conf_compar(const void *lhs, const void *rhs)
389 {
390 	const struct pci_conf *l, *r;
391 
392 	l = lhs;
393 	r = rhs;
394 	if (l->pc_sel.pc_domain != r->pc_sel.pc_domain)
395 		return (l->pc_sel.pc_domain - r->pc_sel.pc_domain);
396 	if (l->pc_sel.pc_bus != r->pc_sel.pc_bus)
397 		return (l->pc_sel.pc_bus - r->pc_sel.pc_bus);
398 	if (l->pc_sel.pc_dev != r->pc_sel.pc_dev)
399 		return (l->pc_sel.pc_dev - r->pc_sel.pc_dev);
400 	return (l->pc_sel.pc_func - r->pc_sel.pc_func);
401 }
402 
403 static void
tree_add_device(struct pci_tree_list * head,struct pci_conf * p,struct pci_conf * conf,size_t count,bitstr_t * added)404 tree_add_device(struct pci_tree_list *head, struct pci_conf *p,
405     struct pci_conf *conf, size_t count, bitstr_t *added)
406 {
407 	struct pci_tree_entry *e;
408 	struct pci_conf *child;
409 	size_t i;
410 
411 	e = malloc(sizeof(*e));
412 	TAILQ_INIT(&e->children);
413 	e->p = p;
414 	TAILQ_INSERT_TAIL(head, e, link);
415 
416 	switch (p->pc_hdr) {
417 	case PCIM_HDRTYPE_BRIDGE:
418 	case PCIM_HDRTYPE_CARDBUS:
419 		break;
420 	default:
421 		return;
422 	}
423 	if (p->pc_secbus == 0)
424 		return;
425 
426 	assert(p->pc_subbus >= p->pc_secbus);
427 	for (i = 0; i < count; i++) {
428 		child = conf + i;
429 		if (child->pc_sel.pc_domain < p->pc_sel.pc_domain)
430 			continue;
431 		if (child->pc_sel.pc_domain > p->pc_sel.pc_domain)
432 			break;
433 		if (child->pc_sel.pc_bus < p->pc_secbus)
434 			continue;
435 		if (child->pc_sel.pc_bus > p->pc_subbus)
436 			break;
437 
438 		if (child->pc_sel.pc_bus == p->pc_secbus) {
439 			assert(bit_test(added, i) == 0);
440 			bit_set(added, i);
441 			tree_add_device(&e->children, conf + i, conf, count,
442 			    added);
443 			continue;
444 		}
445 
446 		if (bit_test(added, i) == 0) {
447 			/*
448 			 * This really shouldn't happen, but if for
449 			 * some reason a child bridge doesn't claim
450 			 * this device, display it now rather than
451 			 * later.
452 			 */
453 			bit_set(added, i);
454 			tree_add_device(&e->children, conf + i, conf, count,
455 			    added);
456 			continue;
457 		}
458 	}
459 }
460 
461 static bool
build_tree(struct pci_tree_list * head,struct pci_conf * conf,size_t count)462 build_tree(struct pci_tree_list *head, struct pci_conf *conf, size_t count)
463 {
464 	bitstr_t *added;
465 	size_t i;
466 
467 	TAILQ_INIT(head);
468 
469 	/*
470 	 * Allocate a bitstring to track which devices have already
471 	 * been added to the tree.
472 	 */
473 	added = bit_alloc(count);
474 	if (added == NULL)
475 		return (false);
476 
477 	for (i = 0; i < count; i++) {
478 		if (bit_test(added, i))
479 			continue;
480 
481 		bit_set(added, i);
482 		tree_add_device(head, conf + i, conf, count, added);
483 	}
484 
485 	free(added);
486 	return (true);
487 }
488 
489 static void
free_tree(struct pci_tree_list * head)490 free_tree(struct pci_tree_list *head)
491 {
492 	struct pci_tree_entry *e, *n;
493 
494 	TAILQ_FOREACH_SAFE(e, head, link, n) {
495 		free_tree(&e->children);
496 		TAILQ_REMOVE(head, e, link);
497 		free(e);
498 	}
499 }
500 
501 static void
print_tree_entry(struct pci_tree_entry * e,const char * indent,bool last,int verbose)502 print_tree_entry(struct pci_tree_entry *e, const char *indent, bool last,
503     int verbose)
504 {
505 	struct pci_vendor_info *vi;
506 	struct pci_device_info *di;
507 	struct pci_tree_entry *child;
508 	struct pci_conf *p = e->p;
509 	char *indent_buf;
510 
511 	printf("%s%c--- ", indent, last ? '`' : '|');
512 	if (p->pd_name[0] != '\0')
513 		printf("%s%lu", p->pd_name, p->pd_unit);
514 	else
515 		printf("pci%d:%d:%d:%d", p->pc_sel.pc_domain, p->pc_sel.pc_bus,
516 		    p->pc_sel.pc_dev, p->pc_sel.pc_func);
517 
518 	if (verbose) {
519 		di = NULL;
520 		TAILQ_FOREACH(vi, &pci_vendors, link) {
521 			if (vi->id == p->pc_vendor) {
522 				printf(" %s", vi->desc);
523 				TAILQ_FOREACH(di, &vi->devs, link) {
524 					if (di->id == p->pc_device) {
525 						printf(" %s", di->desc);
526 						break;
527 					}
528 				}
529 				break;
530 			}
531 		}
532 		if (vi == NULL)
533 			printf(" vendor=0x%04x device=0x%04x", p->pc_vendor,
534 			    p->pc_device);
535 		else if (di == NULL)
536 			printf(" device=0x%04x", p->pc_device);
537 	}
538 	printf("\n");
539 
540 	if (TAILQ_EMPTY(&e->children))
541 		return;
542 
543 	asprintf(&indent_buf, "%s%c  ", indent, last ? ' ' : '|');
544 	TAILQ_FOREACH(child, &e->children, link) {
545 		print_tree_entry(child, indent_buf, TAILQ_NEXT(child, link) ==
546 		    NULL, verbose);
547 	}
548 	free(indent_buf);
549 }
550 
551 static void
show_tree(int verbose)552 show_tree(int verbose)
553 {
554 	struct pci_tree_list head;
555 	struct pci_tree_entry *e, *n;
556 	struct pci_conf *conf;
557 	size_t count;
558 	int fd;
559 	bool last, new_bus;
560 
561 	if (verbose)
562 		load_vendors();
563 
564 	fd = open(_PATH_DEVPCI, O_RDONLY);
565 	if (fd < 0)
566 		err(1, "%s", _PATH_DEVPCI);
567 
568 	if (!fetch_devs(fd, NULL, &conf, &count)) {
569 		exitstatus = 1;
570 		goto close_fd;
571 	}
572 
573 	if (count == 0)
574 		goto close_fd;
575 
576 	if (conf[0].pc_reported_len < offsetof(struct pci_conf, pc_subbus)) {
577 		warnx("kernel too old");
578 		exitstatus = 1;
579 		goto free_conf;
580 	}
581 
582 	/* First, sort devices by DBSF. */
583 	qsort(conf, count, sizeof(*conf), pci_conf_compar);
584 
585 	if (!build_tree(&head, conf, count)) {
586 		warnx("failed to build tree of PCI devices");
587 		exitstatus = 1;
588 		goto free_conf;
589 	}
590 
591 	new_bus = true;
592 	TAILQ_FOREACH(e, &head, link) {
593 		if (new_bus) {
594 			printf("--- pci%d:%d\n", e->p->pc_sel.pc_domain,
595 			    e->p->pc_sel.pc_bus);
596 			new_bus = false;
597 		}
598 
599 		/* Is this the last entry for this bus? */
600 		n = TAILQ_NEXT(e, link);
601 		if (n == NULL ||
602 		    n->p->pc_sel.pc_domain != e->p->pc_sel.pc_domain ||
603 		    n->p->pc_sel.pc_bus != e->p->pc_sel.pc_bus) {
604 			last = true;
605 			new_bus = true;
606 		} else
607 			last = false;
608 
609 		print_tree_entry(e, "  ", last, verbose);
610 	}
611 
612 	free_tree(&head);
613 free_conf:
614 	free(conf);
615 close_fd:
616 	close(fd);
617 }
618 
619 static void
print_bus_range(struct pci_conf * p)620 print_bus_range(struct pci_conf *p)
621 {
622 	printf("    bus range  = %u-%u\n", p->pc_secbus, p->pc_subbus);
623 }
624 
625 static void
print_window(int reg,const char * type,int range,uint64_t base,uint64_t limit)626 print_window(int reg, const char *type, int range, uint64_t base,
627     uint64_t limit)
628 {
629 
630 	printf("    window[%02x] = type %s, range %2d, addr %#jx-%#jx, %s\n",
631 	    reg, type, range, (uintmax_t)base, (uintmax_t)limit,
632 	    base < limit ? "enabled" : "disabled");
633 }
634 
635 static void
print_special_decode(bool isa,bool vga,bool subtractive)636 print_special_decode(bool isa, bool vga, bool subtractive)
637 {
638 	bool comma;
639 
640 	if (isa || vga || subtractive) {
641 		comma = false;
642 		printf("    decode     = ");
643 		if (isa) {
644 			printf("ISA");
645 			comma = true;
646 		}
647 		if (vga) {
648 			printf("%sVGA", comma ? ", " : "");
649 			comma = true;
650 		}
651 		if (subtractive)
652 			printf("%ssubtractive", comma ? ", " : "");
653 		printf("\n");
654 	}
655 }
656 
657 static void
print_bridge_windows(int fd,struct pci_conf * p)658 print_bridge_windows(int fd, struct pci_conf *p)
659 {
660 	uint64_t base, limit;
661 	uint32_t val;
662 	uint16_t bctl;
663 	bool subtractive;
664 	int range;
665 
666 	/*
667 	 * XXX: This assumes that a window with a base and limit of 0
668 	 * is not implemented.  In theory a window might be programmed
669 	 * at the smallest size with a base of 0, but those do not seem
670 	 * common in practice.
671 	 */
672 	val = read_config(fd, &p->pc_sel, PCIR_IOBASEL_1, 1);
673 	if (val != 0 || read_config(fd, &p->pc_sel, PCIR_IOLIMITL_1, 1) != 0) {
674 		if ((val & PCIM_BRIO_MASK) == PCIM_BRIO_32) {
675 			base = PCI_PPBIOBASE(
676 			    read_config(fd, &p->pc_sel, PCIR_IOBASEH_1, 2),
677 			    val);
678 			limit = PCI_PPBIOLIMIT(
679 			    read_config(fd, &p->pc_sel, PCIR_IOLIMITH_1, 2),
680 			    read_config(fd, &p->pc_sel, PCIR_IOLIMITL_1, 1));
681 			range = 32;
682 		} else {
683 			base = PCI_PPBIOBASE(0, val);
684 			limit = PCI_PPBIOLIMIT(0,
685 			    read_config(fd, &p->pc_sel, PCIR_IOLIMITL_1, 1));
686 			range = 16;
687 		}
688 		print_window(PCIR_IOBASEL_1, "I/O Port", range, base, limit);
689 	}
690 
691 	base = PCI_PPBMEMBASE(0,
692 	    read_config(fd, &p->pc_sel, PCIR_MEMBASE_1, 2));
693 	limit = PCI_PPBMEMLIMIT(0,
694 	    read_config(fd, &p->pc_sel, PCIR_MEMLIMIT_1, 2));
695 	print_window(PCIR_MEMBASE_1, "Memory", 32, base, limit);
696 
697 	val = read_config(fd, &p->pc_sel, PCIR_PMBASEL_1, 2);
698 	if (val != 0 || read_config(fd, &p->pc_sel, PCIR_PMLIMITL_1, 2) != 0) {
699 		if ((val & PCIM_BRPM_MASK) == PCIM_BRPM_64) {
700 			base = PCI_PPBMEMBASE(
701 			    read_config(fd, &p->pc_sel, PCIR_PMBASEH_1, 4),
702 			    val);
703 			limit = PCI_PPBMEMLIMIT(
704 			    read_config(fd, &p->pc_sel, PCIR_PMLIMITH_1, 4),
705 			    read_config(fd, &p->pc_sel, PCIR_PMLIMITL_1, 2));
706 			range = 64;
707 		} else {
708 			base = PCI_PPBMEMBASE(0, val);
709 			limit = PCI_PPBMEMLIMIT(0,
710 			    read_config(fd, &p->pc_sel, PCIR_PMLIMITL_1, 2));
711 			range = 32;
712 		}
713 		print_window(PCIR_PMBASEL_1, "Prefetchable Memory", range, base,
714 		    limit);
715 	}
716 
717 	/*
718 	 * XXX: This list of bridges that are subtractive but do not set
719 	 * progif to indicate it is copied from pci_pci.c.
720 	 */
721 	subtractive = p->pc_progif == PCIP_BRIDGE_PCI_SUBTRACTIVE;
722 	switch (p->pc_device << 16 | p->pc_vendor) {
723 	case 0xa002177d:		/* Cavium ThunderX */
724 	case 0x124b8086:		/* Intel 82380FB Mobile */
725 	case 0x060513d7:		/* Toshiba ???? */
726 		subtractive = true;
727 	}
728 	if (p->pc_vendor == 0x8086 && (p->pc_device & 0xff00) == 0x2400)
729 		subtractive = true;
730 
731 	bctl = read_config(fd, &p->pc_sel, PCIR_BRIDGECTL_1, 2);
732 	print_special_decode(bctl & PCIB_BCR_ISA_ENABLE,
733 	    bctl & PCIB_BCR_VGA_ENABLE, subtractive);
734 }
735 
736 static void
print_cardbus_mem_window(int fd,struct pci_conf * p,int basereg,int limitreg,bool prefetch)737 print_cardbus_mem_window(int fd, struct pci_conf *p, int basereg, int limitreg,
738     bool prefetch)
739 {
740 
741 	print_window(basereg, prefetch ? "Prefetchable Memory" : "Memory", 32,
742 	    PCI_CBBMEMBASE(read_config(fd, &p->pc_sel, basereg, 4)),
743 	    PCI_CBBMEMLIMIT(read_config(fd, &p->pc_sel, limitreg, 4)));
744 }
745 
746 static void
print_cardbus_io_window(int fd,struct pci_conf * p,int basereg,int limitreg)747 print_cardbus_io_window(int fd, struct pci_conf *p, int basereg, int limitreg)
748 {
749 	uint32_t base, limit;
750 	uint32_t val;
751 	int range;
752 
753 	val = read_config(fd, &p->pc_sel, basereg, 2);
754 	if ((val & PCIM_CBBIO_MASK) == PCIM_CBBIO_32) {
755 		base = PCI_CBBIOBASE(read_config(fd, &p->pc_sel, basereg, 4));
756 		limit = PCI_CBBIOBASE(read_config(fd, &p->pc_sel, limitreg, 4));
757 		range = 32;
758 	} else {
759 		base = PCI_CBBIOBASE(val);
760 		limit = PCI_CBBIOBASE(read_config(fd, &p->pc_sel, limitreg, 2));
761 		range = 16;
762 	}
763 	print_window(basereg, "I/O Port", range, base, limit);
764 }
765 
766 static void
print_cardbus_windows(int fd,struct pci_conf * p)767 print_cardbus_windows(int fd, struct pci_conf *p)
768 {
769 	uint16_t bctl;
770 
771 	bctl = read_config(fd, &p->pc_sel, PCIR_BRIDGECTL_2, 2);
772 	print_cardbus_mem_window(fd, p, PCIR_MEMBASE0_2, PCIR_MEMLIMIT0_2,
773 	    bctl & CBB_BCR_PREFETCH_0_ENABLE);
774 	print_cardbus_mem_window(fd, p, PCIR_MEMBASE1_2, PCIR_MEMLIMIT1_2,
775 	    bctl & CBB_BCR_PREFETCH_1_ENABLE);
776 	print_cardbus_io_window(fd, p, PCIR_IOBASE0_2, PCIR_IOLIMIT0_2);
777 	print_cardbus_io_window(fd, p, PCIR_IOBASE1_2, PCIR_IOLIMIT1_2);
778 	print_special_decode(bctl & CBB_BCR_ISA_ENABLE,
779 	    bctl & CBB_BCR_VGA_ENABLE, false);
780 }
781 
782 static void
list_bridge(int fd,struct pci_conf * p)783 list_bridge(int fd, struct pci_conf *p)
784 {
785 
786 	switch (p->pc_hdr & PCIM_HDRTYPE) {
787 	case PCIM_HDRTYPE_BRIDGE:
788 		print_bus_range(p);
789 		print_bridge_windows(fd, p);
790 		break;
791 	case PCIM_HDRTYPE_CARDBUS:
792 		print_bus_range(p);
793 		print_cardbus_windows(fd, p);
794 		break;
795 	}
796 }
797 
798 static void
list_bars(int fd,struct pci_conf * p)799 list_bars(int fd, struct pci_conf *p)
800 {
801 	int i, max;
802 
803 	switch (p->pc_hdr & PCIM_HDRTYPE) {
804 	case PCIM_HDRTYPE_NORMAL:
805 		max = PCIR_MAX_BAR_0;
806 		break;
807 	case PCIM_HDRTYPE_BRIDGE:
808 		max = PCIR_MAX_BAR_1;
809 		break;
810 	case PCIM_HDRTYPE_CARDBUS:
811 		max = PCIR_MAX_BAR_2;
812 		break;
813 	default:
814 		return;
815 	}
816 
817 	for (i = 0; i <= max; i++)
818 		print_bar(fd, p, "bar   ", PCIR_BAR(i));
819 }
820 
821 void
print_bar(int fd,struct pci_conf * p,const char * label,uint16_t bar_offset)822 print_bar(int fd, struct pci_conf *p, const char *label, uint16_t bar_offset)
823 {
824 	uint64_t base;
825 	const char *type;
826 	struct pci_bar_io bar;
827 	int range;
828 
829 	bar.pbi_sel = p->pc_sel;
830 	bar.pbi_reg = bar_offset;
831 	if (ioctl(fd, PCIOCGETBAR, &bar) < 0)
832 		return;
833 	if (PCI_BAR_IO(bar.pbi_base)) {
834 		type = "I/O Port";
835 		range = 32;
836 		base = bar.pbi_base & PCIM_BAR_IO_BASE;
837 	} else {
838 		if (bar.pbi_base & PCIM_BAR_MEM_PREFETCH)
839 			type = "Prefetchable Memory";
840 		else
841 			type = "Memory";
842 		switch (bar.pbi_base & PCIM_BAR_MEM_TYPE) {
843 		case PCIM_BAR_MEM_32:
844 			range = 32;
845 			break;
846 		case PCIM_BAR_MEM_1MB:
847 			range = 20;
848 			break;
849 		case PCIM_BAR_MEM_64:
850 			range = 64;
851 			break;
852 		default:
853 			range = -1;
854 		}
855 		base = bar.pbi_base & ~((uint64_t)0xf);
856 	}
857 	printf("    %s[%02x] = type %s, range %2d, base %#jx, ",
858 	    label, bar_offset, type, range, (uintmax_t)base);
859 	printf("size %ju, %s\n", (uintmax_t)bar.pbi_length,
860 	    bar.pbi_enabled ? "enabled" : "disabled");
861 }
862 
863 static void
list_verbose(struct pci_conf * p)864 list_verbose(struct pci_conf *p)
865 {
866 	struct pci_vendor_info	*vi;
867 	struct pci_device_info	*di;
868 	const char *dp;
869 
870 	TAILQ_FOREACH(vi, &pci_vendors, link) {
871 		if (vi->id == p->pc_vendor) {
872 			printf("    vendor     = '%s'\n", vi->desc);
873 			break;
874 		}
875 	}
876 	if (vi == NULL) {
877 		di = NULL;
878 	} else {
879 		TAILQ_FOREACH(di, &vi->devs, link) {
880 			if (di->id == p->pc_device) {
881 				printf("    device     = '%s'\n", di->desc);
882 				break;
883 			}
884 		}
885 	}
886 	if ((dp = guess_class(p)) != NULL)
887 		printf("    class      = %s\n", dp);
888 	if ((dp = guess_subclass(p)) != NULL)
889 		printf("    subclass   = %s\n", dp);
890 }
891 
892 static void
list_vpd(int fd,struct pci_conf * p)893 list_vpd(int fd, struct pci_conf *p)
894 {
895 	struct pci_list_vpd_io list;
896 	struct pci_vpd_element *vpd, *end;
897 
898 	list.plvi_sel = p->pc_sel;
899 	list.plvi_len = 0;
900 	list.plvi_data = NULL;
901 	if (ioctl(fd, PCIOCLISTVPD, &list) < 0 || list.plvi_len == 0)
902 		return;
903 
904 	list.plvi_data = malloc(list.plvi_len);
905 	if (ioctl(fd, PCIOCLISTVPD, &list) < 0) {
906 		free(list.plvi_data);
907 		return;
908 	}
909 
910 	vpd = list.plvi_data;
911 	end = (struct pci_vpd_element *)((char *)vpd + list.plvi_len);
912 	for (; vpd < end; vpd = PVE_NEXT(vpd)) {
913 		if (vpd->pve_flags == PVE_FLAG_IDENT) {
914 			printf("    VPD ident  = '%.*s'\n",
915 			    (int)vpd->pve_datalen, vpd->pve_data);
916 			continue;
917 		}
918 
919 		/* Ignore the checksum keyword. */
920 		if (!(vpd->pve_flags & PVE_FLAG_RW) &&
921 		    memcmp(vpd->pve_keyword, "RV", 2) == 0)
922 			continue;
923 
924 		/* Ignore remaining read-write space. */
925 		if (vpd->pve_flags & PVE_FLAG_RW &&
926 		    memcmp(vpd->pve_keyword, "RW", 2) == 0)
927 			continue;
928 
929 		/* Handle extended capability keyword. */
930 		if (!(vpd->pve_flags & PVE_FLAG_RW) &&
931 		    memcmp(vpd->pve_keyword, "CP", 2) == 0) {
932 			printf("    VPD ro CP  = ID %02x in map 0x%x[0x%x]\n",
933 			    (unsigned int)vpd->pve_data[0],
934 			    PCIR_BAR((unsigned int)vpd->pve_data[1]),
935 			    (unsigned int)vpd->pve_data[3] << 8 |
936 			    (unsigned int)vpd->pve_data[2]);
937 			continue;
938 		}
939 
940 		/* Remaining keywords should all have ASCII values. */
941 		printf("    VPD %s %c%c  = '%.*s'\n",
942 		    vpd->pve_flags & PVE_FLAG_RW ? "rw" : "ro",
943 		    vpd->pve_keyword[0], vpd->pve_keyword[1],
944 		    (int)vpd->pve_datalen, vpd->pve_data);
945 	}
946 	free(list.plvi_data);
947 }
948 
949 /*
950  * This is a direct cut-and-paste from the table in sys/dev/pci/pci.c.
951  */
952 static struct
953 {
954 	int	class;
955 	int	subclass;
956 	const char *desc;
957 } pci_nomatch_tab[] = {
958 	{PCIC_OLD,		-1,			"old"},
959 	{PCIC_OLD,		PCIS_OLD_NONVGA,	"non-VGA display device"},
960 	{PCIC_OLD,		PCIS_OLD_VGA,		"VGA-compatible display device"},
961 	{PCIC_STORAGE,		-1,			"mass storage"},
962 	{PCIC_STORAGE,		PCIS_STORAGE_SCSI,	"SCSI"},
963 	{PCIC_STORAGE,		PCIS_STORAGE_IDE,	"ATA"},
964 	{PCIC_STORAGE,		PCIS_STORAGE_FLOPPY,	"floppy disk"},
965 	{PCIC_STORAGE,		PCIS_STORAGE_IPI,	"IPI"},
966 	{PCIC_STORAGE,		PCIS_STORAGE_RAID,	"RAID"},
967 	{PCIC_STORAGE,		PCIS_STORAGE_ATA_ADMA,	"ATA (ADMA)"},
968 	{PCIC_STORAGE,		PCIS_STORAGE_SATA,	"SATA"},
969 	{PCIC_STORAGE,		PCIS_STORAGE_SAS,	"SAS"},
970 	{PCIC_STORAGE,		PCIS_STORAGE_NVM,	"NVM"},
971 	{PCIC_STORAGE,		PCIS_STORAGE_UFS,	"UFS"},
972 	{PCIC_NETWORK,		-1,			"network"},
973 	{PCIC_NETWORK,		PCIS_NETWORK_ETHERNET,	"ethernet"},
974 	{PCIC_NETWORK,		PCIS_NETWORK_TOKENRING,	"token ring"},
975 	{PCIC_NETWORK,		PCIS_NETWORK_FDDI,	"fddi"},
976 	{PCIC_NETWORK,		PCIS_NETWORK_ATM,	"ATM"},
977 	{PCIC_NETWORK,		PCIS_NETWORK_ISDN,	"ISDN"},
978 	{PCIC_NETWORK,		PCIS_NETWORK_WORLDFIP,	"WorldFip"},
979 	{PCIC_NETWORK,		PCIS_NETWORK_PICMG,	"PICMG"},
980 	{PCIC_NETWORK,		PCIS_NETWORK_INFINIBAND,	"InfiniBand"},
981 	{PCIC_NETWORK,		PCIS_NETWORK_HFC,	"host fabric"},
982 	{PCIC_DISPLAY,		-1,			"display"},
983 	{PCIC_DISPLAY,		PCIS_DISPLAY_VGA,	"VGA"},
984 	{PCIC_DISPLAY,		PCIS_DISPLAY_XGA,	"XGA"},
985 	{PCIC_DISPLAY,		PCIS_DISPLAY_3D,	"3D"},
986 	{PCIC_MULTIMEDIA,	-1,			"multimedia"},
987 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_VIDEO,	"video"},
988 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_AUDIO,	"audio"},
989 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_TELE,	"telephony"},
990 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_HDA,	"HDA"},
991 	{PCIC_MEMORY,		-1,			"memory"},
992 	{PCIC_MEMORY,		PCIS_MEMORY_RAM,	"RAM"},
993 	{PCIC_MEMORY,		PCIS_MEMORY_FLASH,	"flash"},
994 	{PCIC_BRIDGE,		-1,			"bridge"},
995 	{PCIC_BRIDGE,		PCIS_BRIDGE_HOST,	"HOST-PCI"},
996 	{PCIC_BRIDGE,		PCIS_BRIDGE_ISA,	"PCI-ISA"},
997 	{PCIC_BRIDGE,		PCIS_BRIDGE_EISA,	"PCI-EISA"},
998 	{PCIC_BRIDGE,		PCIS_BRIDGE_MCA,	"PCI-MCA"},
999 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI,	"PCI-PCI"},
1000 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCMCIA,	"PCI-PCMCIA"},
1001 	{PCIC_BRIDGE,		PCIS_BRIDGE_NUBUS,	"PCI-NuBus"},
1002 	{PCIC_BRIDGE,		PCIS_BRIDGE_CARDBUS,	"PCI-CardBus"},
1003 	{PCIC_BRIDGE,		PCIS_BRIDGE_RACEWAY,	"PCI-RACEway"},
1004 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI_TRANSPARENT,
1005 	    "Semi-transparent PCI-to-PCI"},
1006 	{PCIC_BRIDGE,		PCIS_BRIDGE_INFINIBAND,	"InfiniBand-PCI"},
1007 	{PCIC_BRIDGE,		PCIS_BRIDGE_AS_PCI,
1008 	    "AdvancedSwitching-PCI"},
1009 	{PCIC_SIMPLECOMM,	-1,			"simple comms"},
1010 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_UART,	"UART"},	/* could detect 16550 */
1011 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_PAR,	"parallel port"},
1012 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MULSER,	"multiport serial"},
1013 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MODEM,	"generic modem"},
1014 	{PCIC_BASEPERIPH,	-1,			"base peripheral"},
1015 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PIC,	"interrupt controller"},
1016 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_DMA,	"DMA controller"},
1017 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_TIMER,	"timer"},
1018 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RTC,	"realtime clock"},
1019 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PCIHOT,	"PCI hot-plug controller"},
1020 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_SDHC,	"SD host controller"},
1021 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_IOMMU,	"IOMMU"},
1022 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RCEC,
1023 	    "Root Complex Event Collector"},
1024 	{PCIC_INPUTDEV,		-1,			"input device"},
1025 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_KEYBOARD,	"keyboard"},
1026 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_DIGITIZER,"digitizer"},
1027 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_MOUSE,	"mouse"},
1028 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_SCANNER,	"scanner"},
1029 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_GAMEPORT,	"gameport"},
1030 	{PCIC_DOCKING,		-1,			"docking station"},
1031 	{PCIC_PROCESSOR,	-1,			"processor"},
1032 	{PCIC_SERIALBUS,	-1,			"serial bus"},
1033 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FW,	"FireWire"},
1034 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_ACCESS,	"AccessBus"},
1035 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SSA,	"SSA"},
1036 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_USB,	"USB"},
1037 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FC,	"Fibre Channel"},
1038 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SMBUS,	"SMBus"},
1039 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_INFINIBAND,	"InfiniBand"},
1040 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_IPMI,	"IPMI"},
1041 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SERCOS,	"SERCOS"},
1042 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_CANBUS,	"CANbus"},
1043 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_MIPI_I3C,	"MIPI I3C"},
1044 	{PCIC_WIRELESS,		-1,			"wireless controller"},
1045 	{PCIC_WIRELESS,		PCIS_WIRELESS_IRDA,	"iRDA"},
1046 	{PCIC_WIRELESS,		PCIS_WIRELESS_IR,	"IR"},
1047 	{PCIC_WIRELESS,		PCIS_WIRELESS_RF,	"RF"},
1048 	{PCIC_WIRELESS,		PCIS_WIRELESS_BLUETOOTH,	"bluetooth"},
1049 	{PCIC_WIRELESS,		PCIS_WIRELESS_BROADBAND,	"broadband"},
1050 	{PCIC_WIRELESS,		PCIS_WIRELESS_80211A,	"ethernet 802.11a"},
1051 	{PCIC_WIRELESS,		PCIS_WIRELESS_80211B,	"ethernet 802.11b"},
1052 	{PCIC_WIRELESS,		PCIS_WIRELESS_CELL,
1053 	    "cellular controller/modem"},
1054 	{PCIC_WIRELESS,		PCIS_WIRELESS_CELL_E,
1055 	    "cellular controller/modem plus ethernet"},
1056 	{PCIC_INTELLIIO,	-1,			"intelligent I/O controller"},
1057 	{PCIC_INTELLIIO,	PCIS_INTELLIIO_I2O,	"I2O"},
1058 	{PCIC_SATCOM,		-1,			"satellite communication"},
1059 	{PCIC_SATCOM,		PCIS_SATCOM_TV,		"sat TV"},
1060 	{PCIC_SATCOM,		PCIS_SATCOM_AUDIO,	"sat audio"},
1061 	{PCIC_SATCOM,		PCIS_SATCOM_VOICE,	"sat voice"},
1062 	{PCIC_SATCOM,		PCIS_SATCOM_DATA,	"sat data"},
1063 	{PCIC_CRYPTO,		-1,			"encrypt/decrypt"},
1064 	{PCIC_CRYPTO,		PCIS_CRYPTO_NETCOMP,	"network/computer crypto"},
1065 	{PCIC_CRYPTO,		PCIS_CRYPTO_ENTERTAIN,	"entertainment crypto"},
1066 	{PCIC_DASP,		-1,			"dasp"},
1067 	{PCIC_DASP,		PCIS_DASP_DPIO,		"DPIO module"},
1068 	{PCIC_DASP,		PCIS_DASP_PERFCNTRS,	"performance counters"},
1069 	{PCIC_DASP,		PCIS_DASP_COMM_SYNC,	"communication synchronizer"},
1070 	{PCIC_DASP,		PCIS_DASP_MGMT_CARD,	"signal processing management"},
1071 	{PCIC_ACCEL,		-1,			"processing accelerators"},
1072 	{PCIC_ACCEL,		PCIS_ACCEL_PROCESSING,	"processing accelerators"},
1073 	{PCIC_INSTRUMENT,	-1,			"non-essential instrumentation"},
1074 	{0, 0,		NULL}
1075 };
1076 
1077 static const char *
guess_class(struct pci_conf * p)1078 guess_class(struct pci_conf *p)
1079 {
1080 	int	i;
1081 
1082 	for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
1083 		if (pci_nomatch_tab[i].class == p->pc_class)
1084 			return(pci_nomatch_tab[i].desc);
1085 	}
1086 	return(NULL);
1087 }
1088 
1089 static const char *
guess_subclass(struct pci_conf * p)1090 guess_subclass(struct pci_conf *p)
1091 {
1092 	int	i;
1093 
1094 	for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
1095 		if ((pci_nomatch_tab[i].class == p->pc_class) &&
1096 		    (pci_nomatch_tab[i].subclass == p->pc_subclass))
1097 			return(pci_nomatch_tab[i].desc);
1098 	}
1099 	return(NULL);
1100 }
1101 
1102 static int
load_vendors(void)1103 load_vendors(void)
1104 {
1105 	const char *dbf;
1106 	FILE *db;
1107 	struct pci_vendor_info *cv;
1108 	struct pci_device_info *cd;
1109 	char buf[1024], str[1024];
1110 	char *ch;
1111 	int id, error;
1112 
1113 	/*
1114 	 * Locate the database and initialise.
1115 	 */
1116 	TAILQ_INIT(&pci_vendors);
1117 	if ((dbf = getenv("PCICONF_VENDOR_DATABASE")) == NULL)
1118 		dbf = _PATH_LPCIVDB;
1119 	if ((db = fopen(dbf, "r")) == NULL) {
1120 		dbf = _PATH_PCIVDB;
1121 		if ((db = fopen(dbf, "r")) == NULL)
1122 			return(1);
1123 	}
1124 	cv = NULL;
1125 	cd = NULL;
1126 	error = 0;
1127 
1128 	/*
1129 	 * Scan input lines from the database
1130 	 */
1131 	for (;;) {
1132 		if (fgets(buf, sizeof(buf), db) == NULL)
1133 			break;
1134 
1135 		if ((ch = strchr(buf, '#')) != NULL)
1136 			*ch = '\0';
1137 		ch = strchr(buf, '\0') - 1;
1138 		while (ch > buf && isspace(*ch))
1139 			*ch-- = '\0';
1140 		if (ch <= buf)
1141 			continue;
1142 
1143 		/* Can't handle subvendor / subdevice entries yet */
1144 		if (buf[0] == '\t' && buf[1] == '\t')
1145 			continue;
1146 
1147 		/* Check for vendor entry */
1148 		if (buf[0] != '\t' && sscanf(buf, "%04x %[^\n]", &id, str) == 2) {
1149 			if ((id == 0) || (strlen(str) < 1))
1150 				continue;
1151 			if ((cv = malloc(sizeof(struct pci_vendor_info))) == NULL) {
1152 				warn("allocating vendor entry");
1153 				error = 1;
1154 				break;
1155 			}
1156 			if ((cv->desc = strdup(str)) == NULL) {
1157 				free(cv);
1158 				warn("allocating vendor description");
1159 				error = 1;
1160 				break;
1161 			}
1162 			cv->id = id;
1163 			TAILQ_INIT(&cv->devs);
1164 			TAILQ_INSERT_TAIL(&pci_vendors, cv, link);
1165 			continue;
1166 		}
1167 
1168 		/* Check for device entry */
1169 		if (buf[0] == '\t' && sscanf(buf + 1, "%04x %[^\n]", &id, str) == 2) {
1170 			if ((id == 0) || (strlen(str) < 1))
1171 				continue;
1172 			if (cv == NULL) {
1173 				warnx("device entry with no vendor!");
1174 				continue;
1175 			}
1176 			if ((cd = malloc(sizeof(struct pci_device_info))) == NULL) {
1177 				warn("allocating device entry");
1178 				error = 1;
1179 				break;
1180 			}
1181 			if ((cd->desc = strdup(str)) == NULL) {
1182 				free(cd);
1183 				warn("allocating device description");
1184 				error = 1;
1185 				break;
1186 			}
1187 			cd->id = id;
1188 			TAILQ_INSERT_TAIL(&cv->devs, cd, link);
1189 			continue;
1190 		}
1191 
1192 		/* It's a comment or junk, ignore it */
1193 	}
1194 	if (ferror(db))
1195 		error = 1;
1196 	fclose(db);
1197 
1198 	return(error);
1199 }
1200 
1201 uint32_t
read_config(int fd,struct pcisel * sel,long reg,int width)1202 read_config(int fd, struct pcisel *sel, long reg, int width)
1203 {
1204 	struct pci_io pi;
1205 
1206 	pi.pi_sel = *sel;
1207 	pi.pi_reg = reg;
1208 	pi.pi_width = width;
1209 
1210 	if (ioctl(fd, PCIOCREAD, &pi) < 0)
1211 		err(1, "ioctl(PCIOCREAD)");
1212 
1213 	return (pi.pi_data);
1214 }
1215 
1216 static struct pcisel
getdevice(const char * name)1217 getdevice(const char *name)
1218 {
1219 	struct pci_conf_io pc;
1220 	struct pci_conf conf[1];
1221 	struct pci_match_conf patterns[1];
1222 	char *cp;
1223 	int fd;
1224 
1225 	fd = open(_PATH_DEVPCI, O_RDONLY, 0);
1226 	if (fd < 0)
1227 		err(1, "%s", _PATH_DEVPCI);
1228 
1229 	bzero(&pc, sizeof(struct pci_conf_io));
1230 	pc.match_buf_len = sizeof(conf);
1231 	pc.matches = conf;
1232 
1233 	bzero(&patterns, sizeof(patterns));
1234 
1235 	/*
1236 	 * The pattern structure requires the unit to be split out from
1237 	 * the driver name.  Walk backwards from the end of the name to
1238 	 * find the start of the unit.
1239 	 */
1240 	if (name[0] == '\0')
1241 		errx(1, "Empty device name");
1242 	cp = strchr(name, '\0');
1243 	assert(cp != NULL && cp != name);
1244 	cp--;
1245 	while (cp != name && isdigit(cp[-1]))
1246 		cp--;
1247 	if (cp == name || !isdigit(*cp))
1248 		errx(1, "Invalid device name");
1249 	if ((size_t)(cp - name) + 1 > sizeof(patterns[0].pd_name))
1250 		errx(1, "Device name is too long");
1251 	memcpy(patterns[0].pd_name, name, cp - name);
1252 	patterns[0].pd_unit = strtol(cp, &cp, 10);
1253 	if (*cp != '\0')
1254 		errx(1, "Invalid device name");
1255 	patterns[0].flags = PCI_GETCONF_MATCH_NAME | PCI_GETCONF_MATCH_UNIT;
1256 	pc.num_patterns = 1;
1257 	pc.pat_buf_len = sizeof(patterns);
1258 	pc.patterns = patterns;
1259 
1260 	if (ioctl(fd, PCIOCGETCONF, &pc) == -1)
1261 		err(1, "ioctl(PCIOCGETCONF)");
1262 	if (pc.status != PCI_GETCONF_LAST_DEVICE &&
1263 	    pc.status != PCI_GETCONF_MORE_DEVS)
1264 		errx(1, "error returned from PCIOCGETCONF ioctl");
1265 	close(fd);
1266 	if (pc.num_matches == 0)
1267 		errx(1, "Device not found");
1268 	return (conf[0].pc_sel);
1269 }
1270 
1271 static struct pcisel
parsesel(const char * str)1272 parsesel(const char *str)
1273 {
1274 	const char *ep;
1275 	char *eppos;
1276 	struct pcisel sel;
1277 	unsigned long selarr[4];
1278 	int i;
1279 
1280 	ep = strchr(str, '@');
1281 	if (ep != NULL)
1282 		ep++;
1283 	else
1284 		ep = str;
1285 
1286 	if (strncmp(ep, "pci", 3) == 0) {
1287 		ep += 3;
1288 		i = 0;
1289 		while (isdigit(*ep) && i < 4) {
1290 			selarr[i++] = strtoul(ep, &eppos, 10);
1291 			ep = eppos;
1292 			if (*ep == ':')
1293 				ep++;
1294 		}
1295 		if (i > 0 && *ep == '\0') {
1296 			sel.pc_func = (i > 2) ? selarr[--i] : 0;
1297 			sel.pc_dev = (i > 0) ? selarr[--i] : 0;
1298 			sel.pc_bus = (i > 0) ? selarr[--i] : 0;
1299 			sel.pc_domain = (i > 0) ? selarr[--i] : 0;
1300 			return (sel);
1301 		}
1302 	}
1303 	errx(1, "cannot parse selector %s", str);
1304 }
1305 
1306 static struct pcisel
getsel(const char * str)1307 getsel(const char *str)
1308 {
1309 
1310 	/*
1311 	 * No device names contain colons and selectors always contain
1312 	 * at least one colon.
1313 	 */
1314 	if (strchr(str, ':') == NULL)
1315 		return (getdevice(str));
1316 	else
1317 		return (parsesel(str));
1318 }
1319 
1320 static void
readit(const char * name,const char * reg,int width)1321 readit(const char *name, const char *reg, int width)
1322 {
1323 	long rstart;
1324 	long rend;
1325 	long r;
1326 	char *end;
1327 	int i, items_per_line;
1328 	int fd;
1329 	struct pcisel sel;
1330 
1331 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
1332 	if (fd < 0)
1333 		err(1, "%s", _PATH_DEVPCI);
1334 
1335 	rend = rstart = strtol(reg, &end, 0);
1336 	if (*end == ':') {
1337 		end++;
1338 		rend = strtol(end, NULL, 0);
1339 	}
1340 	sel = getsel(name);
1341 	items_per_line = 16 / width;
1342 	for (i = 1, r = rstart; r <= rend; i++, r += width) {
1343 		printf("%0*x", width * 2, read_config(fd, &sel, r, width));
1344 
1345 		/* Use a double space in the middle when outputting bytes. */
1346 		if (width == 1 && i % 16 == 8)
1347 			putchar(' ');
1348 
1349 		putchar(i % items_per_line == 0 ? '\n' : ' ');
1350 	}
1351 	if (i % items_per_line != 1)
1352 		putchar('\n');
1353 	close(fd);
1354 }
1355 
1356 static void
writeit(const char * name,const char * reg,const char * data,int width)1357 writeit(const char *name, const char *reg, const char *data, int width)
1358 {
1359 	int fd;
1360 	struct pci_io pi;
1361 
1362 	pi.pi_sel = getsel(name);
1363 	pi.pi_reg = strtoul(reg, NULL, 0); /* XXX error check */
1364 	pi.pi_width = width;
1365 	pi.pi_data = strtoul(data, NULL, 0); /* XXX error check */
1366 
1367 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
1368 	if (fd < 0)
1369 		err(1, "%s", _PATH_DEVPCI);
1370 
1371 	if (ioctl(fd, PCIOCWRITE, &pi) < 0)
1372 		err(1, "ioctl(PCIOCWRITE)");
1373 	close(fd);
1374 }
1375 
1376 static void
chkattached(const char * name)1377 chkattached(const char *name)
1378 {
1379 	int fd;
1380 	struct pci_io pi;
1381 
1382 	pi.pi_sel = getsel(name);
1383 
1384 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
1385 	if (fd < 0)
1386 		err(1, "%s", _PATH_DEVPCI);
1387 
1388 	if (ioctl(fd, PCIOCATTACHED, &pi) < 0)
1389 		err(1, "ioctl(PCIOCATTACHED)");
1390 
1391 	exitstatus = pi.pi_data ? 0 : 2; /* exit(2), if NOT attached */
1392 	printf("%s: %s%s\n", name, pi.pi_data == 0 ? "not " : "", "attached");
1393 	close(fd);
1394 }
1395 
1396 static void
map_bar(const char * name,const char * reg,int flags,struct pci_bar_mmap * pbm)1397 map_bar(const char *name, const char *reg, int flags, struct pci_bar_mmap *pbm)
1398 {
1399 	int fd;
1400 	char *el;
1401 
1402 	memset(pbm, 0, sizeof(struct pci_bar_mmap));
1403 	pbm->pbm_sel = getsel(name);
1404 	pbm->pbm_reg = strtoul(reg, &el, 0);
1405 	if (*reg == '\0' || *el != '\0')
1406 		errx(1, "Invalid bar specification %s", reg);
1407 	pbm->pbm_memattr = VM_MEMATTR_DEVICE;
1408 	pbm->pbm_flags = flags;
1409 
1410 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
1411 	if (fd < 0)
1412 		err(1, "%s", _PATH_DEVPCI);
1413 
1414 	if (ioctl(fd, PCIOCBARMMAP, pbm) < 0)
1415 		err(1, "ioctl(PCIOCBARMMAP)");
1416 
1417 	close(fd);
1418 }
1419 
1420 static void
unmap_bar(struct pci_bar_mmap * pbm)1421 unmap_bar(struct pci_bar_mmap *pbm)
1422 {
1423 	munmap(pbm->pbm_map_base, pbm->pbm_map_length);
1424 }
1425 
1426 static void
dump_bar(const char * name,const char * reg,const char * bar_start,const char * bar_count,int width,int verbose)1427 dump_bar(const char *name, const char *reg, const char *bar_start,
1428     const char *bar_count, int width, int verbose)
1429 {
1430 	struct pci_bar_mmap pbm;
1431 	uint32_t *dd;
1432 	uint16_t *dh;
1433 	uint8_t *db;
1434 	uint64_t *dx, a, start, count;
1435 	char *el;
1436 	size_t res;
1437 
1438 	start = 0;
1439 	if (bar_start != NULL) {
1440 		start = strtoul(bar_start, &el, 0);
1441 		if (*el != '\0')
1442 			errx(1, "Invalid bar start specification %s",
1443 			    bar_start);
1444 	}
1445 	count = 0;
1446 	if (bar_count != NULL) {
1447 		count = strtoul(bar_count, &el, 0);
1448 		if (*el != '\0')
1449 			errx(1, "Invalid count specification %s",
1450 			    bar_count);
1451 	}
1452 
1453 	map_bar(name, reg, 0, &pbm);
1454 
1455 	if (count == 0)
1456 		count = pbm.pbm_bar_length / width;
1457 	if (start + count < start || (start + count) * width < (uint64_t)width)
1458 		errx(1, "(start + count) x width overflow");
1459 	if ((start + count) * width > pbm.pbm_bar_length) {
1460 		if (start * width > pbm.pbm_bar_length)
1461 			count = 0;
1462 		else
1463 			count = (pbm.pbm_bar_length - start * width) / width;
1464 	}
1465 	if (verbose) {
1466 		fprintf(stderr,
1467 		    "Dumping pci%d:%d:%d:%d BAR %x mapped base %p "
1468 		    "off %#x length %#jx from %#jx count %#jx in %d-bytes\n",
1469 		    pbm.pbm_sel.pc_domain, pbm.pbm_sel.pc_bus,
1470 		    pbm.pbm_sel.pc_dev, pbm.pbm_sel.pc_func,
1471 		    pbm.pbm_reg, pbm.pbm_map_base, pbm.pbm_bar_off,
1472 		    pbm.pbm_bar_length, start, count, width);
1473 	}
1474 	switch (width) {
1475 	case 1:
1476 		db = (uint8_t *)(uintptr_t)((uintptr_t)pbm.pbm_map_base +
1477 		    pbm.pbm_bar_off + start * width);
1478 		for (a = 0; a < count; a++, db++) {
1479 			res = fwrite(db, width, 1, stdout);
1480 			if (res != 1) {
1481 				errx(1, "error writing to stdout");
1482 				break;
1483 			}
1484 		}
1485 		break;
1486 	case 2:
1487 		dh = (uint16_t *)(uintptr_t)((uintptr_t)pbm.pbm_map_base +
1488 		    pbm.pbm_bar_off + start * width);
1489 		for (a = 0; a < count; a++, dh++) {
1490 			res = fwrite(dh, width, 1, stdout);
1491 			if (res != 1) {
1492 				errx(1, "error writing to stdout");
1493 				break;
1494 			}
1495 		}
1496 		break;
1497 	case 4:
1498 		dd = (uint32_t *)(uintptr_t)((uintptr_t)pbm.pbm_map_base +
1499 		    pbm.pbm_bar_off + start * width);
1500 		for (a = 0; a < count; a ++, dd++) {
1501 			res = fwrite(dd, width, 1, stdout);
1502 			if (res != 1) {
1503 				errx(1, "error writing to stdout");
1504 				break;
1505 			}
1506 		}
1507 		break;
1508 	case 8:
1509 		dx = (uint64_t *)(uintptr_t)((uintptr_t)pbm.pbm_map_base +
1510 		    pbm.pbm_bar_off + start * width);
1511 		for (a = 0; a < count; a++, dx++) {
1512 			res = fwrite(dx, width, 1, stdout);
1513 			if (res != 1) {
1514 				errx(1, "error writing to stdout");
1515 				break;
1516 			}
1517 		}
1518 		break;
1519 	default:
1520 		errx(1, "invalid access width");
1521 	}
1522 
1523 	unmap_bar(&pbm);
1524 }
1525 
1526 union tunion {
1527 	uint8_t one;
1528 	uint16_t two;
1529 	uint32_t four;
1530 	uint64_t eight;
1531 	uint8_t bytes[8];
1532 };
1533 
1534 static void
read_bar(const char * name,const char * bar,const char * start_end,int width)1535 read_bar(const char *name, const char *bar, const char *start_end, int width)
1536 {
1537 	struct pci_bar_mmap pbm;
1538 	long rstart, rend, r;
1539 	char *end;
1540 	int items_per_line, i;
1541 
1542 	rend = rstart = strtol(start_end, &end, 0);
1543 	if (*end == ':') {
1544 		end++;
1545 		rend = strtol(end, NULL, 0);
1546 	}
1547 
1548 	map_bar(name, bar, 0, &pbm);
1549 
1550 	items_per_line = 16 / width;
1551 	for (i = 1, r = rstart; r <= rend; i++, r += width) {
1552 		uintptr_t addr;
1553 		union tunion t;
1554 		int j;
1555 
1556 		addr = (uintptr_t)pbm.pbm_map_base + pbm.pbm_bar_off + r;
1557 		switch (width) {
1558 		case 1:
1559 			t.one = *((uint8_t *)addr);
1560 			break;
1561 		case 2:
1562 			t.two = *((uint16_t *)addr);
1563 			break;
1564 		case 4:
1565 			t.four = *((uint32_t *)addr);
1566 			break;
1567 		case 8:
1568 			t.eight = *((uint64_t *)addr);
1569 			break;
1570 		default:
1571 			errx(1, "invalid read width");
1572 		}
1573 		for (j = 0; j < width; j++) {
1574 			printf("%02x", t.bytes[j]);
1575 		}
1576 		/* Use a double space in the middle when outputting bytes. */
1577 		if (width == 1 && (i % 16) == 8)
1578 			putchar(' ');
1579 		putchar(i % items_per_line == 0 ? '\n' : ' ');
1580 	}
1581 	if (i % items_per_line != 1)
1582 		putchar('\n');
1583 
1584 	unmap_bar(&pbm);
1585 }
1586 
1587 static void
write_bar(const char * name,const char * bar,const char * offset_str,const char * value_str,int width)1588 write_bar(const char *name, const char *bar, const char *offset_str,
1589     const char *value_str, int width)
1590 {
1591 	struct pci_bar_mmap pbm;
1592 	uint64_t offset, value;
1593 	uintptr_t addr;
1594 	char *el;
1595 
1596 	offset = strtoul(offset_str, &el, 0);
1597 	if (*el != '\0')
1598 		errx(1, "Invalid bar offset specification %s", offset_str);
1599 	value = strtoul(value_str, (char **)0, 0); /* XXX error check */
1600 
1601 	map_bar(name, bar, PCIIO_BAR_MMAP_RW, &pbm);
1602 
1603 	addr = (uintptr_t)pbm.pbm_map_base + pbm.pbm_bar_off + offset;
1604 	switch (width) {
1605 	case 1:
1606 		*((uint8_t *)addr) = value;
1607 		break;
1608 	case 2:
1609 		*((uint16_t *)addr) = value;
1610 		break;
1611 	case 4:
1612 		*((uint32_t *)addr) = value;
1613 		break;
1614 	case 8:
1615 		*((uint64_t *)addr) = value;
1616 		break;
1617 	default:
1618 		errx(1, "invalid write width");
1619 	}
1620 
1621 	unmap_bar(&pbm);
1622 }
1623