xref: /netbsd-src/sys/dev/pci/pci.c (revision e6d6e05cb173f30287ab619b21120b27baa66ad6)
1 /*	$NetBSD: pci.c,v 1.113 2008/02/28 14:25:12 drochner 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.113 2008/02/28 14:25:12 drochner Exp $");
40 
41 #include "opt_pci.h"
42 
43 #include <sys/param.h>
44 #include <sys/malloc.h>
45 #include <sys/systm.h>
46 #include <sys/device.h>
47 
48 #include <dev/pci/pcireg.h>
49 #include <dev/pci/pcivar.h>
50 #include <dev/pci/pcidevs.h>
51 
52 #include <uvm/uvm_extern.h>
53 
54 #include <net/if.h>
55 
56 #include "locators.h"
57 
58 static bool pci_child_register(device_t);
59 
60 #ifdef PCI_CONFIG_DUMP
61 int pci_config_dump = 1;
62 #else
63 int pci_config_dump = 0;
64 #endif
65 
66 int	pciprint(void *, const char *);
67 
68 #ifdef PCI_MACHDEP_ENUMERATE_BUS
69 #define pci_enumerate_bus PCI_MACHDEP_ENUMERATE_BUS
70 #else
71 int pci_enumerate_bus(struct pci_softc *, const int *,
72     int (*)(struct pci_attach_args *), struct pci_attach_args *);
73 #endif
74 
75 /*
76  * Important note about PCI-ISA bridges:
77  *
78  * Callbacks are used to configure these devices so that ISA/EISA bridges
79  * can attach their child busses after PCI configuration is done.
80  *
81  * This works because:
82  *	(1) there can be at most one ISA/EISA bridge per PCI bus, and
83  *	(2) any ISA/EISA bridges must be attached to primary PCI
84  *	    busses (i.e. bus zero).
85  *
86  * That boils down to: there can only be one of these outstanding
87  * at a time, it is cleared when configuring PCI bus 0 before any
88  * subdevices have been found, and it is run after all subdevices
89  * of PCI bus 0 have been found.
90  *
91  * This is needed because there are some (legacy) PCI devices which
92  * can show up as ISA/EISA devices as well (the prime example of which
93  * are VGA controllers).  If you attach ISA from a PCI-ISA/EISA bridge,
94  * and the bridge is seen before the video board is, the board can show
95  * up as an ISA device, and that can (bogusly) complicate the PCI device's
96  * attach code, or make the PCI device not be properly attached at all.
97  *
98  * We use the generic config_defer() facility to achieve this.
99  */
100 
101 static int
102 pcirescan(struct device *sc, const char *ifattr, const int *locators)
103 {
104 
105 	KASSERT(ifattr && !strcmp(ifattr, "pci"));
106 	KASSERT(locators);
107 
108 	pci_enumerate_bus((struct pci_softc *)sc, locators, NULL, NULL);
109 	return (0);
110 }
111 
112 static int
113 pcimatch(struct device *parent, struct cfdata *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 static void
134 pciattach(struct device *parent, struct device *self, void *aux)
135 {
136 	struct pcibus_attach_args *pba = aux;
137 	struct pci_softc *sc = (struct pci_softc *)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 	pci_attach_hook(parent, self, pba);
145 
146 	aprint_naive("\n");
147 	aprint_normal("\n");
148 
149 	io_enabled = (pba->pba_flags & PCI_FLAGS_IO_ENABLED);
150 	mem_enabled = (pba->pba_flags & PCI_FLAGS_MEM_ENABLED);
151 	mrl_enabled = (pba->pba_flags & PCI_FLAGS_MRL_OKAY);
152 	mrm_enabled = (pba->pba_flags & PCI_FLAGS_MRM_OKAY);
153 	mwi_enabled = (pba->pba_flags & PCI_FLAGS_MWI_OKAY);
154 
155 	if (io_enabled == 0 && mem_enabled == 0) {
156 		aprint_error("%s: no spaces enabled!\n", self->dv_xname);
157 		goto fail;
158 	}
159 
160 #define	PRINT(str)							\
161 do {									\
162 	aprint_verbose("%s%s", sep, str);				\
163 	sep = ", ";							\
164 } while (/*CONSTCOND*/0)
165 
166 	aprint_verbose("%s: ", self->dv_xname);
167 
168 	if (io_enabled)
169 		PRINT("i/o space");
170 	if (mem_enabled)
171 		PRINT("memory space");
172 	aprint_verbose(" enabled");
173 
174 	if (mrl_enabled || mrm_enabled || mwi_enabled) {
175 		if (mrl_enabled)
176 			PRINT("rd/line");
177 		if (mrm_enabled)
178 			PRINT("rd/mult");
179 		if (mwi_enabled)
180 			PRINT("wr/inv");
181 		aprint_verbose(" ok");
182 	}
183 
184 	aprint_verbose("\n");
185 
186 #undef PRINT
187 
188 	sc->sc_iot = pba->pba_iot;
189 	sc->sc_memt = pba->pba_memt;
190 	sc->sc_dmat = pba->pba_dmat;
191 	sc->sc_dmat64 = pba->pba_dmat64;
192 	sc->sc_pc = pba->pba_pc;
193 	sc->sc_bus = pba->pba_bus;
194 	sc->sc_bridgetag = pba->pba_bridgetag;
195 	sc->sc_maxndevs = pci_bus_maxdevs(pba->pba_pc, pba->pba_bus);
196 	sc->sc_intrswiz = pba->pba_intrswiz;
197 	sc->sc_intrtag = pba->pba_intrtag;
198 	sc->sc_flags = pba->pba_flags;
199 
200 	device_pmf_driver_set_child_register(&sc->sc_dev, pci_child_register);
201 
202 	pcirescan(&sc->sc_dev, "pci", wildcard);
203 
204 fail:
205 	if (!pmf_device_register(self, NULL, NULL))
206 		aprint_error_dev(self, "couldn't establish power handler\n");
207 }
208 
209 static int
210 pcidetach(struct device *self, int flags)
211 {
212 	int rc;
213 
214 	if ((rc = config_detach_children(self, flags)) != 0)
215 		return rc;
216 	pmf_device_deregister(self);
217 	return 0;
218 }
219 
220 int
221 pciprint(void *aux, const char *pnp)
222 {
223 	struct pci_attach_args *pa = aux;
224 	char devinfo[256];
225 	const struct pci_quirkdata *qd;
226 
227 	if (pnp) {
228 		pci_devinfo(pa->pa_id, pa->pa_class, 1, devinfo, sizeof(devinfo));
229 		aprint_normal("%s at %s", devinfo, pnp);
230 	}
231 	aprint_normal(" dev %d function %d", pa->pa_device, pa->pa_function);
232 	if (pci_config_dump) {
233 		printf(": ");
234 		pci_conf_print(pa->pa_pc, pa->pa_tag, NULL);
235 		if (!pnp)
236 			pci_devinfo(pa->pa_id, pa->pa_class, 1, devinfo, sizeof(devinfo));
237 		printf("%s at %s", devinfo, pnp ? pnp : "?");
238 		printf(" dev %d function %d (", pa->pa_device, pa->pa_function);
239 #ifdef __i386__
240 		printf("tag %#lx, intrtag %#lx, intrswiz %#lx, intrpin %#lx",
241 		    *(long *)&pa->pa_tag, *(long *)&pa->pa_intrtag,
242 		    (long)pa->pa_intrswiz, (long)pa->pa_intrpin);
243 #else
244 		printf("intrswiz %#lx, intrpin %#lx",
245 		    (long)pa->pa_intrswiz, (long)pa->pa_intrpin);
246 #endif
247 		printf(", i/o %s, mem %s,",
248 		    pa->pa_flags & PCI_FLAGS_IO_ENABLED ? "on" : "off",
249 		    pa->pa_flags & PCI_FLAGS_MEM_ENABLED ? "on" : "off");
250 		qd = pci_lookup_quirkdata(PCI_VENDOR(pa->pa_id),
251 		    PCI_PRODUCT(pa->pa_id));
252 		if (qd == NULL) {
253 			printf(" no quirks");
254 		} else {
255 			bitmask_snprintf(qd->quirks,
256 			    "\002\001multifn\002singlefn\003skipfunc0"
257 			    "\004skipfunc1\005skipfunc2\006skipfunc3"
258 			    "\007skipfunc4\010skipfunc5\011skipfunc6"
259 			    "\012skipfunc7",
260 			    devinfo, sizeof (devinfo));
261 			printf(" quirks %s", devinfo);
262 		}
263 		printf(")");
264 	}
265 	return (UNCONF);
266 }
267 
268 int
269 pci_probe_device(struct pci_softc *sc, pcitag_t tag,
270     int (*match)(struct pci_attach_args *), struct pci_attach_args *pap)
271 {
272 	pci_chipset_tag_t pc = sc->sc_pc;
273 	struct pci_attach_args pa;
274 	pcireg_t id, csr, class, intr, bhlcr;
275 	int ret, pin, bus, device, function;
276 	int locs[PCICF_NLOCS];
277 	struct device *subdev;
278 
279 	pci_decompose_tag(pc, tag, &bus, &device, &function);
280 
281 	/* a driver already attached? */
282 	if (sc->PCI_SC_DEVICESC(device, function) && !match)
283 		return (0);
284 
285 	bhlcr = pci_conf_read(pc, tag, PCI_BHLC_REG);
286 	if (PCI_HDRTYPE_TYPE(bhlcr) > 2)
287 		return (0);
288 
289 	id = pci_conf_read(pc, tag, PCI_ID_REG);
290 	csr = pci_conf_read(pc, tag, PCI_COMMAND_STATUS_REG);
291 	class = pci_conf_read(pc, tag, PCI_CLASS_REG);
292 
293 	/* Invalid vendor ID value? */
294 	if (PCI_VENDOR(id) == PCI_VENDOR_INVALID)
295 		return (0);
296 	/* XXX Not invalid, but we've done this ~forever. */
297 	if (PCI_VENDOR(id) == 0)
298 		return (0);
299 
300 	pa.pa_iot = sc->sc_iot;
301 	pa.pa_memt = sc->sc_memt;
302 	pa.pa_dmat = sc->sc_dmat;
303 	pa.pa_dmat64 = sc->sc_dmat64;
304 	pa.pa_pc = pc;
305 	pa.pa_bus = bus;
306 	pa.pa_device = device;
307 	pa.pa_function = function;
308 	pa.pa_tag = tag;
309 	pa.pa_id = id;
310 	pa.pa_class = class;
311 
312 	/*
313 	 * Set up memory, I/O enable, and PCI command flags
314 	 * as appropriate.
315 	 */
316 	pa.pa_flags = sc->sc_flags;
317 	if ((csr & PCI_COMMAND_IO_ENABLE) == 0)
318 		pa.pa_flags &= ~PCI_FLAGS_IO_ENABLED;
319 	if ((csr & PCI_COMMAND_MEM_ENABLE) == 0)
320 		pa.pa_flags &= ~PCI_FLAGS_MEM_ENABLED;
321 
322 	/*
323 	 * If the cache line size is not configured, then
324 	 * clear the MRL/MRM/MWI command-ok flags.
325 	 */
326 	if (PCI_CACHELINE(bhlcr) == 0)
327 		pa.pa_flags &= ~(PCI_FLAGS_MRL_OKAY|
328 		    PCI_FLAGS_MRM_OKAY|PCI_FLAGS_MWI_OKAY);
329 
330 	if (sc->sc_bridgetag == NULL) {
331 		pa.pa_intrswiz = 0;
332 		pa.pa_intrtag = tag;
333 	} else {
334 		pa.pa_intrswiz = sc->sc_intrswiz + device;
335 		pa.pa_intrtag = sc->sc_intrtag;
336 	}
337 
338 	intr = pci_conf_read(pc, tag, PCI_INTERRUPT_REG);
339 
340 	pin = PCI_INTERRUPT_PIN(intr);
341 	pa.pa_rawintrpin = pin;
342 	if (pin == PCI_INTERRUPT_PIN_NONE) {
343 		/* no interrupt */
344 		pa.pa_intrpin = 0;
345 	} else {
346 		/*
347 		 * swizzle it based on the number of busses we're
348 		 * behind and our device number.
349 		 */
350 		pa.pa_intrpin = 	/* XXX */
351 		    ((pin + pa.pa_intrswiz - 1) % 4) + 1;
352 	}
353 	pa.pa_intrline = PCI_INTERRUPT_LINE(intr);
354 
355 	if (match != NULL) {
356 		ret = (*match)(&pa);
357 		if (ret != 0 && pap != NULL)
358 			*pap = pa;
359 	} else {
360 		locs[PCICF_DEV] = device;
361 		locs[PCICF_FUNCTION] = function;
362 
363 		subdev = config_found_sm_loc(&sc->sc_dev, "pci", locs, &pa,
364 					     pciprint, config_stdsubmatch);
365 		sc->PCI_SC_DEVICESC(device, function) = subdev;
366 		ret = (subdev != NULL);
367 	}
368 
369 	return (ret);
370 }
371 
372 static void
373 pcidevdetached(struct device *sc, struct device *dev)
374 {
375 	struct pci_softc *psc = (struct pci_softc *)sc;
376 	int d, f;
377 
378 	d = device_locator(dev, PCICF_DEV);
379 	f = device_locator(dev, PCICF_FUNCTION);
380 
381 	KASSERT(psc->PCI_SC_DEVICESC(d, f) == dev);
382 
383 	psc->PCI_SC_DEVICESC(d, f) = 0;
384 }
385 
386 CFATTACH_DECL2(pci, sizeof(struct pci_softc),
387     pcimatch, pciattach, pcidetach, NULL, pcirescan, pcidevdetached);
388 
389 int
390 pci_get_capability(pci_chipset_tag_t pc, pcitag_t tag, int capid,
391     int *offset, pcireg_t *value)
392 {
393 	pcireg_t reg;
394 	unsigned int ofs;
395 
396 	reg = pci_conf_read(pc, tag, PCI_COMMAND_STATUS_REG);
397 	if (!(reg & PCI_STATUS_CAPLIST_SUPPORT))
398 		return (0);
399 
400 	/* Determine the Capability List Pointer register to start with. */
401 	reg = pci_conf_read(pc, tag, PCI_BHLC_REG);
402 	switch (PCI_HDRTYPE_TYPE(reg)) {
403 	case 0:	/* standard device header */
404 	case 1: /* PCI-PCI bridge header */
405 		ofs = PCI_CAPLISTPTR_REG;
406 		break;
407 	case 2:	/* PCI-CardBus Bridge header */
408 		ofs = PCI_CARDBUS_CAPLISTPTR_REG;
409 		break;
410 	default:
411 		return (0);
412 	}
413 
414 	ofs = PCI_CAPLIST_PTR(pci_conf_read(pc, tag, ofs));
415 	while (ofs != 0) {
416 #ifdef DIAGNOSTIC
417 		if ((ofs & 3) || (ofs < 0x40))
418 			panic("pci_get_capability");
419 #endif
420 		reg = pci_conf_read(pc, tag, ofs);
421 		if (PCI_CAPLIST_CAP(reg) == capid) {
422 			if (offset)
423 				*offset = ofs;
424 			if (value)
425 				*value = reg;
426 			return (1);
427 		}
428 		ofs = PCI_CAPLIST_NEXT(reg);
429 	}
430 
431 	return (0);
432 }
433 
434 int
435 pci_find_device(struct pci_attach_args *pa,
436 		int (*match)(struct pci_attach_args *))
437 {
438 	extern struct cfdriver pci_cd;
439 	struct device *pcidev;
440 	int i;
441 	static const int wildcard[2] = {
442 		PCICF_DEV_DEFAULT,
443 		PCICF_FUNCTION_DEFAULT
444 	};
445 
446 	for (i = 0; i < pci_cd.cd_ndevs; i++) {
447 		pcidev = pci_cd.cd_devs[i];
448 		if (pcidev != NULL &&
449 		    pci_enumerate_bus((struct pci_softc *)pcidev, wildcard,
450 		    		      match, pa) != 0)
451 			return (1);
452 	}
453 	return (0);
454 }
455 
456 #ifndef PCI_MACHDEP_ENUMERATE_BUS
457 /*
458  * Generic PCI bus enumeration routine.  Used unless machine-dependent
459  * code needs to provide something else.
460  */
461 int
462 pci_enumerate_bus(struct pci_softc *sc, const int *locators,
463     int (*match)(struct pci_attach_args *), struct pci_attach_args *pap)
464 {
465 	pci_chipset_tag_t pc = sc->sc_pc;
466 	int device, function, nfunctions, ret;
467 	const struct pci_quirkdata *qd;
468 	pcireg_t id, bhlcr;
469 	pcitag_t tag;
470 #ifdef __PCI_BUS_DEVORDER
471 	char devs[32];
472 	int i;
473 #endif
474 
475 #ifdef __PCI_BUS_DEVORDER
476 	pci_bus_devorder(sc->sc_pc, sc->sc_bus, devs);
477 	for (i = 0; (device = devs[i]) < 32 && device >= 0; i++)
478 #else
479 	for (device = 0; device < sc->sc_maxndevs; device++)
480 #endif
481 	{
482 		if ((locators[PCICF_DEV] != PCICF_DEV_DEFAULT) &&
483 		    (locators[PCICF_DEV] != device))
484 			continue;
485 
486 		tag = pci_make_tag(pc, sc->sc_bus, device, 0);
487 
488 		bhlcr = pci_conf_read(pc, tag, PCI_BHLC_REG);
489 		if (PCI_HDRTYPE_TYPE(bhlcr) > 2)
490 			continue;
491 
492 		id = pci_conf_read(pc, tag, PCI_ID_REG);
493 
494 		/* Invalid vendor ID value? */
495 		if (PCI_VENDOR(id) == PCI_VENDOR_INVALID)
496 			continue;
497 		/* XXX Not invalid, but we've done this ~forever. */
498 		if (PCI_VENDOR(id) == 0)
499 			continue;
500 
501 		qd = pci_lookup_quirkdata(PCI_VENDOR(id), PCI_PRODUCT(id));
502 
503 		if (qd != NULL &&
504 		      (qd->quirks & PCI_QUIRK_MULTIFUNCTION) != 0)
505 			nfunctions = 8;
506 		else if (qd != NULL &&
507 		      (qd->quirks & PCI_QUIRK_MONOFUNCTION) != 0)
508 			nfunctions = 1;
509 		else
510 			nfunctions = PCI_HDRTYPE_MULTIFN(bhlcr) ? 8 : 1;
511 
512 		for (function = 0; function < nfunctions; function++) {
513 			if ((locators[PCICF_FUNCTION] != PCICF_FUNCTION_DEFAULT)
514 			    && (locators[PCICF_FUNCTION] != function))
515 				continue;
516 
517 			if (qd != NULL &&
518 			    (qd->quirks & PCI_QUIRK_SKIP_FUNC(function)) != 0)
519 				continue;
520 			tag = pci_make_tag(pc, sc->sc_bus, device, function);
521 			ret = pci_probe_device(sc, tag, match, pap);
522 			if (match != NULL && ret != 0)
523 				return (ret);
524 		}
525 	}
526 	return (0);
527 }
528 #endif /* PCI_MACHDEP_ENUMERATE_BUS */
529 
530 
531 /*
532  * Vital Product Data (PCI 2.2)
533  */
534 
535 int
536 pci_vpd_read(pci_chipset_tag_t pc, pcitag_t tag, int offset, int count,
537     pcireg_t *data)
538 {
539 	uint32_t reg;
540 	int ofs, i, j;
541 
542 	KASSERT(data != NULL);
543 	KASSERT((offset + count) < 0x7fff);
544 
545 	if (pci_get_capability(pc, tag, PCI_CAP_VPD, &ofs, &reg) == 0)
546 		return (1);
547 
548 	for (i = 0; i < count; offset += sizeof(*data), i++) {
549 		reg &= 0x0000ffff;
550 		reg &= ~PCI_VPD_OPFLAG;
551 		reg |= PCI_VPD_ADDRESS(offset);
552 		pci_conf_write(pc, tag, ofs, reg);
553 
554 		/*
555 		 * PCI 2.2 does not specify how long we should poll
556 		 * for completion nor whether the operation can fail.
557 		 */
558 		j = 0;
559 		do {
560 			if (j++ == 20)
561 				return (1);
562 			delay(4);
563 			reg = pci_conf_read(pc, tag, ofs);
564 		} while ((reg & PCI_VPD_OPFLAG) == 0);
565 		data[i] = pci_conf_read(pc, tag, PCI_VPD_DATAREG(ofs));
566 	}
567 
568 	return (0);
569 }
570 
571 int
572 pci_vpd_write(pci_chipset_tag_t pc, pcitag_t tag, int offset, int count,
573     pcireg_t *data)
574 {
575 	pcireg_t reg;
576 	int ofs, i, j;
577 
578 	KASSERT(data != NULL);
579 	KASSERT((offset + count) < 0x7fff);
580 
581 	if (pci_get_capability(pc, tag, PCI_CAP_VPD, &ofs, &reg) == 0)
582 		return (1);
583 
584 	for (i = 0; i < count; offset += sizeof(*data), i++) {
585 		pci_conf_write(pc, tag, PCI_VPD_DATAREG(ofs), data[i]);
586 
587 		reg &= 0x0000ffff;
588 		reg |= PCI_VPD_OPFLAG;
589 		reg |= PCI_VPD_ADDRESS(offset);
590 		pci_conf_write(pc, tag, ofs, reg);
591 
592 		/*
593 		 * PCI 2.2 does not specify how long we should poll
594 		 * for completion nor whether the operation can fail.
595 		 */
596 		j = 0;
597 		do {
598 			if (j++ == 20)
599 				return (1);
600 			delay(1);
601 			reg = pci_conf_read(pc, tag, ofs);
602 		} while (reg & PCI_VPD_OPFLAG);
603 	}
604 
605 	return (0);
606 }
607 
608 int
609 pci_dma64_available(struct pci_attach_args *pa)
610 {
611 #ifdef _PCI_HAVE_DMA64
612 	if (BUS_DMA_TAG_VALID(pa->pa_dmat64) &&
613 		((uint64_t)physmem << PAGE_SHIFT) > 0xffffffffULL)
614                         return 1;
615 #endif
616         return 0;
617 }
618 
619 void
620 pci_conf_capture(pci_chipset_tag_t pc, pcitag_t tag,
621 		  struct pci_conf_state *pcs)
622 {
623 	int off;
624 
625 	for (off = 0; off < 16; off++)
626 		pcs->reg[off] = pci_conf_read(pc, tag, (off * 4));
627 
628 	return;
629 }
630 
631 void
632 pci_conf_restore(pci_chipset_tag_t pc, pcitag_t tag,
633 		  struct pci_conf_state *pcs)
634 {
635 	int off;
636 	pcireg_t val;
637 
638 	for (off = 15; off >= 0; off--) {
639 		val = pci_conf_read(pc, tag, (off * 4));
640 		if (val != pcs->reg[off])
641 			pci_conf_write(pc, tag, (off * 4), pcs->reg[off]);
642 	}
643 
644 	return;
645 }
646 
647 /*
648  * Power Management Capability (Rev 2.2)
649  */
650 static int
651 pci_get_powerstate_int(pci_chipset_tag_t pc, pcitag_t tag , pcireg_t *state,
652     int offset)
653 {
654 	pcireg_t value, now;
655 
656 	value = pci_conf_read(pc, tag, offset + PCI_PMCSR);
657 	now = value & PCI_PMCSR_STATE_MASK;
658 	switch (now) {
659 	case PCI_PMCSR_STATE_D0:
660 	case PCI_PMCSR_STATE_D1:
661 	case PCI_PMCSR_STATE_D2:
662 	case PCI_PMCSR_STATE_D3:
663 		*state = now;
664 		return 0;
665 	default:
666 		return EINVAL;
667 	}
668 }
669 
670 int
671 pci_get_powerstate(pci_chipset_tag_t pc, pcitag_t tag , pcireg_t *state)
672 {
673 	int offset;
674 	pcireg_t value;
675 
676 	if (!pci_get_capability(pc, tag, PCI_CAP_PWRMGMT, &offset, &value))
677 		return EOPNOTSUPP;
678 
679 	return pci_get_powerstate_int(pc, tag, state, offset);
680 }
681 
682 static int
683 pci_set_powerstate_int(pci_chipset_tag_t pc, pcitag_t tag, pcireg_t state,
684     int offset, pcireg_t cap_reg)
685 {
686 	pcireg_t value, cap, now;
687 
688 	cap = cap_reg >> PCI_PMCR_SHIFT;
689 	value = pci_conf_read(pc, tag, offset + PCI_PMCSR);
690 	now = value & PCI_PMCSR_STATE_MASK;
691 	value &= ~PCI_PMCSR_STATE_MASK;
692 
693 	if (now == state)
694 		return 0;
695 	switch (state) {
696 	case PCI_PMCSR_STATE_D0:
697 		break;
698 	case PCI_PMCSR_STATE_D1:
699 		if (now == PCI_PMCSR_STATE_D2 || now == PCI_PMCSR_STATE_D3) {
700 			printf("invalid transition from %d to D1\n", (int)now);
701 			return EINVAL;
702 		}
703 		if (!(cap & PCI_PMCR_D1SUPP)) {
704 			printf("D1 not supported\n");
705 			return EOPNOTSUPP;
706 		}
707 		break;
708 	case PCI_PMCSR_STATE_D2:
709 		if (now == PCI_PMCSR_STATE_D3) {
710 			printf("invalid transition from %d to D2\n", (int)now);
711 			return EINVAL;
712 		}
713 		if (!(cap & PCI_PMCR_D2SUPP)) {
714 			printf("D2 not supported\n");
715 			return EOPNOTSUPP;
716 		}
717 		break;
718 	case PCI_PMCSR_STATE_D3:
719 		break;
720 	default:
721 		return EINVAL;
722 	}
723 	value |= state;
724 	pci_conf_write(pc, tag, offset + PCI_PMCSR, value);
725 	/* delay according to pcipm1.2, ch. 5.6.1 */
726 	if (state == PCI_PMCSR_STATE_D3 || now == PCI_PMCSR_STATE_D3)
727 		DELAY(10000);
728 	else if (state == PCI_PMCSR_STATE_D2 || now == PCI_PMCSR_STATE_D2)
729 		DELAY(200);
730 
731 	return 0;
732 }
733 
734 int
735 pci_set_powerstate(pci_chipset_tag_t pc, pcitag_t tag, pcireg_t state)
736 {
737 	int offset;
738 	pcireg_t value;
739 
740 	if (!pci_get_capability(pc, tag, PCI_CAP_PWRMGMT, &offset, &value)) {
741 		printf("pci_set_powerstate not supported\n");
742 		return EOPNOTSUPP;
743 	}
744 
745 	return pci_set_powerstate_int(pc, tag, state, offset, value);
746 }
747 
748 int
749 pci_activate(pci_chipset_tag_t pc, pcitag_t tag, void *sc,
750     int (*wakefun)(pci_chipset_tag_t, pcitag_t, void *, pcireg_t))
751 {
752 	struct device *dv = sc;
753 	pcireg_t pmode;
754 	int error;
755 
756 	if ((error = pci_get_powerstate(pc, tag, &pmode)))
757 		return error;
758 
759 	switch (pmode) {
760 	case PCI_PMCSR_STATE_D0:
761 		break;
762 	case PCI_PMCSR_STATE_D3:
763 		if (wakefun == NULL) {
764 			/*
765 			 * The card has lost all configuration data in
766 			 * this state, so punt.
767 			 */
768 			aprint_error(
769 			    "%s: unable to wake up from power state D3\n",
770 			    dv->dv_xname);
771 			return EOPNOTSUPP;
772 		}
773 		/*FALLTHROUGH*/
774 	default:
775 		if (wakefun) {
776 			error = (*wakefun)(pc, tag, sc, pmode);
777 			if (error)
778 				return error;
779 		}
780 		aprint_normal("%s: waking up from power state D%d\n",
781 		    dv->dv_xname, pmode);
782 		if ((error = pci_set_powerstate(pc, tag, PCI_PMCSR_STATE_D0)))
783 			return error;
784 	}
785 	return 0;
786 }
787 
788 int
789 pci_activate_null(pci_chipset_tag_t pc, pcitag_t tag,
790     void *sc, pcireg_t state)
791 {
792 	return 0;
793 }
794 
795 /* I have disabled this code for now. --dyoung
796  *
797  * Insofar as I understand what the PCI retry timeout is [1],
798  * I see no justification for any driver to disable when it
799  * attaches/resumes a device.
800  *
801  * A PCI bus bridge may tell a bus master to retry its transaction
802  * at a later time if the resources to complete the transaction
803  * are not immediately available.  Taking a guess, PCI bus masters
804  * that implement a PCI retry timeout register count down from the
805  * retry timeout to 0 while it retries a delayed PCI transaction.
806  * When it reaches 0, it stops retrying.  A PCI master is *never*
807  * supposed to stop retrying a delayed transaction, though.
808  *
809  * Incidentally, I initially suspected that writing 0 to the register
810  * would not disable *retries*, but would disable the timeout.
811  * That is, any device whose retry timeout was set to 0 would
812  * *never* timeout.  However, I found out, by using PCI debug
813  * facilities on the AMD Elan SC520, that if I write 0 to the retry
814  * timeout register on an ath(4) MiniPCI card, the card really does
815  * not retry transactions.
816  *
817  * Some uses of this register have mentioned "interference" with
818  * a CPU's "C3 sleep state."  It seems to me that if a bus master
819  * is properly put to sleep, it will neither initiate new transactions,
820  * nor retry delayed transactions, so disabling retries should not
821  * be necessary.
822  *
823  * [1] The timeout does not appear to be documented in any PCI
824  * standard, and we have no documentation of it for the devices by
825  * Atheros, and others, that supposedly implement it.
826  */
827 void
828 pci_disable_retry(pci_chipset_tag_t pc, pcitag_t tag)
829 {
830 #if 0
831 	pcireg_t retry;
832 
833 	/*
834 	 * Disable retry timeout to keep PCI Tx retries from
835 	 * interfering with ACPI C3 CPU state.
836 	 */
837 	retry = pci_conf_read(pc, tag, PCI_RETRY_TIMEOUT_REG);
838 	retry &= ~PCI_RETRY_TIMEOUT_REG_MASK;
839 	pci_conf_write(pc, tag, PCI_RETRY_TIMEOUT_REG, retry);
840 #endif
841 }
842 
843 struct pci_child_power {
844 	struct pci_conf_state p_pciconf;
845 	pci_chipset_tag_t p_pc;
846 	pcitag_t p_tag;
847 	bool p_has_pm;
848 	int p_pm_offset;
849 	pcireg_t p_pm_cap;
850 	pcireg_t p_class;
851 };
852 
853 static bool
854 pci_child_suspend(device_t dv PMF_FN_ARGS)
855 {
856 	struct pci_child_power *priv = device_pmf_bus_private(dv);
857 	pcireg_t ocsr, csr;
858 
859 	pci_conf_capture(priv->p_pc, priv->p_tag, &priv->p_pciconf);
860 
861 	if (!priv->p_has_pm)
862 		return true; /* ??? hopefully handled by ACPI */
863 	if (PCI_CLASS(priv->p_class) == PCI_CLASS_DISPLAY)
864 		return true; /* XXX */
865 
866 	/* disable decoding and busmastering, see pcipm1.2 ch. 8.2.1 */
867 	ocsr = pci_conf_read(priv->p_pc, priv->p_tag, PCI_COMMAND_STATUS_REG);
868 	csr = ocsr & ~(PCI_COMMAND_IO_ENABLE | PCI_COMMAND_MEM_ENABLE
869 		       | PCI_COMMAND_MASTER_ENABLE);
870 	pci_conf_write(priv->p_pc, priv->p_tag, PCI_COMMAND_STATUS_REG, csr);
871 	if (pci_set_powerstate_int(priv->p_pc, priv->p_tag,
872 	    PCI_PMCSR_STATE_D3, priv->p_pm_offset, priv->p_pm_cap)) {
873 		pci_conf_write(priv->p_pc, priv->p_tag,
874 			       PCI_COMMAND_STATUS_REG, ocsr);
875 		aprint_error_dev(dv, "unsupported state, continuing.\n");
876 		return false;
877 	}
878 	return true;
879 }
880 
881 static bool
882 pci_child_resume(device_t dv PMF_FN_ARGS)
883 {
884 	struct pci_child_power *priv = device_pmf_bus_private(dv);
885 
886 	if (priv->p_has_pm &&
887 	    pci_set_powerstate_int(priv->p_pc, priv->p_tag,
888 	    PCI_PMCSR_STATE_D0, priv->p_pm_offset, priv->p_pm_cap)) {
889 		aprint_error_dev(dv, "unsupported state, continuing.\n");
890 		return false;
891 	}
892 
893 	pci_conf_restore(priv->p_pc, priv->p_tag, &priv->p_pciconf);
894 
895 	return true;
896 }
897 
898 static bool
899 pci_child_shutdown(device_t dv, int how)
900 {
901 	struct pci_child_power *priv = device_pmf_bus_private(dv);
902 	pcireg_t csr;
903 
904 	/* disable busmastering */
905 	csr = pci_conf_read(priv->p_pc, priv->p_tag, PCI_COMMAND_STATUS_REG);
906 	csr &= ~PCI_COMMAND_MASTER_ENABLE;
907 	pci_conf_write(priv->p_pc, priv->p_tag, PCI_COMMAND_STATUS_REG, csr);
908 	return true;
909 }
910 
911 static void
912 pci_child_deregister(device_t dv)
913 {
914 	struct pci_child_power *priv = device_pmf_bus_private(dv);
915 
916 	free(priv, M_DEVBUF);
917 }
918 
919 static bool
920 pci_child_register(device_t child)
921 {
922 	device_t self = device_parent(child);
923 	struct pci_softc *sc = device_private(self);
924 	struct pci_child_power *priv;
925 	int device, function, off;
926 	pcireg_t reg;
927 
928 	priv = malloc(sizeof(*priv), M_DEVBUF, M_WAITOK);
929 
930 	device = device_locator(child, PCICF_DEV);
931 	function = device_locator(child, PCICF_FUNCTION);
932 
933 	priv->p_pc = sc->sc_pc;
934 	priv->p_tag = pci_make_tag(priv->p_pc, sc->sc_bus, device,
935 	    function);
936 	priv->p_class = pci_conf_read(priv->p_pc, priv->p_tag, PCI_CLASS_REG);
937 
938 	if (pci_get_capability(priv->p_pc, priv->p_tag,
939 			       PCI_CAP_PWRMGMT, &off, &reg)) {
940 		priv->p_has_pm = true;
941 		priv->p_pm_offset = off;
942 		priv->p_pm_cap = reg;
943 	} else {
944 		priv->p_has_pm = false;
945 		priv->p_pm_offset = -1;
946 	}
947 
948 	device_pmf_bus_register(child, priv, pci_child_suspend,
949 	    pci_child_resume, pci_child_shutdown, pci_child_deregister);
950 
951 	return true;
952 }
953