xref: /netbsd-src/sys/dev/pci/pci.c (revision a6f3f22f245acb8ee3bbf6871d7dce989204fa97)
1 /*	$NetBSD: pci.c,v 1.149 2015/10/02 05:22:53 msaitoh Exp $	*/
2 
3 /*
4  * Copyright (c) 1995, 1996, 1997, 1998
5  *     Christopher G. Demetriou.  All rights reserved.
6  * Copyright (c) 1994 Charles M. Hannum.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by Charles M. Hannum.
19  * 4. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  * PCI bus autoconfiguration.
36  */
37 
38 #include <sys/cdefs.h>
39 __KERNEL_RCSID(0, "$NetBSD: pci.c,v 1.149 2015/10/02 05:22:53 msaitoh Exp $");
40 
41 #ifdef _KERNEL_OPT
42 #include "opt_pci.h"
43 #endif
44 
45 #include <sys/param.h>
46 #include <sys/malloc.h>
47 #include <sys/systm.h>
48 #include <sys/device.h>
49 #include <sys/module.h>
50 
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pcivar.h>
53 #include <dev/pci/pcidevs.h>
54 
55 #include <net/if.h>
56 
57 #include "locators.h"
58 
59 static bool pci_child_register(device_t);
60 
61 #ifdef PCI_CONFIG_DUMP
62 int pci_config_dump = 1;
63 #else
64 int pci_config_dump = 0;
65 #endif
66 
67 int	pciprint(void *, const char *);
68 
69 #ifdef PCI_MACHDEP_ENUMERATE_BUS
70 #define pci_enumerate_bus PCI_MACHDEP_ENUMERATE_BUS
71 #endif
72 
73 /*
74  * Important note about PCI-ISA bridges:
75  *
76  * Callbacks are used to configure these devices so that ISA/EISA bridges
77  * can attach their child busses after PCI configuration is done.
78  *
79  * This works because:
80  *	(1) there can be at most one ISA/EISA bridge per PCI bus, and
81  *	(2) any ISA/EISA bridges must be attached to primary PCI
82  *	    busses (i.e. bus zero).
83  *
84  * That boils down to: there can only be one of these outstanding
85  * at a time, it is cleared when configuring PCI bus 0 before any
86  * subdevices have been found, and it is run after all subdevices
87  * of PCI bus 0 have been found.
88  *
89  * This is needed because there are some (legacy) PCI devices which
90  * can show up as ISA/EISA devices as well (the prime example of which
91  * are VGA controllers).  If you attach ISA from a PCI-ISA/EISA bridge,
92  * and the bridge is seen before the video board is, the board can show
93  * up as an ISA device, and that can (bogusly) complicate the PCI device's
94  * attach code, or make the PCI device not be properly attached at all.
95  *
96  * We use the generic config_defer() facility to achieve this.
97  */
98 
99 int
100 pcirescan(device_t self, const char *ifattr, const int *locators)
101 {
102 	struct pci_softc *sc = device_private(self);
103 
104 	KASSERT(ifattr && !strcmp(ifattr, "pci"));
105 	KASSERT(locators);
106 
107 	pci_enumerate_bus(sc, locators, NULL, NULL);
108 
109 	return 0;
110 }
111 
112 int
113 pcimatch(device_t parent, cfdata_t cf, void *aux)
114 {
115 	struct pcibus_attach_args *pba = aux;
116 
117 	/* Check the locators */
118 	if (cf->cf_loc[PCIBUSCF_BUS] != PCIBUSCF_BUS_DEFAULT &&
119 	    cf->cf_loc[PCIBUSCF_BUS] != pba->pba_bus)
120 		return 0;
121 
122 	/* sanity */
123 	if (pba->pba_bus < 0 || pba->pba_bus > 255)
124 		return 0;
125 
126 	/*
127 	 * XXX check other (hardware?) indicators
128 	 */
129 
130 	return 1;
131 }
132 
133 void
134 pciattach(device_t parent, device_t self, void *aux)
135 {
136 	struct pcibus_attach_args *pba = aux;
137 	struct pci_softc *sc = device_private(self);
138 	int io_enabled, mem_enabled, mrl_enabled, mrm_enabled, mwi_enabled;
139 	const char *sep = "";
140 	static const int wildcard[PCICF_NLOCS] = {
141 		PCICF_DEV_DEFAULT, PCICF_FUNCTION_DEFAULT
142 	};
143 
144 	sc->sc_dev = self;
145 
146 	pci_attach_hook(parent, self, pba);
147 
148 	aprint_naive("\n");
149 	aprint_normal("\n");
150 
151 	io_enabled = (pba->pba_flags & PCI_FLAGS_IO_OKAY);
152 	mem_enabled = (pba->pba_flags & PCI_FLAGS_MEM_OKAY);
153 	mrl_enabled = (pba->pba_flags & PCI_FLAGS_MRL_OKAY);
154 	mrm_enabled = (pba->pba_flags & PCI_FLAGS_MRM_OKAY);
155 	mwi_enabled = (pba->pba_flags & PCI_FLAGS_MWI_OKAY);
156 
157 	if (io_enabled == 0 && mem_enabled == 0) {
158 		aprint_error_dev(self, "no spaces enabled!\n");
159 		goto fail;
160 	}
161 
162 #define	PRINT(str)							\
163 do {									\
164 	aprint_verbose("%s%s", sep, str);				\
165 	sep = ", ";							\
166 } while (/*CONSTCOND*/0)
167 
168 	aprint_verbose_dev(self, "");
169 
170 	if (io_enabled)
171 		PRINT("i/o space");
172 	if (mem_enabled)
173 		PRINT("memory space");
174 	aprint_verbose(" enabled");
175 
176 	if (mrl_enabled || mrm_enabled || mwi_enabled) {
177 		if (mrl_enabled)
178 			PRINT("rd/line");
179 		if (mrm_enabled)
180 			PRINT("rd/mult");
181 		if (mwi_enabled)
182 			PRINT("wr/inv");
183 		aprint_verbose(" ok");
184 	}
185 
186 	aprint_verbose("\n");
187 
188 #undef PRINT
189 
190 	sc->sc_iot = pba->pba_iot;
191 	sc->sc_memt = pba->pba_memt;
192 	sc->sc_dmat = pba->pba_dmat;
193 	sc->sc_dmat64 = pba->pba_dmat64;
194 	sc->sc_pc = pba->pba_pc;
195 	sc->sc_bus = pba->pba_bus;
196 	sc->sc_bridgetag = pba->pba_bridgetag;
197 	sc->sc_maxndevs = pci_bus_maxdevs(pba->pba_pc, pba->pba_bus);
198 	sc->sc_intrswiz = pba->pba_intrswiz;
199 	sc->sc_intrtag = pba->pba_intrtag;
200 	sc->sc_flags = pba->pba_flags;
201 
202 	device_pmf_driver_set_child_register(sc->sc_dev, pci_child_register);
203 
204 	pcirescan(sc->sc_dev, "pci", wildcard);
205 
206 fail:
207 	if (!pmf_device_register(self, NULL, NULL))
208 		aprint_error_dev(self, "couldn't establish power handler\n");
209 }
210 
211 int
212 pcidetach(device_t self, int flags)
213 {
214 	int rc;
215 
216 	if ((rc = config_detach_children(self, flags)) != 0)
217 		return rc;
218 	pmf_device_deregister(self);
219 	return 0;
220 }
221 
222 int
223 pciprint(void *aux, const char *pnp)
224 {
225 	struct pci_attach_args *pa = aux;
226 	char devinfo[256];
227 	const struct pci_quirkdata *qd;
228 
229 	if (pnp) {
230 		pci_devinfo(pa->pa_id, pa->pa_class, 1, devinfo, sizeof(devinfo));
231 		aprint_normal("%s at %s", devinfo, pnp);
232 	}
233 	aprint_normal(" dev %d function %d", pa->pa_device, pa->pa_function);
234 	if (pci_config_dump) {
235 		printf(": ");
236 		pci_conf_print(pa->pa_pc, pa->pa_tag, NULL);
237 		if (!pnp)
238 			pci_devinfo(pa->pa_id, pa->pa_class, 1, devinfo, sizeof(devinfo));
239 		printf("%s at %s", devinfo, pnp ? pnp : "?");
240 		printf(" dev %d function %d (", pa->pa_device, pa->pa_function);
241 #ifdef __i386__
242 		printf("tag %#lx, intrtag %#lx, intrswiz %#lx, intrpin %#lx",
243 		    *(long *)&pa->pa_tag, *(long *)&pa->pa_intrtag,
244 		    (long)pa->pa_intrswiz, (long)pa->pa_intrpin);
245 #else
246 		printf("intrswiz %#lx, intrpin %#lx",
247 		    (long)pa->pa_intrswiz, (long)pa->pa_intrpin);
248 #endif
249 		printf(", i/o %s, mem %s,",
250 		    pa->pa_flags & PCI_FLAGS_IO_OKAY ? "on" : "off",
251 		    pa->pa_flags & PCI_FLAGS_MEM_OKAY ? "on" : "off");
252 		qd = pci_lookup_quirkdata(PCI_VENDOR(pa->pa_id),
253 		    PCI_PRODUCT(pa->pa_id));
254 		if (qd == NULL) {
255 			printf(" no quirks");
256 		} else {
257 			snprintb(devinfo, sizeof (devinfo),
258 			    "\002\001multifn\002singlefn\003skipfunc0"
259 			    "\004skipfunc1\005skipfunc2\006skipfunc3"
260 			    "\007skipfunc4\010skipfunc5\011skipfunc6"
261 			    "\012skipfunc7", qd->quirks);
262 			printf(" quirks %s", devinfo);
263 		}
264 		printf(")");
265 	}
266 	return UNCONF;
267 }
268 
269 int
270 pci_probe_device(struct pci_softc *sc, pcitag_t tag,
271     int (*match)(const struct pci_attach_args *),
272     struct pci_attach_args *pap)
273 {
274 	pci_chipset_tag_t pc = sc->sc_pc;
275 	struct pci_attach_args pa;
276 	pcireg_t id, /* csr, */ pciclass, intr, bhlcr, bar, endbar;
277 #ifdef __HAVE_PCI_MSI_MSIX
278 	pcireg_t cap;
279 	int off;
280 #endif
281 	int ret, pin, bus, device, function, i, width;
282 	int locs[PCICF_NLOCS];
283 
284 	pci_decompose_tag(pc, tag, &bus, &device, &function);
285 
286 	/* a driver already attached? */
287 	if (sc->PCI_SC_DEVICESC(device, function).c_dev != NULL && !match)
288 		return 0;
289 
290 	bhlcr = pci_conf_read(pc, tag, PCI_BHLC_REG);
291 	if (PCI_HDRTYPE_TYPE(bhlcr) > 2)
292 		return 0;
293 
294 	id = pci_conf_read(pc, tag, PCI_ID_REG);
295 	/* csr = pci_conf_read(pc, tag, PCI_COMMAND_STATUS_REG); */
296 	pciclass = pci_conf_read(pc, tag, PCI_CLASS_REG);
297 
298 	/* Invalid vendor ID value? */
299 	if (PCI_VENDOR(id) == PCI_VENDOR_INVALID)
300 		return 0;
301 	/* XXX Not invalid, but we've done this ~forever. */
302 	if (PCI_VENDOR(id) == 0)
303 		return 0;
304 
305 	/* Collect memory range info */
306 	memset(sc->PCI_SC_DEVICESC(device, function).c_range, 0,
307 	    sizeof(sc->PCI_SC_DEVICESC(device, function).c_range));
308 	i = 0;
309 	switch (PCI_HDRTYPE_TYPE(bhlcr)) {
310 	case PCI_HDRTYPE_PPB:
311 		endbar = PCI_MAPREG_PPB_END;
312 		break;
313 	case PCI_HDRTYPE_PCB:
314 		endbar = PCI_MAPREG_PCB_END;
315 		break;
316 	default:
317 		endbar = PCI_MAPREG_END;
318 		break;
319 	}
320 	for (bar = PCI_MAPREG_START; bar < endbar; bar += width) {
321 		struct pci_range *r;
322 		pcireg_t type;
323 
324 		width = 4;
325 		if (pci_mapreg_probe(pc, tag, bar, &type) == 0)
326 			continue;
327 
328 		if (PCI_MAPREG_TYPE(type) == PCI_MAPREG_TYPE_MEM) {
329 			if (PCI_MAPREG_MEM_TYPE(type) ==
330 			    PCI_MAPREG_MEM_TYPE_64BIT)
331 				width = 8;
332 
333 			r = &sc->PCI_SC_DEVICESC(device, function).c_range[i++];
334 			if (pci_mapreg_info(pc, tag, bar, type,
335 			    &r->r_offset, &r->r_size, &r->r_flags) != 0)
336 				break;
337 			if ((PCI_VENDOR(id) == PCI_VENDOR_ATI) && (bar == 0x10)
338 			    && (r->r_size == 0x1000000)) {
339 				struct pci_range *nr;
340 				/*
341 				 * this has to be a mach64
342 				 * split things up so each half-aperture can
343 				 * be mapped PREFETCHABLE except the last page
344 				 * which may contain registers
345 				 */
346 				r->r_size = 0x7ff000;
347 				r->r_flags = BUS_SPACE_MAP_LINEAR |
348 					     BUS_SPACE_MAP_PREFETCHABLE;
349 				nr = &sc->PCI_SC_DEVICESC(device,
350 				    function).c_range[i++];
351 				nr->r_offset = r->r_offset + 0x800000;
352 				nr->r_size = 0x7ff000;
353 				nr->r_flags = BUS_SPACE_MAP_LINEAR |
354 					      BUS_SPACE_MAP_PREFETCHABLE;
355 			}
356 
357 		}
358 	}
359 
360 	pa.pa_iot = sc->sc_iot;
361 	pa.pa_memt = sc->sc_memt;
362 	pa.pa_dmat = sc->sc_dmat;
363 	pa.pa_dmat64 = sc->sc_dmat64;
364 	pa.pa_pc = pc;
365 	pa.pa_bus = bus;
366 	pa.pa_device = device;
367 	pa.pa_function = function;
368 	pa.pa_tag = tag;
369 	pa.pa_id = id;
370 	pa.pa_class = pciclass;
371 
372 	/*
373 	 * Set up memory, I/O enable, and PCI command flags
374 	 * as appropriate.
375 	 */
376 	pa.pa_flags = sc->sc_flags;
377 
378 	/*
379 	 * If the cache line size is not configured, then
380 	 * clear the MRL/MRM/MWI command-ok flags.
381 	 */
382 	if (PCI_CACHELINE(bhlcr) == 0) {
383 		pa.pa_flags &= ~(PCI_FLAGS_MRL_OKAY|
384 		    PCI_FLAGS_MRM_OKAY|PCI_FLAGS_MWI_OKAY);
385 	}
386 
387 	if (sc->sc_bridgetag == NULL) {
388 		pa.pa_intrswiz = 0;
389 		pa.pa_intrtag = tag;
390 	} else {
391 		pa.pa_intrswiz = sc->sc_intrswiz + device;
392 		pa.pa_intrtag = sc->sc_intrtag;
393 	}
394 
395 	intr = pci_conf_read(pc, tag, PCI_INTERRUPT_REG);
396 
397 	pin = PCI_INTERRUPT_PIN(intr);
398 	pa.pa_rawintrpin = pin;
399 	if (pin == PCI_INTERRUPT_PIN_NONE) {
400 		/* no interrupt */
401 		pa.pa_intrpin = 0;
402 	} else {
403 		/*
404 		 * swizzle it based on the number of busses we're
405 		 * behind and our device number.
406 		 */
407 		pa.pa_intrpin = 	/* XXX */
408 		    ((pin + pa.pa_intrswiz - 1) % 4) + 1;
409 	}
410 	pa.pa_intrline = PCI_INTERRUPT_LINE(intr);
411 
412 #ifdef __HAVE_PCI_MSI_MSIX
413 	if (pci_get_ht_capability(pc, tag, PCI_HT_CAP_MSIMAP, &off, &cap)) {
414 		/*
415 		 * XXX Should we enable MSI mapping ourselves on
416 		 * systems that have it disabled?
417 		 */
418 		if (cap & PCI_HT_MSI_ENABLED) {
419 			uint64_t addr;
420 			if ((cap & PCI_HT_MSI_FIXED) == 0) {
421 				addr = pci_conf_read(pc, tag,
422 				    off + PCI_HT_MSI_ADDR_LO);
423 				addr |= (uint64_t)pci_conf_read(pc, tag,
424 				    off + PCI_HT_MSI_ADDR_HI) << 32;
425 			} else
426 				addr = PCI_HT_MSI_FIXED_ADDR;
427 
428 			/*
429 			 * XXX This will fail to enable MSI on systems
430 			 * that don't use the canonical address.
431 			 */
432 			if (addr == PCI_HT_MSI_FIXED_ADDR) {
433 				pa.pa_flags |= PCI_FLAGS_MSI_OKAY;
434 				pa.pa_flags |= PCI_FLAGS_MSIX_OKAY;
435 			}
436 		}
437 	}
438 #endif
439 
440 	if (match != NULL) {
441 		ret = (*match)(&pa);
442 		if (ret != 0 && pap != NULL)
443 			*pap = pa;
444 	} else {
445 		struct pci_child *c;
446 		locs[PCICF_DEV] = device;
447 		locs[PCICF_FUNCTION] = function;
448 
449 		c = &sc->PCI_SC_DEVICESC(device, function);
450 		pci_conf_capture(pc, tag, &c->c_conf);
451 		if (pci_get_powerstate(pc, tag, &c->c_powerstate) == 0)
452 			c->c_psok = true;
453 		else
454 			c->c_psok = false;
455 
456 		c->c_dev = config_found_sm_loc(sc->sc_dev, "pci", locs, &pa,
457 					     pciprint, config_stdsubmatch);
458 
459 		ret = (c->c_dev != NULL);
460 	}
461 
462 	return ret;
463 }
464 
465 void
466 pcidevdetached(device_t self, device_t child)
467 {
468 	struct pci_softc *sc = device_private(self);
469 	int d, f;
470 	pcitag_t tag;
471 	struct pci_child *c;
472 
473 	d = device_locator(child, PCICF_DEV);
474 	f = device_locator(child, PCICF_FUNCTION);
475 
476 	c = &sc->PCI_SC_DEVICESC(d, f);
477 
478 	KASSERT(c->c_dev == child);
479 
480 	tag = pci_make_tag(sc->sc_pc, sc->sc_bus, d, f);
481 	if (c->c_psok)
482 		pci_set_powerstate(sc->sc_pc, tag, c->c_powerstate);
483 	pci_conf_restore(sc->sc_pc, tag, &c->c_conf);
484 	c->c_dev = NULL;
485 }
486 
487 CFATTACH_DECL3_NEW(pci, sizeof(struct pci_softc),
488     pcimatch, pciattach, pcidetach, NULL, pcirescan, pcidevdetached,
489     DVF_DETACH_SHUTDOWN);
490 
491 int
492 pci_get_capability(pci_chipset_tag_t pc, pcitag_t tag, int capid,
493     int *offset, pcireg_t *value)
494 {
495 	pcireg_t reg;
496 	unsigned int ofs;
497 
498 	reg = pci_conf_read(pc, tag, PCI_COMMAND_STATUS_REG);
499 	if (!(reg & PCI_STATUS_CAPLIST_SUPPORT))
500 		return 0;
501 
502 	/* Determine the Capability List Pointer register to start with. */
503 	reg = pci_conf_read(pc, tag, PCI_BHLC_REG);
504 	switch (PCI_HDRTYPE_TYPE(reg)) {
505 	case 0:	/* standard device header */
506 	case 1: /* PCI-PCI bridge header */
507 		ofs = PCI_CAPLISTPTR_REG;
508 		break;
509 	case 2:	/* PCI-CardBus Bridge header */
510 		ofs = PCI_CARDBUS_CAPLISTPTR_REG;
511 		break;
512 	default:
513 		return 0;
514 	}
515 
516 	ofs = PCI_CAPLIST_PTR(pci_conf_read(pc, tag, ofs));
517 	while (ofs != 0) {
518 		if ((ofs & 3) || (ofs < 0x40)) {
519 			int bus, device, function;
520 
521 			pci_decompose_tag(pc, tag, &bus, &device, &function);
522 
523 			printf("Skipping broken PCI header on %d:%d:%d\n",
524 			    bus, device, function);
525 			break;
526 		}
527 		reg = pci_conf_read(pc, tag, ofs);
528 		if (PCI_CAPLIST_CAP(reg) == capid) {
529 			if (offset)
530 				*offset = ofs;
531 			if (value)
532 				*value = reg;
533 			return 1;
534 		}
535 		ofs = PCI_CAPLIST_NEXT(reg);
536 	}
537 
538 	return 0;
539 }
540 
541 int
542 pci_get_ht_capability(pci_chipset_tag_t pc, pcitag_t tag, int capid,
543     int *offset, pcireg_t *value)
544 {
545 	pcireg_t reg;
546 	unsigned int ofs;
547 
548 	if (pci_get_capability(pc, tag, PCI_CAP_LDT, &ofs, NULL) == 0)
549 		return 0;
550 
551 	while (ofs != 0) {
552 #ifdef DIAGNOSTIC
553 		if ((ofs & 3) || (ofs < 0x40))
554 			panic("pci_get_ht_capability");
555 #endif
556 		reg = pci_conf_read(pc, tag, ofs);
557 		if (PCI_HT_CAP(reg) == capid) {
558 			if (offset)
559 				*offset = ofs;
560 			if (value)
561 				*value = reg;
562 			return 1;
563 		}
564 		ofs = PCI_CAPLIST_NEXT(reg);
565 	}
566 
567 	return 0;
568 }
569 
570 /*
571  * return number of the devices's MSI vectors
572  * return 0 if the device does not support MSI
573  */
574 int
575 pci_msi_count(pci_chipset_tag_t pc, pcitag_t tag)
576 {
577 	pcireg_t reg;
578 	uint32_t mmc;
579 	int count, offset;
580 
581 	if (pci_get_capability(pc, tag, PCI_CAP_MSI, &offset, NULL) == 0)
582 		return 0;
583 
584 	reg = pci_conf_read(pc, tag, offset + PCI_MSI_CTL);
585 	mmc = PCI_MSI_CTL_MMC(reg);
586 	count = 1 << mmc;
587 	if (count > PCI_MSI_MAX_VECTORS) {
588 		aprint_error("detect an illegal device! The device use reserved MMC values.\n");
589 		return 0;
590 	}
591 
592 	return count;
593 }
594 
595 /*
596  * return number of the devices's MSI-X vectors
597  * return 0 if the device does not support MSI-X
598  */
599 int
600 pci_msix_count(pci_chipset_tag_t pc, pcitag_t tag)
601 {
602 	pcireg_t reg;
603 	int offset;
604 
605 	if (pci_get_capability(pc, tag, PCI_CAP_MSIX, &offset, NULL) == 0)
606 		return 0;
607 
608 	reg = pci_conf_read(pc, tag, offset + PCI_MSIX_CTL);
609 
610 	return PCI_MSIX_CTL_TBLSIZE(reg);
611 }
612 
613 int
614 pci_get_ext_capability(pci_chipset_tag_t pc, pcitag_t tag, int capid,
615     int *offset, pcireg_t *value)
616 {
617 	pcireg_t reg;
618 	unsigned int ofs;
619 
620 	/* Only supported for PCI-express devices */
621 	if (!pci_get_capability(pc, tag, PCI_CAP_PCIEXPRESS, NULL, NULL))
622 		return 0;
623 
624 	ofs = PCI_EXTCAPLIST_BASE;
625 	reg = pci_conf_read(pc, tag, ofs);
626 	if (reg == 0xffffffff || reg == 0)
627 		return 0;
628 
629 	for (;;) {
630 #ifdef DIAGNOSTIC
631 		if ((ofs & 3) || ofs < PCI_EXTCAPLIST_BASE)
632 			panic("%s: invalid offset %u", __func__, ofs);
633 #endif
634 		if (PCI_EXTCAPLIST_CAP(reg) == capid) {
635 			if (offset != NULL)
636 				*offset = ofs;
637 			if (value != NULL)
638 				*value = reg;
639 			return 1;
640 		}
641 		ofs = PCI_EXTCAPLIST_NEXT(reg);
642 		if (ofs == 0)
643 			break;
644 		reg = pci_conf_read(pc, tag, ofs);
645 	}
646 
647 	return 0;
648 }
649 
650 int
651 pci_find_device(struct pci_attach_args *pa,
652 		int (*match)(const struct pci_attach_args *))
653 {
654 	extern struct cfdriver pci_cd;
655 	device_t pcidev;
656 	int i;
657 	static const int wildcard[2] = {
658 		PCICF_DEV_DEFAULT,
659 		PCICF_FUNCTION_DEFAULT
660 	};
661 
662 	for (i = 0; i < pci_cd.cd_ndevs; i++) {
663 		pcidev = device_lookup(&pci_cd, i);
664 		if (pcidev != NULL &&
665 		    pci_enumerate_bus(device_private(pcidev), wildcard,
666 		    		      match, pa) != 0)
667 			return 1;
668 	}
669 	return 0;
670 }
671 
672 #ifndef PCI_MACHDEP_ENUMERATE_BUS
673 /*
674  * Generic PCI bus enumeration routine.  Used unless machine-dependent
675  * code needs to provide something else.
676  */
677 int
678 pci_enumerate_bus(struct pci_softc *sc, const int *locators,
679     int (*match)(const struct pci_attach_args *), struct pci_attach_args *pap)
680 {
681 	pci_chipset_tag_t pc = sc->sc_pc;
682 	int device, function, nfunctions, ret;
683 	const struct pci_quirkdata *qd;
684 	pcireg_t id, bhlcr;
685 	pcitag_t tag;
686 	uint8_t devs[32];
687 	int i, n;
688 
689 	n = pci_bus_devorder(sc->sc_pc, sc->sc_bus, devs, __arraycount(devs));
690 	for (i = 0; i < n; i++) {
691 		device = devs[i];
692 
693 		if ((locators[PCICF_DEV] != PCICF_DEV_DEFAULT) &&
694 		    (locators[PCICF_DEV] != device))
695 			continue;
696 
697 		tag = pci_make_tag(pc, sc->sc_bus, device, 0);
698 
699 		bhlcr = pci_conf_read(pc, tag, PCI_BHLC_REG);
700 		if (PCI_HDRTYPE_TYPE(bhlcr) > 2)
701 			continue;
702 
703 		id = pci_conf_read(pc, tag, PCI_ID_REG);
704 
705 		/* Invalid vendor ID value? */
706 		if (PCI_VENDOR(id) == PCI_VENDOR_INVALID)
707 			continue;
708 		/* XXX Not invalid, but we've done this ~forever. */
709 		if (PCI_VENDOR(id) == 0)
710 			continue;
711 
712 		qd = pci_lookup_quirkdata(PCI_VENDOR(id), PCI_PRODUCT(id));
713 
714 		if (qd != NULL &&
715 		      (qd->quirks & PCI_QUIRK_MULTIFUNCTION) != 0)
716 			nfunctions = 8;
717 		else if (qd != NULL &&
718 		      (qd->quirks & PCI_QUIRK_MONOFUNCTION) != 0)
719 			nfunctions = 1;
720 		else
721 			nfunctions = PCI_HDRTYPE_MULTIFN(bhlcr) ? 8 : 1;
722 
723 #ifdef __PCI_DEV_FUNCORDER
724 		char funcs[8];
725 		int j;
726 		for (j = 0; j < nfunctions; j++) {
727 			funcs[j] = j;
728 		}
729 		if (j < __arraycount(funcs))
730 			funcs[j] = -1;
731 		if (nfunctions > 1) {
732 			pci_dev_funcorder(sc->sc_pc, sc->sc_bus, device,
733 			    nfunctions, funcs);
734 		}
735 		for (j = 0;
736 		     j < 8 && (function = funcs[j]) < 8 && function >= 0;
737 		     j++) {
738 #else
739 		for (function = 0; function < nfunctions; function++) {
740 #endif
741 			if ((locators[PCICF_FUNCTION] != PCICF_FUNCTION_DEFAULT)
742 			    && (locators[PCICF_FUNCTION] != function))
743 				continue;
744 
745 			if (qd != NULL &&
746 			    (qd->quirks & PCI_QUIRK_SKIP_FUNC(function)) != 0)
747 				continue;
748 			tag = pci_make_tag(pc, sc->sc_bus, device, function);
749 			ret = pci_probe_device(sc, tag, match, pap);
750 			if (match != NULL && ret != 0)
751 				return ret;
752 		}
753 	}
754 	return 0;
755 }
756 #endif /* PCI_MACHDEP_ENUMERATE_BUS */
757 
758 
759 /*
760  * Vital Product Data (PCI 2.2)
761  */
762 
763 int
764 pci_vpd_read(pci_chipset_tag_t pc, pcitag_t tag, int offset, int count,
765     pcireg_t *data)
766 {
767 	uint32_t reg;
768 	int ofs, i, j;
769 
770 	KASSERT(data != NULL);
771 	KASSERT((offset + count) < 0x7fff);
772 
773 	if (pci_get_capability(pc, tag, PCI_CAP_VPD, &ofs, &reg) == 0)
774 		return 1;
775 
776 	for (i = 0; i < count; offset += sizeof(*data), i++) {
777 		reg &= 0x0000ffff;
778 		reg &= ~PCI_VPD_OPFLAG;
779 		reg |= PCI_VPD_ADDRESS(offset);
780 		pci_conf_write(pc, tag, ofs, reg);
781 
782 		/*
783 		 * PCI 2.2 does not specify how long we should poll
784 		 * for completion nor whether the operation can fail.
785 		 */
786 		j = 0;
787 		do {
788 			if (j++ == 20)
789 				return 1;
790 			delay(4);
791 			reg = pci_conf_read(pc, tag, ofs);
792 		} while ((reg & PCI_VPD_OPFLAG) == 0);
793 		data[i] = pci_conf_read(pc, tag, PCI_VPD_DATAREG(ofs));
794 	}
795 
796 	return 0;
797 }
798 
799 int
800 pci_vpd_write(pci_chipset_tag_t pc, pcitag_t tag, int offset, int count,
801     pcireg_t *data)
802 {
803 	pcireg_t reg;
804 	int ofs, i, j;
805 
806 	KASSERT(data != NULL);
807 	KASSERT((offset + count) < 0x7fff);
808 
809 	if (pci_get_capability(pc, tag, PCI_CAP_VPD, &ofs, &reg) == 0)
810 		return 1;
811 
812 	for (i = 0; i < count; offset += sizeof(*data), i++) {
813 		pci_conf_write(pc, tag, PCI_VPD_DATAREG(ofs), data[i]);
814 
815 		reg &= 0x0000ffff;
816 		reg |= PCI_VPD_OPFLAG;
817 		reg |= PCI_VPD_ADDRESS(offset);
818 		pci_conf_write(pc, tag, ofs, reg);
819 
820 		/*
821 		 * PCI 2.2 does not specify how long we should poll
822 		 * for completion nor whether the operation can fail.
823 		 */
824 		j = 0;
825 		do {
826 			if (j++ == 20)
827 				return 1;
828 			delay(1);
829 			reg = pci_conf_read(pc, tag, ofs);
830 		} while (reg & PCI_VPD_OPFLAG);
831 	}
832 
833 	return 0;
834 }
835 
836 int
837 pci_dma64_available(const struct pci_attach_args *pa)
838 {
839 #ifdef _PCI_HAVE_DMA64
840 	if (BUS_DMA_TAG_VALID(pa->pa_dmat64))
841                         return 1;
842 #endif
843         return 0;
844 }
845 
846 void
847 pci_conf_capture(pci_chipset_tag_t pc, pcitag_t tag,
848 		  struct pci_conf_state *pcs)
849 {
850 	int off;
851 
852 	for (off = 0; off < 16; off++)
853 		pcs->reg[off] = pci_conf_read(pc, tag, (off * 4));
854 
855 	return;
856 }
857 
858 void
859 pci_conf_restore(pci_chipset_tag_t pc, pcitag_t tag,
860 		  struct pci_conf_state *pcs)
861 {
862 	int off;
863 	pcireg_t val;
864 
865 	for (off = 15; off >= 0; off--) {
866 		val = pci_conf_read(pc, tag, (off * 4));
867 		if (val != pcs->reg[off])
868 			pci_conf_write(pc, tag, (off * 4), pcs->reg[off]);
869 	}
870 
871 	return;
872 }
873 
874 /*
875  * Power Management Capability (Rev 2.2)
876  */
877 static int
878 pci_get_powerstate_int(pci_chipset_tag_t pc, pcitag_t tag , pcireg_t *state,
879     int offset)
880 {
881 	pcireg_t value, now;
882 
883 	value = pci_conf_read(pc, tag, offset + PCI_PMCSR);
884 	now = value & PCI_PMCSR_STATE_MASK;
885 	switch (now) {
886 	case PCI_PMCSR_STATE_D0:
887 	case PCI_PMCSR_STATE_D1:
888 	case PCI_PMCSR_STATE_D2:
889 	case PCI_PMCSR_STATE_D3:
890 		*state = now;
891 		return 0;
892 	default:
893 		return EINVAL;
894 	}
895 }
896 
897 int
898 pci_get_powerstate(pci_chipset_tag_t pc, pcitag_t tag , pcireg_t *state)
899 {
900 	int offset;
901 	pcireg_t value;
902 
903 	if (!pci_get_capability(pc, tag, PCI_CAP_PWRMGMT, &offset, &value))
904 		return EOPNOTSUPP;
905 
906 	return pci_get_powerstate_int(pc, tag, state, offset);
907 }
908 
909 static int
910 pci_set_powerstate_int(pci_chipset_tag_t pc, pcitag_t tag, pcireg_t state,
911     int offset, pcireg_t cap_reg)
912 {
913 	pcireg_t value, cap, now;
914 
915 	cap = cap_reg >> PCI_PMCR_SHIFT;
916 	value = pci_conf_read(pc, tag, offset + PCI_PMCSR);
917 	now = value & PCI_PMCSR_STATE_MASK;
918 	value &= ~PCI_PMCSR_STATE_MASK;
919 
920 	if (now == state)
921 		return 0;
922 	switch (state) {
923 	case PCI_PMCSR_STATE_D0:
924 		break;
925 	case PCI_PMCSR_STATE_D1:
926 		if (now == PCI_PMCSR_STATE_D2 || now == PCI_PMCSR_STATE_D3) {
927 			printf("invalid transition from %d to D1\n", (int)now);
928 			return EINVAL;
929 		}
930 		if (!(cap & PCI_PMCR_D1SUPP)) {
931 			printf("D1 not supported\n");
932 			return EOPNOTSUPP;
933 		}
934 		break;
935 	case PCI_PMCSR_STATE_D2:
936 		if (now == PCI_PMCSR_STATE_D3) {
937 			printf("invalid transition from %d to D2\n", (int)now);
938 			return EINVAL;
939 		}
940 		if (!(cap & PCI_PMCR_D2SUPP)) {
941 			printf("D2 not supported\n");
942 			return EOPNOTSUPP;
943 		}
944 		break;
945 	case PCI_PMCSR_STATE_D3:
946 		break;
947 	default:
948 		return EINVAL;
949 	}
950 	value |= state;
951 	pci_conf_write(pc, tag, offset + PCI_PMCSR, value);
952 	/* delay according to pcipm1.2, ch. 5.6.1 */
953 	if (state == PCI_PMCSR_STATE_D3 || now == PCI_PMCSR_STATE_D3)
954 		DELAY(10000);
955 	else if (state == PCI_PMCSR_STATE_D2 || now == PCI_PMCSR_STATE_D2)
956 		DELAY(200);
957 
958 	return 0;
959 }
960 
961 int
962 pci_set_powerstate(pci_chipset_tag_t pc, pcitag_t tag, pcireg_t state)
963 {
964 	int offset;
965 	pcireg_t value;
966 
967 	if (!pci_get_capability(pc, tag, PCI_CAP_PWRMGMT, &offset, &value)) {
968 		printf("pci_set_powerstate not supported\n");
969 		return EOPNOTSUPP;
970 	}
971 
972 	return pci_set_powerstate_int(pc, tag, state, offset, value);
973 }
974 
975 int
976 pci_activate(pci_chipset_tag_t pc, pcitag_t tag, device_t dev,
977     int (*wakefun)(pci_chipset_tag_t, pcitag_t, device_t, pcireg_t))
978 {
979 	pcireg_t pmode;
980 	int error;
981 
982 	if ((error = pci_get_powerstate(pc, tag, &pmode)))
983 		return error;
984 
985 	switch (pmode) {
986 	case PCI_PMCSR_STATE_D0:
987 		break;
988 	case PCI_PMCSR_STATE_D3:
989 		if (wakefun == NULL) {
990 			/*
991 			 * The card has lost all configuration data in
992 			 * this state, so punt.
993 			 */
994 			aprint_error_dev(dev,
995 			    "unable to wake up from power state D3\n");
996 			return EOPNOTSUPP;
997 		}
998 		/*FALLTHROUGH*/
999 	default:
1000 		if (wakefun) {
1001 			error = (*wakefun)(pc, tag, dev, pmode);
1002 			if (error)
1003 				return error;
1004 		}
1005 		aprint_normal_dev(dev, "waking up from power state D%d\n",
1006 		    pmode);
1007 		if ((error = pci_set_powerstate(pc, tag, PCI_PMCSR_STATE_D0)))
1008 			return error;
1009 	}
1010 	return 0;
1011 }
1012 
1013 int
1014 pci_activate_null(pci_chipset_tag_t pc, pcitag_t tag,
1015     device_t dev, pcireg_t state)
1016 {
1017 	return 0;
1018 }
1019 
1020 struct pci_child_power {
1021 	struct pci_conf_state p_pciconf;
1022 	pci_chipset_tag_t p_pc;
1023 	pcitag_t p_tag;
1024 	bool p_has_pm;
1025 	int p_pm_offset;
1026 	pcireg_t p_pm_cap;
1027 	pcireg_t p_class;
1028 	pcireg_t p_csr;
1029 };
1030 
1031 static bool
1032 pci_child_suspend(device_t dv, const pmf_qual_t *qual)
1033 {
1034 	struct pci_child_power *priv = device_pmf_bus_private(dv);
1035 	pcireg_t ocsr, csr;
1036 
1037 	pci_conf_capture(priv->p_pc, priv->p_tag, &priv->p_pciconf);
1038 
1039 	if (!priv->p_has_pm)
1040 		return true; /* ??? hopefully handled by ACPI */
1041 	if (PCI_CLASS(priv->p_class) == PCI_CLASS_DISPLAY)
1042 		return true; /* XXX */
1043 
1044 	/* disable decoding and busmastering, see pcipm1.2 ch. 8.2.1 */
1045 	ocsr = pci_conf_read(priv->p_pc, priv->p_tag, PCI_COMMAND_STATUS_REG);
1046 	csr = ocsr & ~(PCI_COMMAND_IO_ENABLE | PCI_COMMAND_MEM_ENABLE
1047 		       | PCI_COMMAND_MASTER_ENABLE);
1048 	pci_conf_write(priv->p_pc, priv->p_tag, PCI_COMMAND_STATUS_REG, csr);
1049 	if (pci_set_powerstate_int(priv->p_pc, priv->p_tag,
1050 	    PCI_PMCSR_STATE_D3, priv->p_pm_offset, priv->p_pm_cap)) {
1051 		pci_conf_write(priv->p_pc, priv->p_tag,
1052 			       PCI_COMMAND_STATUS_REG, ocsr);
1053 		aprint_error_dev(dv, "unsupported state, continuing.\n");
1054 		return false;
1055 	}
1056 	return true;
1057 }
1058 
1059 static bool
1060 pci_child_resume(device_t dv, const pmf_qual_t *qual)
1061 {
1062 	struct pci_child_power *priv = device_pmf_bus_private(dv);
1063 
1064 	if (priv->p_has_pm &&
1065 	    pci_set_powerstate_int(priv->p_pc, priv->p_tag,
1066 	    PCI_PMCSR_STATE_D0, priv->p_pm_offset, priv->p_pm_cap)) {
1067 		aprint_error_dev(dv, "unsupported state, continuing.\n");
1068 		return false;
1069 	}
1070 
1071 	pci_conf_restore(priv->p_pc, priv->p_tag, &priv->p_pciconf);
1072 
1073 	return true;
1074 }
1075 
1076 static bool
1077 pci_child_shutdown(device_t dv, int how)
1078 {
1079 	struct pci_child_power *priv = device_pmf_bus_private(dv);
1080 	pcireg_t csr;
1081 
1082 	/* restore original bus-mastering state */
1083 	csr = pci_conf_read(priv->p_pc, priv->p_tag, PCI_COMMAND_STATUS_REG);
1084 	csr &= ~PCI_COMMAND_MASTER_ENABLE;
1085 	csr |= priv->p_csr & PCI_COMMAND_MASTER_ENABLE;
1086 	pci_conf_write(priv->p_pc, priv->p_tag, PCI_COMMAND_STATUS_REG, csr);
1087 	return true;
1088 }
1089 
1090 static void
1091 pci_child_deregister(device_t dv)
1092 {
1093 	struct pci_child_power *priv = device_pmf_bus_private(dv);
1094 
1095 	free(priv, M_DEVBUF);
1096 }
1097 
1098 static bool
1099 pci_child_register(device_t child)
1100 {
1101 	device_t self = device_parent(child);
1102 	struct pci_softc *sc = device_private(self);
1103 	struct pci_child_power *priv;
1104 	int device, function, off;
1105 	pcireg_t reg;
1106 
1107 	priv = malloc(sizeof(*priv), M_DEVBUF, M_WAITOK);
1108 
1109 	device = device_locator(child, PCICF_DEV);
1110 	function = device_locator(child, PCICF_FUNCTION);
1111 
1112 	priv->p_pc = sc->sc_pc;
1113 	priv->p_tag = pci_make_tag(priv->p_pc, sc->sc_bus, device,
1114 	    function);
1115 	priv->p_class = pci_conf_read(priv->p_pc, priv->p_tag, PCI_CLASS_REG);
1116 	priv->p_csr = pci_conf_read(priv->p_pc, priv->p_tag,
1117 	    PCI_COMMAND_STATUS_REG);
1118 
1119 	if (pci_get_capability(priv->p_pc, priv->p_tag,
1120 			       PCI_CAP_PWRMGMT, &off, &reg)) {
1121 		priv->p_has_pm = true;
1122 		priv->p_pm_offset = off;
1123 		priv->p_pm_cap = reg;
1124 	} else {
1125 		priv->p_has_pm = false;
1126 		priv->p_pm_offset = -1;
1127 	}
1128 
1129 	device_pmf_bus_register(child, priv, pci_child_suspend,
1130 	    pci_child_resume, pci_child_shutdown, pci_child_deregister);
1131 
1132 	return true;
1133 }
1134 
1135 MODULE(MODULE_CLASS_DRIVER, pci, NULL);
1136 
1137 static int
1138 pci_modcmd(modcmd_t cmd, void *priv)
1139 {
1140 	if (cmd == MODULE_CMD_INIT || cmd == MODULE_CMD_FINI)
1141 		return 0;
1142 	return ENOTTY;
1143 }
1144