xref: /freebsd/usr.sbin/pciconf/pciconf.c (revision 325151a3)
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 
38 #include <assert.h>
39 #include <ctype.h>
40 #include <err.h>
41 #include <inttypes.h>
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <sys/pciio.h>
47 #include <sys/queue.h>
48 
49 #include <dev/pci/pcireg.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 TAILQ_HEAD(,pci_vendor_info)	pci_vendors;
70 
71 static struct pcisel getsel(const char *str);
72 static void list_bars(int fd, struct pci_conf *p);
73 static void list_devs(const char *name, int verbose, int bars, int caps,
74     int errors, int vpd);
75 static void list_verbose(struct pci_conf *p);
76 static void list_vpd(int fd, struct pci_conf *p);
77 static const char *guess_class(struct pci_conf *p);
78 static const char *guess_subclass(struct pci_conf *p);
79 static int load_vendors(void);
80 static void readit(const char *, const char *, int);
81 static void writeit(const char *, const char *, const char *, int);
82 static void chkattached(const char *);
83 
84 static int exitstatus = 0;
85 
86 static void
87 usage(void)
88 {
89 	fprintf(stderr, "%s\n%s\n%s\n%s\n",
90 		"usage: pciconf -l [-bcevV] [device]",
91 		"       pciconf -a device",
92 		"       pciconf -r [-b | -h] device addr[:addr2]",
93 		"       pciconf -w [-b | -h] device addr value");
94 	exit (1);
95 }
96 
97 int
98 main(int argc, char **argv)
99 {
100 	int c;
101 	int listmode, readmode, writemode, attachedmode;
102 	int bars, caps, errors, verbose, vpd;
103 	int byte, isshort;
104 
105 	listmode = readmode = writemode = attachedmode = 0;
106 	bars = caps = errors = verbose = vpd = byte = isshort = 0;
107 
108 	while ((c = getopt(argc, argv, "abcehlrwvV")) != -1) {
109 		switch(c) {
110 		case 'a':
111 			attachedmode = 1;
112 			break;
113 
114 		case 'b':
115 			bars = 1;
116 			byte = 1;
117 			break;
118 
119 		case 'c':
120 			caps = 1;
121 			break;
122 
123 		case 'e':
124 			errors = 1;
125 			break;
126 
127 		case 'h':
128 			isshort = 1;
129 			break;
130 
131 		case 'l':
132 			listmode = 1;
133 			break;
134 
135 		case 'r':
136 			readmode = 1;
137 			break;
138 
139 		case 'w':
140 			writemode = 1;
141 			break;
142 
143 		case 'v':
144 			verbose = 1;
145 			break;
146 
147 		case 'V':
148 			vpd = 1;
149 			break;
150 
151 		default:
152 			usage();
153 		}
154 	}
155 
156 	if ((listmode && optind >= argc + 1)
157 	    || (writemode && optind + 3 != argc)
158 	    || (readmode && optind + 2 != argc)
159 	    || (attachedmode && optind + 1 != argc))
160 		usage();
161 
162 	if (listmode) {
163 		list_devs(optind + 1 == argc ? argv[optind] : NULL, verbose,
164 		    bars, caps, errors, vpd);
165 	} else if (attachedmode) {
166 		chkattached(argv[optind]);
167 	} else if (readmode) {
168 		readit(argv[optind], argv[optind + 1],
169 		    byte ? 1 : isshort ? 2 : 4);
170 	} else if (writemode) {
171 		writeit(argv[optind], argv[optind + 1], argv[optind + 2],
172 		    byte ? 1 : isshort ? 2 : 4);
173 	} else {
174 		usage();
175 	}
176 
177 	return exitstatus;
178 }
179 
180 static void
181 list_devs(const char *name, int verbose, int bars, int caps, int errors,
182     int vpd)
183 {
184 	int fd;
185 	struct pci_conf_io pc;
186 	struct pci_conf conf[255], *p;
187 	struct pci_match_conf patterns[1];
188 	int none_count = 0;
189 
190 	if (verbose)
191 		load_vendors();
192 
193 	fd = open(_PATH_DEVPCI, (caps || errors) ? O_RDWR : O_RDONLY, 0);
194 	if (fd < 0)
195 		err(1, "%s", _PATH_DEVPCI);
196 
197 	bzero(&pc, sizeof(struct pci_conf_io));
198 	pc.match_buf_len = sizeof(conf);
199 	pc.matches = conf;
200 	if (name != NULL) {
201 		bzero(&patterns, sizeof(patterns));
202 		patterns[0].pc_sel = getsel(name);
203 		patterns[0].flags = PCI_GETCONF_MATCH_DOMAIN |
204 		    PCI_GETCONF_MATCH_BUS | PCI_GETCONF_MATCH_DEV |
205 		    PCI_GETCONF_MATCH_FUNC;
206 		pc.num_patterns = 1;
207 		pc.pat_buf_len = sizeof(patterns);
208 		pc.patterns = patterns;
209 	}
210 
211 	do {
212 		if (ioctl(fd, PCIOCGETCONF, &pc) == -1)
213 			err(1, "ioctl(PCIOCGETCONF)");
214 
215 		/*
216 		 * 255 entries should be more than enough for most people,
217 		 * but if someone has more devices, and then changes things
218 		 * around between ioctls, we'll do the cheesy thing and
219 		 * just bail.  The alternative would be to go back to the
220 		 * beginning of the list, and print things twice, which may
221 		 * not be desirable.
222 		 */
223 		if (pc.status == PCI_GETCONF_LIST_CHANGED) {
224 			warnx("PCI device list changed, please try again");
225 			exitstatus = 1;
226 			close(fd);
227 			return;
228 		} else if (pc.status ==  PCI_GETCONF_ERROR) {
229 			warnx("error returned from PCIOCGETCONF ioctl");
230 			exitstatus = 1;
231 			close(fd);
232 			return;
233 		}
234 		for (p = conf; p < &conf[pc.num_matches]; p++) {
235 			printf("%s%d@pci%d:%d:%d:%d:\tclass=0x%06x card=0x%08x "
236 			    "chip=0x%08x rev=0x%02x hdr=0x%02x\n",
237 			    *p->pd_name ? p->pd_name :
238 			    "none",
239 			    *p->pd_name ? (int)p->pd_unit :
240 			    none_count++, p->pc_sel.pc_domain,
241 			    p->pc_sel.pc_bus, p->pc_sel.pc_dev,
242 			    p->pc_sel.pc_func, (p->pc_class << 16) |
243 			    (p->pc_subclass << 8) | p->pc_progif,
244 			    (p->pc_subdevice << 16) | p->pc_subvendor,
245 			    (p->pc_device << 16) | p->pc_vendor,
246 			    p->pc_revid, p->pc_hdr);
247 			if (verbose)
248 				list_verbose(p);
249 			if (bars)
250 				list_bars(fd, p);
251 			if (caps)
252 				list_caps(fd, p);
253 			if (errors)
254 				list_errors(fd, p);
255 			if (vpd)
256 				list_vpd(fd, p);
257 		}
258 	} while (pc.status == PCI_GETCONF_MORE_DEVS);
259 
260 	close(fd);
261 }
262 
263 static void
264 list_bars(int fd, struct pci_conf *p)
265 {
266 	int i, max;
267 
268 	switch (p->pc_hdr & PCIM_HDRTYPE) {
269 	case PCIM_HDRTYPE_NORMAL:
270 		max = PCIR_MAX_BAR_0;
271 		break;
272 	case PCIM_HDRTYPE_BRIDGE:
273 		max = PCIR_MAX_BAR_1;
274 		break;
275 	case PCIM_HDRTYPE_CARDBUS:
276 		max = PCIR_MAX_BAR_2;
277 		break;
278 	default:
279 		return;
280 	}
281 
282 	for (i = 0; i <= max; i++)
283 		print_bar(fd, p, "bar   ", PCIR_BAR(i));
284 }
285 
286 void
287 print_bar(int fd, struct pci_conf *p, const char *label, uint16_t bar_offset)
288 {
289 	uint64_t base;
290 	const char *type;
291 	struct pci_bar_io bar;
292 	int range;
293 
294 	bar.pbi_sel = p->pc_sel;
295 	bar.pbi_reg = bar_offset;
296 	if (ioctl(fd, PCIOCGETBAR, &bar) < 0)
297 		return;
298 	if (PCI_BAR_IO(bar.pbi_base)) {
299 		type = "I/O Port";
300 		range = 32;
301 		base = bar.pbi_base & PCIM_BAR_IO_BASE;
302 	} else {
303 		if (bar.pbi_base & PCIM_BAR_MEM_PREFETCH)
304 			type = "Prefetchable Memory";
305 		else
306 			type = "Memory";
307 		switch (bar.pbi_base & PCIM_BAR_MEM_TYPE) {
308 		case PCIM_BAR_MEM_32:
309 			range = 32;
310 			break;
311 		case PCIM_BAR_MEM_1MB:
312 			range = 20;
313 			break;
314 		case PCIM_BAR_MEM_64:
315 			range = 64;
316 			break;
317 		default:
318 			range = -1;
319 		}
320 		base = bar.pbi_base & ~((uint64_t)0xf);
321 	}
322 	printf("    %s[%02x] = type %s, range %2d, base %#jx, ",
323 	    label, bar_offset, type, range, (uintmax_t)base);
324 	printf("size %ju, %s\n", (uintmax_t)bar.pbi_length,
325 	    bar.pbi_enabled ? "enabled" : "disabled");
326 }
327 
328 static void
329 list_verbose(struct pci_conf *p)
330 {
331 	struct pci_vendor_info	*vi;
332 	struct pci_device_info	*di;
333 	const char *dp;
334 
335 	TAILQ_FOREACH(vi, &pci_vendors, link) {
336 		if (vi->id == p->pc_vendor) {
337 			printf("    vendor     = '%s'\n", vi->desc);
338 			break;
339 		}
340 	}
341 	if (vi == NULL) {
342 		di = NULL;
343 	} else {
344 		TAILQ_FOREACH(di, &vi->devs, link) {
345 			if (di->id == p->pc_device) {
346 				printf("    device     = '%s'\n", di->desc);
347 				break;
348 			}
349 		}
350 	}
351 	if ((dp = guess_class(p)) != NULL)
352 		printf("    class      = %s\n", dp);
353 	if ((dp = guess_subclass(p)) != NULL)
354 		printf("    subclass   = %s\n", dp);
355 }
356 
357 static void
358 list_vpd(int fd, struct pci_conf *p)
359 {
360 	struct pci_list_vpd_io list;
361 	struct pci_vpd_element *vpd, *end;
362 
363 	list.plvi_sel = p->pc_sel;
364 	list.plvi_len = 0;
365 	list.plvi_data = NULL;
366 	if (ioctl(fd, PCIOCLISTVPD, &list) < 0 || list.plvi_len == 0)
367 		return;
368 
369 	list.plvi_data = malloc(list.plvi_len);
370 	if (ioctl(fd, PCIOCLISTVPD, &list) < 0) {
371 		free(list.plvi_data);
372 		return;
373 	}
374 
375 	vpd = list.plvi_data;
376 	end = (struct pci_vpd_element *)((char *)vpd + list.plvi_len);
377 	for (; vpd < end; vpd = PVE_NEXT(vpd)) {
378 		if (vpd->pve_flags == PVE_FLAG_IDENT) {
379 			printf("    VPD ident  = '%.*s'\n",
380 			    (int)vpd->pve_datalen, vpd->pve_data);
381 			continue;
382 		}
383 
384 		/* Ignore the checksum keyword. */
385 		if (!(vpd->pve_flags & PVE_FLAG_RW) &&
386 		    memcmp(vpd->pve_keyword, "RV", 2) == 0)
387 			continue;
388 
389 		/* Ignore remaining read-write space. */
390 		if (vpd->pve_flags & PVE_FLAG_RW &&
391 		    memcmp(vpd->pve_keyword, "RW", 2) == 0)
392 			continue;
393 
394 		/* Handle extended capability keyword. */
395 		if (!(vpd->pve_flags & PVE_FLAG_RW) &&
396 		    memcmp(vpd->pve_keyword, "CP", 2) == 0) {
397 			printf("    VPD ro CP  = ID %02x in map 0x%x[0x%x]\n",
398 			    (unsigned int)vpd->pve_data[0],
399 			    PCIR_BAR((unsigned int)vpd->pve_data[1]),
400 			    (unsigned int)vpd->pve_data[3] << 8 |
401 			    (unsigned int)vpd->pve_data[2]);
402 			continue;
403 		}
404 
405 		/* Remaining keywords should all have ASCII values. */
406 		printf("    VPD %s %c%c  = '%.*s'\n",
407 		    vpd->pve_flags & PVE_FLAG_RW ? "rw" : "ro",
408 		    vpd->pve_keyword[0], vpd->pve_keyword[1],
409 		    (int)vpd->pve_datalen, vpd->pve_data);
410 	}
411 	free(list.plvi_data);
412 }
413 
414 /*
415  * This is a direct cut-and-paste from the table in sys/dev/pci/pci.c.
416  */
417 static struct
418 {
419 	int	class;
420 	int	subclass;
421 	const char *desc;
422 } pci_nomatch_tab[] = {
423 	{PCIC_OLD,		-1,			"old"},
424 	{PCIC_OLD,		PCIS_OLD_NONVGA,	"non-VGA display device"},
425 	{PCIC_OLD,		PCIS_OLD_VGA,		"VGA-compatible display device"},
426 	{PCIC_STORAGE,		-1,			"mass storage"},
427 	{PCIC_STORAGE,		PCIS_STORAGE_SCSI,	"SCSI"},
428 	{PCIC_STORAGE,		PCIS_STORAGE_IDE,	"ATA"},
429 	{PCIC_STORAGE,		PCIS_STORAGE_FLOPPY,	"floppy disk"},
430 	{PCIC_STORAGE,		PCIS_STORAGE_IPI,	"IPI"},
431 	{PCIC_STORAGE,		PCIS_STORAGE_RAID,	"RAID"},
432 	{PCIC_STORAGE,		PCIS_STORAGE_ATA_ADMA,	"ATA (ADMA)"},
433 	{PCIC_STORAGE,		PCIS_STORAGE_SATA,	"SATA"},
434 	{PCIC_STORAGE,		PCIS_STORAGE_SAS,	"SAS"},
435 	{PCIC_STORAGE,		PCIS_STORAGE_NVM,	"NVM"},
436 	{PCIC_NETWORK,		-1,			"network"},
437 	{PCIC_NETWORK,		PCIS_NETWORK_ETHERNET,	"ethernet"},
438 	{PCIC_NETWORK,		PCIS_NETWORK_TOKENRING,	"token ring"},
439 	{PCIC_NETWORK,		PCIS_NETWORK_FDDI,	"fddi"},
440 	{PCIC_NETWORK,		PCIS_NETWORK_ATM,	"ATM"},
441 	{PCIC_NETWORK,		PCIS_NETWORK_ISDN,	"ISDN"},
442 	{PCIC_DISPLAY,		-1,			"display"},
443 	{PCIC_DISPLAY,		PCIS_DISPLAY_VGA,	"VGA"},
444 	{PCIC_DISPLAY,		PCIS_DISPLAY_XGA,	"XGA"},
445 	{PCIC_DISPLAY,		PCIS_DISPLAY_3D,	"3D"},
446 	{PCIC_MULTIMEDIA,	-1,			"multimedia"},
447 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_VIDEO,	"video"},
448 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_AUDIO,	"audio"},
449 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_TELE,	"telephony"},
450 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_HDA,	"HDA"},
451 	{PCIC_MEMORY,		-1,			"memory"},
452 	{PCIC_MEMORY,		PCIS_MEMORY_RAM,	"RAM"},
453 	{PCIC_MEMORY,		PCIS_MEMORY_FLASH,	"flash"},
454 	{PCIC_BRIDGE,		-1,			"bridge"},
455 	{PCIC_BRIDGE,		PCIS_BRIDGE_HOST,	"HOST-PCI"},
456 	{PCIC_BRIDGE,		PCIS_BRIDGE_ISA,	"PCI-ISA"},
457 	{PCIC_BRIDGE,		PCIS_BRIDGE_EISA,	"PCI-EISA"},
458 	{PCIC_BRIDGE,		PCIS_BRIDGE_MCA,	"PCI-MCA"},
459 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI,	"PCI-PCI"},
460 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCMCIA,	"PCI-PCMCIA"},
461 	{PCIC_BRIDGE,		PCIS_BRIDGE_NUBUS,	"PCI-NuBus"},
462 	{PCIC_BRIDGE,		PCIS_BRIDGE_CARDBUS,	"PCI-CardBus"},
463 	{PCIC_BRIDGE,		PCIS_BRIDGE_RACEWAY,	"PCI-RACEway"},
464 	{PCIC_SIMPLECOMM,	-1,			"simple comms"},
465 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_UART,	"UART"},	/* could detect 16550 */
466 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_PAR,	"parallel port"},
467 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MULSER,	"multiport serial"},
468 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MODEM,	"generic modem"},
469 	{PCIC_BASEPERIPH,	-1,			"base peripheral"},
470 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PIC,	"interrupt controller"},
471 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_DMA,	"DMA controller"},
472 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_TIMER,	"timer"},
473 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RTC,	"realtime clock"},
474 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PCIHOT,	"PCI hot-plug controller"},
475 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_SDHC,	"SD host controller"},
476 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_IOMMU,	"IOMMU"},
477 	{PCIC_INPUTDEV,		-1,			"input device"},
478 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_KEYBOARD,	"keyboard"},
479 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_DIGITIZER,"digitizer"},
480 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_MOUSE,	"mouse"},
481 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_SCANNER,	"scanner"},
482 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_GAMEPORT,	"gameport"},
483 	{PCIC_DOCKING,		-1,			"docking station"},
484 	{PCIC_PROCESSOR,	-1,			"processor"},
485 	{PCIC_SERIALBUS,	-1,			"serial bus"},
486 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FW,	"FireWire"},
487 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_ACCESS,	"AccessBus"},
488 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SSA,	"SSA"},
489 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_USB,	"USB"},
490 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FC,	"Fibre Channel"},
491 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SMBUS,	"SMBus"},
492 	{PCIC_WIRELESS,		-1,			"wireless controller"},
493 	{PCIC_WIRELESS,		PCIS_WIRELESS_IRDA,	"iRDA"},
494 	{PCIC_WIRELESS,		PCIS_WIRELESS_IR,	"IR"},
495 	{PCIC_WIRELESS,		PCIS_WIRELESS_RF,	"RF"},
496 	{PCIC_INTELLIIO,	-1,			"intelligent I/O controller"},
497 	{PCIC_INTELLIIO,	PCIS_INTELLIIO_I2O,	"I2O"},
498 	{PCIC_SATCOM,		-1,			"satellite communication"},
499 	{PCIC_SATCOM,		PCIS_SATCOM_TV,		"sat TV"},
500 	{PCIC_SATCOM,		PCIS_SATCOM_AUDIO,	"sat audio"},
501 	{PCIC_SATCOM,		PCIS_SATCOM_VOICE,	"sat voice"},
502 	{PCIC_SATCOM,		PCIS_SATCOM_DATA,	"sat data"},
503 	{PCIC_CRYPTO,		-1,			"encrypt/decrypt"},
504 	{PCIC_CRYPTO,		PCIS_CRYPTO_NETCOMP,	"network/computer crypto"},
505 	{PCIC_CRYPTO,		PCIS_CRYPTO_NETCOMP,	"entertainment crypto"},
506 	{PCIC_DASP,		-1,			"dasp"},
507 	{PCIC_DASP,		PCIS_DASP_DPIO,		"DPIO module"},
508 	{0, 0,		NULL}
509 };
510 
511 static const char *
512 guess_class(struct pci_conf *p)
513 {
514 	int	i;
515 
516 	for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
517 		if (pci_nomatch_tab[i].class == p->pc_class)
518 			return(pci_nomatch_tab[i].desc);
519 	}
520 	return(NULL);
521 }
522 
523 static const char *
524 guess_subclass(struct pci_conf *p)
525 {
526 	int	i;
527 
528 	for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
529 		if ((pci_nomatch_tab[i].class == p->pc_class) &&
530 		    (pci_nomatch_tab[i].subclass == p->pc_subclass))
531 			return(pci_nomatch_tab[i].desc);
532 	}
533 	return(NULL);
534 }
535 
536 static int
537 load_vendors(void)
538 {
539 	const char *dbf;
540 	FILE *db;
541 	struct pci_vendor_info *cv;
542 	struct pci_device_info *cd;
543 	char buf[1024], str[1024];
544 	char *ch;
545 	int id, error;
546 
547 	/*
548 	 * Locate the database and initialise.
549 	 */
550 	TAILQ_INIT(&pci_vendors);
551 	if ((dbf = getenv("PCICONF_VENDOR_DATABASE")) == NULL)
552 		dbf = _PATH_LPCIVDB;
553 	if ((db = fopen(dbf, "r")) == NULL) {
554 		dbf = _PATH_PCIVDB;
555 		if ((db = fopen(dbf, "r")) == NULL)
556 			return(1);
557 	}
558 	cv = NULL;
559 	cd = NULL;
560 	error = 0;
561 
562 	/*
563 	 * Scan input lines from the database
564 	 */
565 	for (;;) {
566 		if (fgets(buf, sizeof(buf), db) == NULL)
567 			break;
568 
569 		if ((ch = strchr(buf, '#')) != NULL)
570 			*ch = '\0';
571 		ch = strchr(buf, '\0') - 1;
572 		while (ch > buf && isspace(*ch))
573 			*ch-- = '\0';
574 		if (ch <= buf)
575 			continue;
576 
577 		/* Can't handle subvendor / subdevice entries yet */
578 		if (buf[0] == '\t' && buf[1] == '\t')
579 			continue;
580 
581 		/* Check for vendor entry */
582 		if (buf[0] != '\t' && sscanf(buf, "%04x %[^\n]", &id, str) == 2) {
583 			if ((id == 0) || (strlen(str) < 1))
584 				continue;
585 			if ((cv = malloc(sizeof(struct pci_vendor_info))) == NULL) {
586 				warn("allocating vendor entry");
587 				error = 1;
588 				break;
589 			}
590 			if ((cv->desc = strdup(str)) == NULL) {
591 				free(cv);
592 				warn("allocating vendor description");
593 				error = 1;
594 				break;
595 			}
596 			cv->id = id;
597 			TAILQ_INIT(&cv->devs);
598 			TAILQ_INSERT_TAIL(&pci_vendors, cv, link);
599 			continue;
600 		}
601 
602 		/* Check for device entry */
603 		if (buf[0] == '\t' && sscanf(buf + 1, "%04x %[^\n]", &id, str) == 2) {
604 			if ((id == 0) || (strlen(str) < 1))
605 				continue;
606 			if (cv == NULL) {
607 				warnx("device entry with no vendor!");
608 				continue;
609 			}
610 			if ((cd = malloc(sizeof(struct pci_device_info))) == NULL) {
611 				warn("allocating device entry");
612 				error = 1;
613 				break;
614 			}
615 			if ((cd->desc = strdup(str)) == NULL) {
616 				free(cd);
617 				warn("allocating device description");
618 				error = 1;
619 				break;
620 			}
621 			cd->id = id;
622 			TAILQ_INSERT_TAIL(&cv->devs, cd, link);
623 			continue;
624 		}
625 
626 		/* It's a comment or junk, ignore it */
627 	}
628 	if (ferror(db))
629 		error = 1;
630 	fclose(db);
631 
632 	return(error);
633 }
634 
635 uint32_t
636 read_config(int fd, struct pcisel *sel, long reg, int width)
637 {
638 	struct pci_io pi;
639 
640 	pi.pi_sel = *sel;
641 	pi.pi_reg = reg;
642 	pi.pi_width = width;
643 
644 	if (ioctl(fd, PCIOCREAD, &pi) < 0)
645 		err(1, "ioctl(PCIOCREAD)");
646 
647 	return (pi.pi_data);
648 }
649 
650 static struct pcisel
651 getdevice(const char *name)
652 {
653 	struct pci_conf_io pc;
654 	struct pci_conf conf[1];
655 	struct pci_match_conf patterns[1];
656 	char *cp;
657 	int fd;
658 
659 	fd = open(_PATH_DEVPCI, O_RDONLY, 0);
660 	if (fd < 0)
661 		err(1, "%s", _PATH_DEVPCI);
662 
663 	bzero(&pc, sizeof(struct pci_conf_io));
664 	pc.match_buf_len = sizeof(conf);
665 	pc.matches = conf;
666 
667 	bzero(&patterns, sizeof(patterns));
668 
669 	/*
670 	 * The pattern structure requires the unit to be split out from
671 	 * the driver name.  Walk backwards from the end of the name to
672 	 * find the start of the unit.
673 	 */
674 	if (name[0] == '\0')
675 		errx(1, "Empty device name");
676 	cp = strchr(name, '\0');
677 	assert(cp != NULL && cp != name);
678 	cp--;
679 	while (cp != name && isdigit(cp[-1]))
680 		cp--;
681 	if (cp == name || !isdigit(*cp))
682 		errx(1, "Invalid device name");
683 	if ((size_t)(cp - name) + 1 > sizeof(patterns[0].pd_name))
684 		errx(1, "Device name is too long");
685 	memcpy(patterns[0].pd_name, name, cp - name);
686 	patterns[0].pd_unit = strtol(cp, &cp, 10);
687 	assert(*cp == '\0');
688 	patterns[0].flags = PCI_GETCONF_MATCH_NAME | PCI_GETCONF_MATCH_UNIT;
689 	pc.num_patterns = 1;
690 	pc.pat_buf_len = sizeof(patterns);
691 	pc.patterns = patterns;
692 
693 	if (ioctl(fd, PCIOCGETCONF, &pc) == -1)
694 		err(1, "ioctl(PCIOCGETCONF)");
695 	if (pc.status != PCI_GETCONF_LAST_DEVICE &&
696 	    pc.status != PCI_GETCONF_MORE_DEVS)
697 		errx(1, "error returned from PCIOCGETCONF ioctl");
698 	close(fd);
699 	if (pc.num_matches == 0)
700 		errx(1, "Device not found");
701 	return (conf[0].pc_sel);
702 }
703 
704 static struct pcisel
705 parsesel(const char *str)
706 {
707 	char *ep = strchr(str, '@');
708 	char *epbase;
709 	struct pcisel sel;
710 	unsigned long selarr[4];
711 	int i;
712 
713 	if (ep == NULL)
714 		ep = (char *)str;
715 	else
716 		ep++;
717 
718 	epbase = ep;
719 
720 	if (strncmp(ep, "pci", 3) == 0) {
721 		ep += 3;
722 		i = 0;
723 		do {
724 			selarr[i++] = strtoul(ep, &ep, 10);
725 		} while ((*ep == ':' || *ep == '.') && *++ep != '\0' && i < 4);
726 
727 		if (i > 2)
728 			sel.pc_func = selarr[--i];
729 		else
730 			sel.pc_func = 0;
731 		sel.pc_dev = selarr[--i];
732 		sel.pc_bus = selarr[--i];
733 		if (i > 0)
734 			sel.pc_domain = selarr[--i];
735 		else
736 			sel.pc_domain = 0;
737 	}
738 	if (*ep != '\x0' || ep == epbase)
739 		errx(1, "cannot parse selector %s", str);
740 	return sel;
741 }
742 
743 static struct pcisel
744 getsel(const char *str)
745 {
746 
747 	/*
748 	 * No device names contain colons and selectors always contain
749 	 * at least one colon.
750 	 */
751 	if (strchr(str, ':') == NULL)
752 		return (getdevice(str));
753 	else
754 		return (parsesel(str));
755 }
756 
757 static void
758 readone(int fd, struct pcisel *sel, long reg, int width)
759 {
760 
761 	printf("%0*x", width*2, read_config(fd, sel, reg, width));
762 }
763 
764 static void
765 readit(const char *name, const char *reg, int width)
766 {
767 	long rstart;
768 	long rend;
769 	long r;
770 	char *end;
771 	int i;
772 	int fd;
773 	struct pcisel sel;
774 
775 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
776 	if (fd < 0)
777 		err(1, "%s", _PATH_DEVPCI);
778 
779 	rend = rstart = strtol(reg, &end, 0);
780 	if (end && *end == ':') {
781 		end++;
782 		rend = strtol(end, (char **) 0, 0);
783 	}
784 	sel = getsel(name);
785 	for (i = 1, r = rstart; r <= rend; i++, r += width) {
786 		readone(fd, &sel, r, width);
787 		if (i && !(i % 8))
788 			putchar(' ');
789 		putchar(i % (16/width) ? ' ' : '\n');
790 	}
791 	if (i % (16/width) != 1)
792 		putchar('\n');
793 	close(fd);
794 }
795 
796 static void
797 writeit(const char *name, const char *reg, const char *data, int width)
798 {
799 	int fd;
800 	struct pci_io pi;
801 
802 	pi.pi_sel = getsel(name);
803 	pi.pi_reg = strtoul(reg, (char **)0, 0); /* XXX error check */
804 	pi.pi_width = width;
805 	pi.pi_data = strtoul(data, (char **)0, 0); /* XXX error check */
806 
807 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
808 	if (fd < 0)
809 		err(1, "%s", _PATH_DEVPCI);
810 
811 	if (ioctl(fd, PCIOCWRITE, &pi) < 0)
812 		err(1, "ioctl(PCIOCWRITE)");
813 }
814 
815 static void
816 chkattached(const char *name)
817 {
818 	int fd;
819 	struct pci_io pi;
820 
821 	pi.pi_sel = getsel(name);
822 
823 	fd = open(_PATH_DEVPCI, O_RDWR, 0);
824 	if (fd < 0)
825 		err(1, "%s", _PATH_DEVPCI);
826 
827 	if (ioctl(fd, PCIOCATTACHED, &pi) < 0)
828 		err(1, "ioctl(PCIOCATTACHED)");
829 
830 	exitstatus = pi.pi_data ? 0 : 2; /* exit(2), if NOT attached */
831 	printf("%s: %s%s\n", name, pi.pi_data == 0 ? "not " : "", "attached");
832 }
833