pci.c revision 138306
1/*
2 * Copyright (c) 1997, Stefan Esser <se@freebsd.org>
3 * Copyright (c) 2000, Michael Smith <msmith@freebsd.org>
4 * Copyright (c) 2000, BSDi
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice unmodified, this list of conditions, and the following
12 *    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 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/sys/dev/pci/pci.c 138306 2004-12-02 08:07:12Z njl $");
31
32#include "opt_bus.h"
33
34#include <sys/param.h>
35#include <sys/systm.h>
36#include <sys/malloc.h>
37#include <sys/module.h>
38#include <sys/linker.h>
39#include <sys/fcntl.h>
40#include <sys/conf.h>
41#include <sys/kernel.h>
42#include <sys/queue.h>
43#include <sys/sysctl.h>
44#include <sys/types.h>
45
46#include <vm/vm.h>
47#include <vm/pmap.h>
48#include <vm/vm_extern.h>
49
50#include <sys/bus.h>
51#include <machine/bus.h>
52#include <sys/rman.h>
53#include <machine/resource.h>
54
55#include <sys/pciio.h>
56#include <dev/pci/pcireg.h>
57#include <dev/pci/pcivar.h>
58#include <dev/pci/pci_private.h>
59
60#include "pcib_if.h"
61#include "pci_if.h"
62
63#include <contrib/dev/acpica/acpi.h>
64#include <dev/acpica/acpivar.h>
65#include "acpi_if.h"
66
67static uint32_t		pci_mapbase(unsigned mapreg);
68static int		pci_maptype(unsigned mapreg);
69static int		pci_mapsize(unsigned testval);
70static int		pci_maprange(unsigned mapreg);
71static void		pci_fixancient(pcicfgregs *cfg);
72
73static int		pci_porten(device_t pcib, int b, int s, int f);
74static int		pci_memen(device_t pcib, int b, int s, int f);
75static int		pci_add_map(device_t pcib, device_t bus, device_t dev,
76			    int b, int s, int f, int reg,
77			    struct resource_list *rl);
78static void		pci_add_resources(device_t pcib, device_t bus,
79			    device_t dev);
80static int		pci_probe(device_t dev);
81static int		pci_attach(device_t dev);
82static void		pci_load_vendor_data(void);
83static int		pci_describe_parse_line(char **ptr, int *vendor,
84			    int *device, char **desc);
85static char		*pci_describe_device(device_t dev);
86static int		pci_modevent(module_t mod, int what, void *arg);
87static void		pci_hdrtypedata(device_t pcib, int b, int s, int f,
88			    pcicfgregs *cfg);
89static void		pci_read_extcap(device_t pcib, pcicfgregs *cfg);
90static void		pci_cfg_restore(device_t, struct pci_devinfo *);
91static void		pci_cfg_save(device_t, struct pci_devinfo *, int);
92
93static device_method_t pci_methods[] = {
94	/* Device interface */
95	DEVMETHOD(device_probe,		pci_probe),
96	DEVMETHOD(device_attach,	pci_attach),
97	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
98	DEVMETHOD(device_suspend,	pci_suspend),
99	DEVMETHOD(device_resume,	pci_resume),
100
101	/* Bus interface */
102	DEVMETHOD(bus_print_child,	pci_print_child),
103	DEVMETHOD(bus_probe_nomatch,	pci_probe_nomatch),
104	DEVMETHOD(bus_read_ivar,	pci_read_ivar),
105	DEVMETHOD(bus_write_ivar,	pci_write_ivar),
106	DEVMETHOD(bus_driver_added,	pci_driver_added),
107	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
108	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
109
110	DEVMETHOD(bus_get_resource_list,pci_get_resource_list),
111	DEVMETHOD(bus_set_resource,	bus_generic_rl_set_resource),
112	DEVMETHOD(bus_get_resource,	bus_generic_rl_get_resource),
113	DEVMETHOD(bus_delete_resource,	pci_delete_resource),
114	DEVMETHOD(bus_alloc_resource,	pci_alloc_resource),
115	DEVMETHOD(bus_release_resource,	bus_generic_rl_release_resource),
116	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
117	DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
118	DEVMETHOD(bus_child_pnpinfo_str, pci_child_pnpinfo_str_method),
119	DEVMETHOD(bus_child_location_str, pci_child_location_str_method),
120
121	/* PCI interface */
122	DEVMETHOD(pci_read_config,	pci_read_config_method),
123	DEVMETHOD(pci_write_config,	pci_write_config_method),
124	DEVMETHOD(pci_enable_busmaster,	pci_enable_busmaster_method),
125	DEVMETHOD(pci_disable_busmaster, pci_disable_busmaster_method),
126	DEVMETHOD(pci_enable_io,	pci_enable_io_method),
127	DEVMETHOD(pci_disable_io,	pci_disable_io_method),
128	DEVMETHOD(pci_get_powerstate,	pci_get_powerstate_method),
129	DEVMETHOD(pci_set_powerstate,	pci_set_powerstate_method),
130	DEVMETHOD(pci_assign_interrupt,	pci_assign_interrupt_method),
131
132	{ 0, 0 }
133};
134
135DEFINE_CLASS_0(pci, pci_driver, pci_methods, 0);
136
137devclass_t	pci_devclass;
138DRIVER_MODULE(pci, pcib, pci_driver, pci_devclass, pci_modevent, 0);
139MODULE_VERSION(pci, 1);
140
141static char	*pci_vendordata;
142static size_t	pci_vendordata_size;
143
144
145struct pci_quirk {
146	uint32_t devid;	/* Vendor/device of the card */
147	int	type;
148#define PCI_QUIRK_MAP_REG	1 /* PCI map register in weird place */
149	int	arg1;
150	int	arg2;
151};
152
153struct pci_quirk pci_quirks[] = {
154	/* The Intel 82371AB and 82443MX has a map register at offset 0x90. */
155	{ 0x71138086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
156	{ 0x719b8086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
157	/* As does the Serverworks OSB4 (the SMBus mapping register) */
158	{ 0x02001166, PCI_QUIRK_MAP_REG,	0x90,	 0 },
159
160	{ 0 }
161};
162
163/* map register information */
164#define PCI_MAPMEM	0x01	/* memory map */
165#define PCI_MAPMEMP	0x02	/* prefetchable memory map */
166#define PCI_MAPPORT	0x04	/* port map */
167
168struct devlist pci_devq;
169uint32_t pci_generation;
170uint32_t pci_numdevs = 0;
171
172/* sysctl vars */
173SYSCTL_NODE(_hw, OID_AUTO, pci, CTLFLAG_RD, 0, "PCI bus tuning parameters");
174
175static int pci_enable_io_modes = 1;
176TUNABLE_INT("hw.pci.enable_io_modes", &pci_enable_io_modes);
177SYSCTL_INT(_hw_pci, OID_AUTO, enable_io_modes, CTLFLAG_RW,
178    &pci_enable_io_modes, 1,
179    "Enable I/O and memory bits in the config register.  Some BIOSes do not\n\
180enable these bits correctly.  We'd like to do this all the time, but there\n\
181are some peripherals that this causes problems with.");
182
183static int pci_do_powerstate = 1;
184TUNABLE_INT("hw.pci.do_powerstate", &pci_do_powerstate);
185SYSCTL_INT(_hw_pci, OID_AUTO, do_powerstate, CTLFLAG_RW,
186    &pci_do_powerstate, 1,
187    "Power down devices into D3 state when no driver attaches to them.\n\
188Otherwise, leave the device in D0 state when no driver attaches.");
189
190/* Find a device_t by bus/slot/function */
191
192device_t
193pci_find_bsf(uint8_t bus, uint8_t slot, uint8_t func)
194{
195	struct pci_devinfo *dinfo;
196
197	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
198		if ((dinfo->cfg.bus == bus) &&
199		    (dinfo->cfg.slot == slot) &&
200		    (dinfo->cfg.func == func)) {
201			return (dinfo->cfg.dev);
202		}
203	}
204
205	return (NULL);
206}
207
208/* Find a device_t by vendor/device ID */
209
210device_t
211pci_find_device(uint16_t vendor, uint16_t device)
212{
213	struct pci_devinfo *dinfo;
214
215	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
216		if ((dinfo->cfg.vendor == vendor) &&
217		    (dinfo->cfg.device == device)) {
218			return (dinfo->cfg.dev);
219		}
220	}
221
222	return (NULL);
223}
224
225/* return base address of memory or port map */
226
227static uint32_t
228pci_mapbase(unsigned mapreg)
229{
230	int mask = 0x03;
231	if ((mapreg & 0x01) == 0)
232		mask = 0x0f;
233	return (mapreg & ~mask);
234}
235
236/* return map type of memory or port map */
237
238static int
239pci_maptype(unsigned mapreg)
240{
241	static uint8_t maptype[0x10] = {
242		PCI_MAPMEM,		PCI_MAPPORT,
243		PCI_MAPMEM,		0,
244		PCI_MAPMEM,		PCI_MAPPORT,
245		0,			0,
246		PCI_MAPMEM|PCI_MAPMEMP,	PCI_MAPPORT,
247		PCI_MAPMEM|PCI_MAPMEMP, 0,
248		PCI_MAPMEM|PCI_MAPMEMP,	PCI_MAPPORT,
249		0,			0,
250	};
251
252	return maptype[mapreg & 0x0f];
253}
254
255/* return log2 of map size decoded for memory or port map */
256
257static int
258pci_mapsize(unsigned testval)
259{
260	int ln2size;
261
262	testval = pci_mapbase(testval);
263	ln2size = 0;
264	if (testval != 0) {
265		while ((testval & 1) == 0)
266		{
267			ln2size++;
268			testval >>= 1;
269		}
270	}
271	return (ln2size);
272}
273
274/* return log2 of address range supported by map register */
275
276static int
277pci_maprange(unsigned mapreg)
278{
279	int ln2range = 0;
280	switch (mapreg & 0x07) {
281	case 0x00:
282	case 0x01:
283	case 0x05:
284		ln2range = 32;
285		break;
286	case 0x02:
287		ln2range = 20;
288		break;
289	case 0x04:
290		ln2range = 64;
291		break;
292	}
293	return (ln2range);
294}
295
296/* adjust some values from PCI 1.0 devices to match 2.0 standards ... */
297
298static void
299pci_fixancient(pcicfgregs *cfg)
300{
301	if (cfg->hdrtype != 0)
302		return;
303
304	/* PCI to PCI bridges use header type 1 */
305	if (cfg->baseclass == PCIC_BRIDGE && cfg->subclass == PCIS_BRIDGE_PCI)
306		cfg->hdrtype = 1;
307}
308
309/* extract header type specific config data */
310
311static void
312pci_hdrtypedata(device_t pcib, int b, int s, int f, pcicfgregs *cfg)
313{
314#define REG(n, w)	PCIB_READ_CONFIG(pcib, b, s, f, n, w)
315	switch (cfg->hdrtype) {
316	case 0:
317		cfg->subvendor      = REG(PCIR_SUBVEND_0, 2);
318		cfg->subdevice      = REG(PCIR_SUBDEV_0, 2);
319		cfg->nummaps	    = PCI_MAXMAPS_0;
320		break;
321	case 1:
322		cfg->subvendor      = REG(PCIR_SUBVEND_1, 2);
323		cfg->subdevice      = REG(PCIR_SUBDEV_1, 2);
324		cfg->nummaps	    = PCI_MAXMAPS_1;
325		break;
326	case 2:
327		cfg->subvendor      = REG(PCIR_SUBVEND_2, 2);
328		cfg->subdevice      = REG(PCIR_SUBDEV_2, 2);
329		cfg->nummaps	    = PCI_MAXMAPS_2;
330		break;
331	}
332#undef REG
333}
334
335/* read configuration header into pcicfgregs structure */
336
337struct pci_devinfo *
338pci_read_device(device_t pcib, int b, int s, int f, size_t size)
339{
340#define REG(n, w)	PCIB_READ_CONFIG(pcib, b, s, f, n, w)
341	pcicfgregs *cfg = NULL;
342	struct pci_devinfo *devlist_entry;
343	struct devlist *devlist_head;
344
345	devlist_head = &pci_devq;
346
347	devlist_entry = NULL;
348
349	if (REG(PCIR_DEVVENDOR, 4) != -1) {
350		devlist_entry = malloc(size, M_DEVBUF, M_WAITOK | M_ZERO);
351		if (devlist_entry == NULL)
352			return (NULL);
353
354		cfg = &devlist_entry->cfg;
355
356		cfg->bus		= b;
357		cfg->slot		= s;
358		cfg->func		= f;
359		cfg->vendor		= REG(PCIR_VENDOR, 2);
360		cfg->device		= REG(PCIR_DEVICE, 2);
361		cfg->cmdreg		= REG(PCIR_COMMAND, 2);
362		cfg->statreg		= REG(PCIR_STATUS, 2);
363		cfg->baseclass		= REG(PCIR_CLASS, 1);
364		cfg->subclass		= REG(PCIR_SUBCLASS, 1);
365		cfg->progif		= REG(PCIR_PROGIF, 1);
366		cfg->revid		= REG(PCIR_REVID, 1);
367		cfg->hdrtype		= REG(PCIR_HDRTYPE, 1);
368		cfg->cachelnsz		= REG(PCIR_CACHELNSZ, 1);
369		cfg->lattimer		= REG(PCIR_LATTIMER, 1);
370		cfg->intpin		= REG(PCIR_INTPIN, 1);
371		cfg->intline		= REG(PCIR_INTLINE, 1);
372
373		cfg->mingnt		= REG(PCIR_MINGNT, 1);
374		cfg->maxlat		= REG(PCIR_MAXLAT, 1);
375
376		cfg->mfdev		= (cfg->hdrtype & PCIM_MFDEV) != 0;
377		cfg->hdrtype		&= ~PCIM_MFDEV;
378
379		pci_fixancient(cfg);
380		pci_hdrtypedata(pcib, b, s, f, cfg);
381
382		if (REG(PCIR_STATUS, 2) & PCIM_STATUS_CAPPRESENT)
383			pci_read_extcap(pcib, cfg);
384
385		STAILQ_INSERT_TAIL(devlist_head, devlist_entry, pci_links);
386
387		devlist_entry->conf.pc_sel.pc_bus = cfg->bus;
388		devlist_entry->conf.pc_sel.pc_dev = cfg->slot;
389		devlist_entry->conf.pc_sel.pc_func = cfg->func;
390		devlist_entry->conf.pc_hdr = cfg->hdrtype;
391
392		devlist_entry->conf.pc_subvendor = cfg->subvendor;
393		devlist_entry->conf.pc_subdevice = cfg->subdevice;
394		devlist_entry->conf.pc_vendor = cfg->vendor;
395		devlist_entry->conf.pc_device = cfg->device;
396
397		devlist_entry->conf.pc_class = cfg->baseclass;
398		devlist_entry->conf.pc_subclass = cfg->subclass;
399		devlist_entry->conf.pc_progif = cfg->progif;
400		devlist_entry->conf.pc_revid = cfg->revid;
401
402		pci_numdevs++;
403		pci_generation++;
404	}
405	return (devlist_entry);
406#undef REG
407}
408
409static void
410pci_read_extcap(device_t pcib, pcicfgregs *cfg)
411{
412#define REG(n, w)	PCIB_READ_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, n, w)
413	int	ptr, nextptr, ptrptr;
414
415	switch (cfg->hdrtype & PCIM_HDRTYPE) {
416	case 0:
417		ptrptr = PCIR_CAP_PTR;
418		break;
419	case 2:
420		ptrptr = 0x14;
421		break;
422	default:
423		return;		/* no extended capabilities support */
424	}
425	nextptr = REG(ptrptr, 1);	/* sanity check? */
426
427	/*
428	 * Read capability entries.
429	 */
430	while (nextptr != 0) {
431		/* Sanity check */
432		if (nextptr > 255) {
433			printf("illegal PCI extended capability offset %d\n",
434			    nextptr);
435			return;
436		}
437		/* Find the next entry */
438		ptr = nextptr;
439		nextptr = REG(ptr + 1, 1);
440
441		/* Process this entry */
442		switch (REG(ptr, 1)) {
443		case PCIY_PMG:		/* PCI power management */
444			if (cfg->pp.pp_cap == 0) {
445				cfg->pp.pp_cap = REG(ptr + PCIR_POWER_CAP, 2);
446				cfg->pp.pp_status = ptr + PCIR_POWER_STATUS;
447				cfg->pp.pp_pmcsr = ptr + PCIR_POWER_PMCSR;
448				if ((nextptr - ptr) > PCIR_POWER_DATA)
449					cfg->pp.pp_data = ptr + PCIR_POWER_DATA;
450			}
451			break;
452		case PCIY_MSI:		/* PCI MSI */
453			cfg->msi.msi_ctrl = REG(ptr + PCIR_MSI_CTRL, 2);
454			if (cfg->msi.msi_ctrl & PCIM_MSICTRL_64BIT)
455				cfg->msi.msi_data = PCIR_MSI_DATA_64BIT;
456			else
457				cfg->msi.msi_data = PCIR_MSI_DATA;
458			cfg->msi.msi_msgnum = 1 << ((cfg->msi.msi_ctrl &
459						     PCIM_MSICTRL_MMC_MASK)>>1);
460		default:
461			break;
462		}
463	}
464#undef REG
465}
466
467/* free pcicfgregs structure and all depending data structures */
468
469int
470pci_freecfg(struct pci_devinfo *dinfo)
471{
472	struct devlist *devlist_head;
473
474	devlist_head = &pci_devq;
475
476	STAILQ_REMOVE(devlist_head, dinfo, pci_devinfo, pci_links);
477	free(dinfo, M_DEVBUF);
478
479	/* increment the generation count */
480	pci_generation++;
481
482	/* we're losing one device */
483	pci_numdevs--;
484	return (0);
485}
486
487/*
488 * PCI power manangement
489 */
490int
491pci_set_powerstate_method(device_t dev, device_t child, int state)
492{
493	struct pci_devinfo *dinfo = device_get_ivars(child);
494	pcicfgregs *cfg = &dinfo->cfg;
495	uint16_t status;
496	int result;
497
498	/*
499	 * Dx -> Dx is a nop always.
500	 */
501	if (pci_get_powerstate(child) == state)
502		return (0);
503
504	if (cfg->pp.pp_cap != 0) {
505		status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2)
506		    & ~PCIM_PSTAT_DMASK;
507		result = 0;
508		switch (state) {
509		case PCI_POWERSTATE_D0:
510			status |= PCIM_PSTAT_D0;
511			break;
512		case PCI_POWERSTATE_D1:
513			if (cfg->pp.pp_cap & PCIM_PCAP_D1SUPP) {
514				status |= PCIM_PSTAT_D1;
515			} else {
516				result = EOPNOTSUPP;
517			}
518			break;
519		case PCI_POWERSTATE_D2:
520			if (cfg->pp.pp_cap & PCIM_PCAP_D2SUPP) {
521				status |= PCIM_PSTAT_D2;
522			} else {
523				result = EOPNOTSUPP;
524			}
525			break;
526		case PCI_POWERSTATE_D3:
527			status |= PCIM_PSTAT_D3;
528			break;
529		default:
530			result = EINVAL;
531		}
532		if (result == 0)
533			PCI_WRITE_CONFIG(dev, child, cfg->pp.pp_status, status,
534					 2);
535	} else {
536		result = ENXIO;
537	}
538	return(result);
539}
540
541int
542pci_get_powerstate_method(device_t dev, device_t child)
543{
544	struct pci_devinfo *dinfo = device_get_ivars(child);
545	pcicfgregs *cfg = &dinfo->cfg;
546	uint16_t status;
547	int result;
548
549	if (cfg->pp.pp_cap != 0) {
550		status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2);
551		switch (status & PCIM_PSTAT_DMASK) {
552		case PCIM_PSTAT_D0:
553			result = PCI_POWERSTATE_D0;
554			break;
555		case PCIM_PSTAT_D1:
556			result = PCI_POWERSTATE_D1;
557			break;
558		case PCIM_PSTAT_D2:
559			result = PCI_POWERSTATE_D2;
560			break;
561		case PCIM_PSTAT_D3:
562			result = PCI_POWERSTATE_D3;
563			break;
564		default:
565			result = PCI_POWERSTATE_UNKNOWN;
566			break;
567		}
568	} else {
569		/* No support, device is always at D0 */
570		result = PCI_POWERSTATE_D0;
571	}
572	return(result);
573}
574
575/*
576 * Some convenience functions for PCI device drivers.
577 */
578
579static __inline void
580pci_set_command_bit(device_t dev, device_t child, uint16_t bit)
581{
582	uint16_t	command;
583
584	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
585	command |= bit;
586	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
587}
588
589static __inline void
590pci_clear_command_bit(device_t dev, device_t child, uint16_t bit)
591{
592	uint16_t	command;
593
594	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
595	command &= ~bit;
596	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
597}
598
599int
600pci_enable_busmaster_method(device_t dev, device_t child)
601{
602	pci_set_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
603	return (0);
604}
605
606int
607pci_disable_busmaster_method(device_t dev, device_t child)
608{
609	pci_clear_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
610	return (0);
611}
612
613int
614pci_enable_io_method(device_t dev, device_t child, int space)
615{
616	uint16_t command;
617	uint16_t bit;
618	char *error;
619
620	bit = 0;
621	error = NULL;
622
623	switch(space) {
624	case SYS_RES_IOPORT:
625		bit = PCIM_CMD_PORTEN;
626		error = "port";
627		break;
628	case SYS_RES_MEMORY:
629		bit = PCIM_CMD_MEMEN;
630		error = "memory";
631		break;
632	default:
633		return (EINVAL);
634	}
635	pci_set_command_bit(dev, child, bit);
636	/* Some devices seem to need a brief stall here, what do to? */
637	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
638	if (command & bit)
639		return (0);
640	device_printf(child, "failed to enable %s mapping!\n", error);
641	return (ENXIO);
642}
643
644int
645pci_disable_io_method(device_t dev, device_t child, int space)
646{
647	uint16_t command;
648	uint16_t bit;
649	char *error;
650
651	bit = 0;
652	error = NULL;
653
654	switch(space) {
655	case SYS_RES_IOPORT:
656		bit = PCIM_CMD_PORTEN;
657		error = "port";
658		break;
659	case SYS_RES_MEMORY:
660		bit = PCIM_CMD_MEMEN;
661		error = "memory";
662		break;
663	default:
664		return (EINVAL);
665	}
666	pci_clear_command_bit(dev, child, bit);
667	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
668	if (command & bit) {
669		device_printf(child, "failed to disable %s mapping!\n", error);
670		return (ENXIO);
671	}
672	return (0);
673}
674
675/*
676 * New style pci driver.  Parent device is either a pci-host-bridge or a
677 * pci-pci-bridge.  Both kinds are represented by instances of pcib.
678 */
679
680void
681pci_print_verbose(struct pci_devinfo *dinfo)
682{
683	if (bootverbose) {
684		pcicfgregs *cfg = &dinfo->cfg;
685
686		printf("found->\tvendor=0x%04x, dev=0x%04x, revid=0x%02x\n",
687		    cfg->vendor, cfg->device, cfg->revid);
688		printf("\tbus=%d, slot=%d, func=%d\n",
689		    cfg->bus, cfg->slot, cfg->func);
690		printf("\tclass=%02x-%02x-%02x, hdrtype=0x%02x, mfdev=%d\n",
691		    cfg->baseclass, cfg->subclass, cfg->progif, cfg->hdrtype,
692		    cfg->mfdev);
693		printf("\tcmdreg=0x%04x, statreg=0x%04x, cachelnsz=%d (dwords)\n",
694		    cfg->cmdreg, cfg->statreg, cfg->cachelnsz);
695		printf("\tlattimer=0x%02x (%d ns), mingnt=0x%02x (%d ns), maxlat=0x%02x (%d ns)\n",
696		    cfg->lattimer, cfg->lattimer * 30, cfg->mingnt,
697		    cfg->mingnt * 250, cfg->maxlat, cfg->maxlat * 250);
698		if (cfg->intpin > 0)
699			printf("\tintpin=%c, irq=%d\n",
700			    cfg->intpin +'a' -1, cfg->intline);
701		if (cfg->pp.pp_cap) {
702			uint16_t status;
703
704			status = pci_read_config(cfg->dev, cfg->pp.pp_status, 2);
705			printf("\tpowerspec %d  supports D0%s%s D3  current D%d\n",
706			    cfg->pp.pp_cap & PCIM_PCAP_SPEC,
707			    cfg->pp.pp_cap & PCIM_PCAP_D1SUPP ? " D1" : "",
708			    cfg->pp.pp_cap & PCIM_PCAP_D2SUPP ? " D2" : "",
709			    status & PCIM_PSTAT_DMASK);
710		}
711		if (cfg->msi.msi_data) {
712			int ctrl;
713
714			ctrl =  cfg->msi.msi_ctrl;
715			printf("\tMSI supports %d message%s%s%s\n",
716			    cfg->msi.msi_msgnum,
717			    (cfg->msi.msi_msgnum == 1) ? "" : "s",
718			    (ctrl & PCIM_MSICTRL_64BIT) ? ", 64 bit" : "",
719			    (ctrl & PCIM_MSICTRL_VECTOR) ? ", vector masks":"");
720		}
721	}
722}
723
724static int
725pci_porten(device_t pcib, int b, int s, int f)
726{
727	return (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2)
728		& PCIM_CMD_PORTEN) != 0;
729}
730
731static int
732pci_memen(device_t pcib, int b, int s, int f)
733{
734	return (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2)
735		& PCIM_CMD_MEMEN) != 0;
736}
737
738/*
739 * Add a resource based on a pci map register. Return 1 if the map
740 * register is a 32bit map register or 2 if it is a 64bit register.
741 */
742static int
743pci_add_map(device_t pcib, device_t bus, device_t dev,
744    int b, int s, int f, int reg, struct resource_list *rl)
745{
746	uint32_t map;
747	uint64_t base;
748	uint64_t start, end, count;
749	uint8_t ln2size;
750	uint8_t ln2range;
751	uint32_t testval;
752	uint16_t cmd;
753	int type;
754
755	map = PCIB_READ_CONFIG(pcib, b, s, f, reg, 4);
756	PCIB_WRITE_CONFIG(pcib, b, s, f, reg, 0xffffffff, 4);
757	testval = PCIB_READ_CONFIG(pcib, b, s, f, reg, 4);
758	PCIB_WRITE_CONFIG(pcib, b, s, f, reg, map, 4);
759
760	if (pci_maptype(map) & PCI_MAPMEM)
761		type = SYS_RES_MEMORY;
762	else
763		type = SYS_RES_IOPORT;
764	ln2size = pci_mapsize(testval);
765	ln2range = pci_maprange(testval);
766	base = pci_mapbase(map);
767
768	/*
769	 * For I/O registers, if bottom bit is set, and the next bit up
770	 * isn't clear, we know we have a BAR that doesn't conform to the
771	 * spec, so ignore it.  Also, sanity check the size of the data
772	 * areas to the type of memory involved.  Memory must be at least
773	 * 32 bytes in size, while I/O ranges must be at least 4.
774	 */
775	if ((testval & 0x1) == 0x1 &&
776	    (testval & 0x2) != 0)
777		return (1);
778	if ((type == SYS_RES_MEMORY && ln2size < 5) ||
779	    (type == SYS_RES_IOPORT && ln2size < 2))
780		return (1);
781
782	if (ln2range == 64)
783		/* Read the other half of a 64bit map register */
784		base |= (uint64_t) PCIB_READ_CONFIG(pcib, b, s, f, reg + 4, 4) << 32;
785
786	if (bootverbose) {
787		printf("\tmap[%02x]: type %x, range %2d, base %08x, size %2d",
788		    reg, pci_maptype(map), ln2range,
789		    (unsigned int) base, ln2size);
790		if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f))
791			printf(", port disabled\n");
792		else if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f))
793			printf(", memory disabled\n");
794		else
795			printf(", enabled\n");
796	}
797
798	/*
799	 * This code theoretically does the right thing, but has
800	 * undesirable side effects in some cases where peripherals
801	 * respond oddly to having these bits enabled.  Let the user
802	 * be able to turn them off (since pci_enable_io_modes is 1 by
803	 * default).
804	 */
805	if (pci_enable_io_modes) {
806		/* Turn on resources that have been left off by a lazy BIOS */
807		if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f)) {
808			cmd = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2);
809			cmd |= PCIM_CMD_PORTEN;
810			PCIB_WRITE_CONFIG(pcib, b, s, f, PCIR_COMMAND, cmd, 2);
811		}
812		if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f)) {
813			cmd = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2);
814			cmd |= PCIM_CMD_MEMEN;
815			PCIB_WRITE_CONFIG(pcib, b, s, f, PCIR_COMMAND, cmd, 2);
816		}
817	} else {
818		if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f))
819			return (1);
820		if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f))
821			return (1);
822	}
823	/*
824	 * If base is 0, then we have problems.  It is best to ignore
825	 * such entires for the moment.  These will be allocated later if
826	 * the driver specifically requests them.
827	 */
828	if (base == 0)
829		return 1;
830
831	start = base;
832	end = base + (1 << ln2size) - 1;
833	count = 1 << ln2size;
834	resource_list_add(rl, type, reg, start, end, count);
835
836	/*
837	 * Not quite sure what to do on failure of allocating the resource
838	 * since I can postulate several right answers.
839	 */
840	resource_list_alloc(rl, bus, dev, type, &reg, start, end, count, 0);
841	return ((ln2range == 64) ? 2 : 1);
842}
843
844/*
845 * For ATA devices we need to decide early what addressing mode to use.
846 * Legacy demands that the primary and secondary ATA ports sits on the
847 * same addresses that old ISA hardware did. This dictates that we use
848 * those addresses and ignore the BAR's if we cannot set PCI native
849 * addressing mode.
850 */
851static void
852pci_ata_maps(device_t pcib, device_t bus, device_t dev, int b,
853	     int s, int f, struct resource_list *rl)
854{
855	int rid, type, progif;
856#if 0
857	/* if this device supports PCI native addressing use it */
858	progif = pci_read_config(dev, PCIR_PROGIF, 1);
859	if ((progif & 0x8a) == 0x8a) {
860		if (pci_mapbase(pci_read_config(dev, PCIR_BAR(0), 4)) &&
861		    pci_mapbase(pci_read_config(dev, PCIR_BAR(2), 4))) {
862			printf("Trying ATA native PCI addressing mode\n");
863			pci_write_config(dev, PCIR_PROGIF, progif | 0x05, 1);
864		}
865	}
866#endif
867	progif = pci_read_config(dev, PCIR_PROGIF, 1);
868	type = SYS_RES_IOPORT;
869	if (progif & PCIP_STORAGE_IDE_MODEPRIM) {
870		pci_add_map(pcib, bus, dev, b, s, f, PCIR_BAR(0), rl);
871		pci_add_map(pcib, bus, dev, b, s, f, PCIR_BAR(1), rl);
872	}
873	else {
874		rid = PCIR_BAR(0);
875		resource_list_add(rl, type, rid, 0x1f0, 0x1f7, 8);
876		resource_list_alloc(rl, bus, dev, type, &rid, 0x1f0, 0x1f7,8,0);
877		rid = PCIR_BAR(1);
878		resource_list_add(rl, type, rid, 0x3f6, 0x3f6, 1);
879		resource_list_alloc(rl, bus, dev, type, &rid, 0x3f6, 0x3f6,1,0);
880	}
881	if (progif & PCIP_STORAGE_IDE_MODESEC) {
882		pci_add_map(pcib, bus, dev, b, s, f, PCIR_BAR(2), rl);
883		pci_add_map(pcib, bus, dev, b, s, f, PCIR_BAR(3), rl);
884	}
885	else {
886		rid = PCIR_BAR(2);
887		resource_list_add(rl, type, rid, 0x170, 0x177, 8);
888		resource_list_alloc(rl, bus, dev, type, &rid, 0x170, 0x177,8,0);
889		rid = PCIR_BAR(3);
890		resource_list_add(rl, type, rid, 0x376, 0x376, 1);
891		resource_list_alloc(rl, bus, dev, type, &rid, 0x376, 0x376,1,0);
892	}
893	pci_add_map(pcib, bus, dev, b, s, f, PCIR_BAR(4), rl);
894}
895
896static void
897pci_add_resources(device_t pcib, device_t bus, device_t dev)
898{
899	struct pci_devinfo *dinfo = device_get_ivars(dev);
900	pcicfgregs *cfg = &dinfo->cfg;
901	struct resource_list *rl = &dinfo->resources;
902	struct pci_quirk *q;
903	int b, i, irq, f, s;
904
905	b = cfg->bus;
906	s = cfg->slot;
907	f = cfg->func;
908
909	/* ATA devices needs special map treatment */
910	if ((pci_get_class(dev) == PCIC_STORAGE) &&
911	    (pci_get_subclass(dev) == PCIS_STORAGE_IDE) &&
912	    (pci_get_progif(dev) & PCIP_STORAGE_IDE_MASTERDEV))
913		pci_ata_maps(pcib, bus, dev, b, s, f, rl);
914	else
915		for (i = 0; i < cfg->nummaps;)
916			i += pci_add_map(pcib, bus, dev, b, s, f, PCIR_BAR(i),
917			    rl);
918
919	for (q = &pci_quirks[0]; q->devid; q++) {
920		if (q->devid == ((cfg->device << 16) | cfg->vendor)
921		    && q->type == PCI_QUIRK_MAP_REG)
922			pci_add_map(pcib, bus, dev, b, s, f, q->arg1, rl);
923	}
924
925	if (cfg->intpin > 0 && PCI_INTERRUPT_VALID(cfg->intline)) {
926#if defined(__ia64__) || defined(__i386__) || defined(__amd64__) || \
927		defined(__arm__)
928		/*
929		 * Try to re-route interrupts. Sometimes the BIOS or
930		 * firmware may leave bogus values in these registers.
931		 * If the re-route fails, then just stick with what we
932		 * have.
933		 */
934		irq = PCI_ASSIGN_INTERRUPT(bus, dev);
935		if (PCI_INTERRUPT_VALID(irq)) {
936			pci_write_config(dev, PCIR_INTLINE, irq, 1);
937			cfg->intline = irq;
938		} else
939#endif
940			irq = cfg->intline;
941		resource_list_add(rl, SYS_RES_IRQ, 0, irq, irq, 1);
942	}
943}
944
945void
946pci_add_children(device_t dev, int busno, size_t dinfo_size)
947{
948#define REG(n, w)	PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
949	device_t pcib = device_get_parent(dev);
950	struct pci_devinfo *dinfo;
951	int maxslots;
952	int s, f, pcifunchigh;
953	uint8_t hdrtype;
954
955	KASSERT(dinfo_size >= sizeof(struct pci_devinfo),
956	    ("dinfo_size too small"));
957	maxslots = PCIB_MAXSLOTS(pcib);
958	for (s = 0; s <= maxslots; s++) {
959		pcifunchigh = 0;
960		f = 0;
961		hdrtype = REG(PCIR_HDRTYPE, 1);
962		if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
963			continue;
964		if (hdrtype & PCIM_MFDEV)
965			pcifunchigh = PCI_FUNCMAX;
966		for (f = 0; f <= pcifunchigh; f++) {
967			dinfo = pci_read_device(pcib, busno, s, f, dinfo_size);
968			if (dinfo != NULL) {
969				pci_add_child(dev, dinfo);
970			}
971		}
972	}
973#undef REG
974}
975
976void
977pci_add_child(device_t bus, struct pci_devinfo *dinfo)
978{
979	device_t pcib;
980
981	pcib = device_get_parent(bus);
982	dinfo->cfg.dev = device_add_child(bus, NULL, -1);
983	device_set_ivars(dinfo->cfg.dev, dinfo);
984	pci_cfg_save(dinfo->cfg.dev, dinfo, 0);
985	pci_cfg_restore(dinfo->cfg.dev, dinfo);
986	pci_add_resources(pcib, bus, dinfo->cfg.dev);
987	pci_print_verbose(dinfo);
988}
989
990static int
991pci_probe(device_t dev)
992{
993
994	device_set_desc(dev, "PCI bus");
995
996	/* Allow other subclasses to override this driver. */
997	return (-1000);
998}
999
1000static int
1001pci_attach(device_t dev)
1002{
1003	int busno;
1004
1005	/*
1006	 * Since there can be multiple independantly numbered PCI
1007	 * busses on some large alpha systems, we can't use the unit
1008	 * number to decide what bus we are probing. We ask the parent
1009	 * pcib what our bus number is.
1010	 */
1011	busno = pcib_get_bus(dev);
1012	if (bootverbose)
1013		device_printf(dev, "physical bus=%d\n", busno);
1014
1015	pci_add_children(dev, busno, sizeof(struct pci_devinfo));
1016
1017	return (bus_generic_attach(dev));
1018}
1019
1020int
1021pci_suspend(device_t dev)
1022{
1023	int dstate, error, i, numdevs;
1024	device_t acpi_dev, child, *devlist;
1025	struct pci_devinfo *dinfo;
1026
1027	/*
1028	 * Save the PCI configuration space for each child and set the
1029	 * device in the appropriate power state for this sleep state.
1030	 */
1031	acpi_dev = NULL;
1032	if (pci_do_powerstate)
1033		acpi_dev = devclass_get_device(devclass_find("acpi"), 0);
1034	device_get_children(dev, &devlist, &numdevs);
1035	for (i = 0; i < numdevs; i++) {
1036		child = devlist[i];
1037		dinfo = (struct pci_devinfo *) device_get_ivars(child);
1038		pci_cfg_save(child, dinfo, 0);
1039	}
1040
1041	/* Suspend devices before potentially powering them down. */
1042	error = bus_generic_suspend(dev);
1043	if (error)
1044		return (error);
1045
1046	/*
1047	 * Always set the device to D3.  If ACPI suggests a different
1048	 * power state, use it instead.  If ACPI is not present, the
1049	 * firmware is responsible for managing device power.  Skip
1050	 * children who aren't attached since they are powered down
1051	 * separately.  Only manage type 0 devices for now.
1052	 */
1053	for (i = 0; acpi_dev && i < numdevs; i++) {
1054		child = devlist[i];
1055		dinfo = (struct pci_devinfo *) device_get_ivars(child);
1056		if (device_is_attached(child) && dinfo->cfg.hdrtype == 0) {
1057			dstate = PCI_POWERSTATE_D3;
1058			ACPI_PWR_FOR_SLEEP(acpi_dev, child, &dstate);
1059			pci_set_powerstate(child, dstate);
1060		}
1061	}
1062	free(devlist, M_TEMP);
1063	return (0);
1064}
1065
1066int
1067pci_resume(device_t dev)
1068{
1069	int i, numdevs;
1070	device_t acpi_dev, child, *devlist;
1071	struct pci_devinfo *dinfo;
1072
1073	/*
1074	 * Set each child to D0 and restore its PCI configuration space.
1075	 */
1076	acpi_dev = NULL;
1077	if (pci_do_powerstate)
1078		acpi_dev = devclass_get_device(devclass_find("acpi"), 0);
1079	device_get_children(dev, &devlist, &numdevs);
1080	for (i = 0; i < numdevs; i++) {
1081		/*
1082		 * Notify ACPI we're going to D0 but ignore the result.  If
1083		 * ACPI is not present, the firmware is responsible for
1084		 * managing device power.  Only manage type 0 devices for now.
1085		 */
1086		child = devlist[i];
1087		dinfo = (struct pci_devinfo *) device_get_ivars(child);
1088		if (acpi_dev && device_is_attached(child) &&
1089		    dinfo->cfg.hdrtype == 0) {
1090			ACPI_PWR_FOR_SLEEP(acpi_dev, child, NULL);
1091			pci_set_powerstate(child, PCI_POWERSTATE_D0);
1092		}
1093
1094		/* Now the device is powered up, restore its config space. */
1095		pci_cfg_restore(child, dinfo);
1096	}
1097	free(devlist, M_TEMP);
1098	return (bus_generic_resume(dev));
1099}
1100
1101static void
1102pci_load_vendor_data(void)
1103{
1104	caddr_t vendordata, info;
1105
1106	if ((vendordata = preload_search_by_type("pci_vendor_data")) != NULL) {
1107		info = preload_search_info(vendordata, MODINFO_ADDR);
1108		pci_vendordata = *(char **)info;
1109		info = preload_search_info(vendordata, MODINFO_SIZE);
1110		pci_vendordata_size = *(size_t *)info;
1111		/* terminate the database */
1112		pci_vendordata[pci_vendordata_size] = '\n';
1113	}
1114}
1115
1116void
1117pci_driver_added(device_t dev, driver_t *driver)
1118{
1119	int numdevs;
1120	device_t *devlist;
1121	device_t child;
1122	struct pci_devinfo *dinfo;
1123	int i;
1124
1125	if (bootverbose)
1126		device_printf(dev, "driver added\n");
1127	DEVICE_IDENTIFY(driver, dev);
1128	device_get_children(dev, &devlist, &numdevs);
1129	for (i = 0; i < numdevs; i++) {
1130		child = devlist[i];
1131		if (device_get_state(child) != DS_NOTPRESENT)
1132			continue;
1133		dinfo = device_get_ivars(child);
1134		pci_print_verbose(dinfo);
1135/*XXX???*/	/* resource_list_init(&dinfo->cfg.resources); */
1136		if (bootverbose)
1137			printf("pci%d:%d:%d: reprobing on driver added\n",
1138			    dinfo->cfg.bus, dinfo->cfg.slot, dinfo->cfg.func);
1139		pci_cfg_restore(child, dinfo);
1140		if (device_probe_and_attach(child) != 0)
1141			pci_cfg_save(child, dinfo, 1);
1142	}
1143	free(devlist, M_TEMP);
1144}
1145
1146int
1147pci_print_child(device_t dev, device_t child)
1148{
1149	struct pci_devinfo *dinfo;
1150	struct resource_list *rl;
1151	int retval = 0;
1152
1153	dinfo = device_get_ivars(child);
1154	rl = &dinfo->resources;
1155
1156	retval += bus_print_child_header(dev, child);
1157
1158	retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#lx");
1159	retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY, "%#lx");
1160	retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%ld");
1161	if (device_get_flags(dev))
1162		retval += printf(" flags %#x", device_get_flags(dev));
1163
1164	retval += printf(" at device %d.%d", pci_get_slot(child),
1165	    pci_get_function(child));
1166
1167	retval += bus_print_child_footer(dev, child);
1168
1169	return (retval);
1170}
1171
1172static struct
1173{
1174	int	class;
1175	int	subclass;
1176	char	*desc;
1177} pci_nomatch_tab[] = {
1178	{PCIC_OLD,		-1,			"old"},
1179	{PCIC_OLD,		PCIS_OLD_NONVGA,	"non-VGA display device"},
1180	{PCIC_OLD,		PCIS_OLD_VGA,		"VGA-compatible display device"},
1181	{PCIC_STORAGE,		-1,			"mass storage"},
1182	{PCIC_STORAGE,		PCIS_STORAGE_SCSI,	"SCSI"},
1183	{PCIC_STORAGE,		PCIS_STORAGE_IDE,	"ATA"},
1184	{PCIC_STORAGE,		PCIS_STORAGE_FLOPPY,	"floppy disk"},
1185	{PCIC_STORAGE,		PCIS_STORAGE_IPI,	"IPI"},
1186	{PCIC_STORAGE,		PCIS_STORAGE_RAID,	"RAID"},
1187	{PCIC_NETWORK,		-1,			"network"},
1188	{PCIC_NETWORK,		PCIS_NETWORK_ETHERNET,	"ethernet"},
1189	{PCIC_NETWORK,		PCIS_NETWORK_TOKENRING,	"token ring"},
1190	{PCIC_NETWORK,		PCIS_NETWORK_FDDI,	"fddi"},
1191	{PCIC_NETWORK,		PCIS_NETWORK_ATM,	"ATM"},
1192	{PCIC_DISPLAY,		-1,			"display"},
1193	{PCIC_DISPLAY,		PCIS_DISPLAY_VGA,	"VGA"},
1194	{PCIC_DISPLAY,		PCIS_DISPLAY_XGA,	"XGA"},
1195	{PCIC_MULTIMEDIA,	-1,			"multimedia"},
1196	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_VIDEO,	"video"},
1197	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_AUDIO,	"audio"},
1198	{PCIC_MEMORY,		-1,			"memory"},
1199	{PCIC_MEMORY,		PCIS_MEMORY_RAM,	"RAM"},
1200	{PCIC_MEMORY,		PCIS_MEMORY_FLASH,	"flash"},
1201	{PCIC_BRIDGE,		-1,			"bridge"},
1202	{PCIC_BRIDGE,		PCIS_BRIDGE_HOST,	"HOST-PCI"},
1203	{PCIC_BRIDGE,		PCIS_BRIDGE_ISA,	"PCI-ISA"},
1204	{PCIC_BRIDGE,		PCIS_BRIDGE_EISA,	"PCI-EISA"},
1205	{PCIC_BRIDGE,		PCIS_BRIDGE_MCA,	"PCI-MCA"},
1206	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI,	"PCI-PCI"},
1207	{PCIC_BRIDGE,		PCIS_BRIDGE_PCMCIA,	"PCI-PCMCIA"},
1208	{PCIC_BRIDGE,		PCIS_BRIDGE_NUBUS,	"PCI-NuBus"},
1209	{PCIC_BRIDGE,		PCIS_BRIDGE_CARDBUS,	"PCI-CardBus"},
1210	{PCIC_BRIDGE,		PCIS_BRIDGE_OTHER,	"PCI-unknown"},
1211	{PCIC_SIMPLECOMM,	-1,			"simple comms"},
1212	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_UART,	"UART"},	/* could detect 16550 */
1213	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_PAR,	"parallel port"},
1214	{PCIC_BASEPERIPH,	-1,			"base peripheral"},
1215	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PIC,	"interrupt controller"},
1216	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_DMA,	"DMA controller"},
1217	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_TIMER,	"timer"},
1218	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RTC,	"realtime clock"},
1219	{PCIC_INPUTDEV,		-1,			"input device"},
1220	{PCIC_INPUTDEV,		PCIS_INPUTDEV_KEYBOARD,	"keyboard"},
1221	{PCIC_INPUTDEV,		PCIS_INPUTDEV_DIGITIZER,"digitizer"},
1222	{PCIC_INPUTDEV,		PCIS_INPUTDEV_MOUSE,	"mouse"},
1223	{PCIC_DOCKING,		-1,			"docking station"},
1224	{PCIC_PROCESSOR,	-1,			"processor"},
1225	{PCIC_SERIALBUS,	-1,			"serial bus"},
1226	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FW,	"FireWire"},
1227	{PCIC_SERIALBUS,	PCIS_SERIALBUS_ACCESS,	"AccessBus"},
1228	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SSA,	"SSA"},
1229	{PCIC_SERIALBUS,	PCIS_SERIALBUS_USB,	"USB"},
1230	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FC,	"Fibre Channel"},
1231	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SMBUS,	"SMBus"},
1232	{0, 0,		NULL}
1233};
1234
1235void
1236pci_probe_nomatch(device_t dev, device_t child)
1237{
1238	int	i;
1239	char	*cp, *scp, *device;
1240
1241	/*
1242	 * Look for a listing for this device in a loaded device database.
1243	 */
1244	if ((device = pci_describe_device(child)) != NULL) {
1245		device_printf(dev, "<%s>", device);
1246		free(device, M_DEVBUF);
1247	} else {
1248		/*
1249		 * Scan the class/subclass descriptions for a general
1250		 * description.
1251		 */
1252		cp = "unknown";
1253		scp = NULL;
1254		for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
1255			if (pci_nomatch_tab[i].class == pci_get_class(child)) {
1256				if (pci_nomatch_tab[i].subclass == -1) {
1257					cp = pci_nomatch_tab[i].desc;
1258				} else if (pci_nomatch_tab[i].subclass ==
1259				    pci_get_subclass(child)) {
1260					scp = pci_nomatch_tab[i].desc;
1261				}
1262			}
1263		}
1264		device_printf(dev, "<%s%s%s>",
1265		    cp ? cp : "",
1266		    ((cp != NULL) && (scp != NULL)) ? ", " : "",
1267		    scp ? scp : "");
1268	}
1269	printf(" at device %d.%d (no driver attached)\n",
1270	    pci_get_slot(child), pci_get_function(child));
1271	if (pci_do_powerstate)
1272		pci_cfg_save(child,
1273		    (struct pci_devinfo *) device_get_ivars(child), 1);
1274	return;
1275}
1276
1277/*
1278 * Parse the PCI device database, if loaded, and return a pointer to a
1279 * description of the device.
1280 *
1281 * The database is flat text formatted as follows:
1282 *
1283 * Any line not in a valid format is ignored.
1284 * Lines are terminated with newline '\n' characters.
1285 *
1286 * A VENDOR line consists of the 4 digit (hex) vendor code, a TAB, then
1287 * the vendor name.
1288 *
1289 * A DEVICE line is entered immediately below the corresponding VENDOR ID.
1290 * - devices cannot be listed without a corresponding VENDOR line.
1291 * A DEVICE line consists of a TAB, the 4 digit (hex) device code,
1292 * another TAB, then the device name.
1293 */
1294
1295/*
1296 * Assuming (ptr) points to the beginning of a line in the database,
1297 * return the vendor or device and description of the next entry.
1298 * The value of (vendor) or (device) inappropriate for the entry type
1299 * is set to -1.  Returns nonzero at the end of the database.
1300 *
1301 * Note that this is slightly unrobust in the face of corrupt data;
1302 * we attempt to safeguard against this by spamming the end of the
1303 * database with a newline when we initialise.
1304 */
1305static int
1306pci_describe_parse_line(char **ptr, int *vendor, int *device, char **desc)
1307{
1308	char	*cp = *ptr;
1309	int	left;
1310
1311	*device = -1;
1312	*vendor = -1;
1313	**desc = '\0';
1314	for (;;) {
1315		left = pci_vendordata_size - (cp - pci_vendordata);
1316		if (left <= 0) {
1317			*ptr = cp;
1318			return(1);
1319		}
1320
1321		/* vendor entry? */
1322		if (*cp != '\t' &&
1323		    sscanf(cp, "%x\t%80[^\n]", vendor, *desc) == 2)
1324			break;
1325		/* device entry? */
1326		if (*cp == '\t' &&
1327		    sscanf(cp, "%x\t%80[^\n]", device, *desc) == 2)
1328			break;
1329
1330		/* skip to next line */
1331		while (*cp != '\n' && left > 0) {
1332			cp++;
1333			left--;
1334		}
1335		if (*cp == '\n') {
1336			cp++;
1337			left--;
1338		}
1339	}
1340	/* skip to next line */
1341	while (*cp != '\n' && left > 0) {
1342		cp++;
1343		left--;
1344	}
1345	if (*cp == '\n' && left > 0)
1346		cp++;
1347	*ptr = cp;
1348	return(0);
1349}
1350
1351static char *
1352pci_describe_device(device_t dev)
1353{
1354	int	vendor, device;
1355	char	*desc, *vp, *dp, *line;
1356
1357	desc = vp = dp = NULL;
1358
1359	/*
1360	 * If we have no vendor data, we can't do anything.
1361	 */
1362	if (pci_vendordata == NULL)
1363		goto out;
1364
1365	/*
1366	 * Scan the vendor data looking for this device
1367	 */
1368	line = pci_vendordata;
1369	if ((vp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
1370		goto out;
1371	for (;;) {
1372		if (pci_describe_parse_line(&line, &vendor, &device, &vp))
1373			goto out;
1374		if (vendor == pci_get_vendor(dev))
1375			break;
1376	}
1377	if ((dp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
1378		goto out;
1379	for (;;) {
1380		if (pci_describe_parse_line(&line, &vendor, &device, &dp)) {
1381			*dp = 0;
1382			break;
1383		}
1384		if (vendor != -1) {
1385			*dp = 0;
1386			break;
1387		}
1388		if (device == pci_get_device(dev))
1389			break;
1390	}
1391	if (dp[0] == '\0')
1392		snprintf(dp, 80, "0x%x", pci_get_device(dev));
1393	if ((desc = malloc(strlen(vp) + strlen(dp) + 3, M_DEVBUF, M_NOWAIT)) !=
1394	    NULL)
1395		sprintf(desc, "%s, %s", vp, dp);
1396 out:
1397	if (vp != NULL)
1398		free(vp, M_DEVBUF);
1399	if (dp != NULL)
1400		free(dp, M_DEVBUF);
1401	return(desc);
1402}
1403
1404int
1405pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1406{
1407	struct pci_devinfo *dinfo;
1408	pcicfgregs *cfg;
1409
1410	dinfo = device_get_ivars(child);
1411	cfg = &dinfo->cfg;
1412
1413	switch (which) {
1414	case PCI_IVAR_ETHADDR:
1415		/*
1416		 * The generic accessor doesn't deal with failure, so
1417		 * we set the return value, then return an error.
1418		 */
1419		*((uint8_t **) result) = NULL;
1420		return (EINVAL);
1421	case PCI_IVAR_SUBVENDOR:
1422		*result = cfg->subvendor;
1423		break;
1424	case PCI_IVAR_SUBDEVICE:
1425		*result = cfg->subdevice;
1426		break;
1427	case PCI_IVAR_VENDOR:
1428		*result = cfg->vendor;
1429		break;
1430	case PCI_IVAR_DEVICE:
1431		*result = cfg->device;
1432		break;
1433	case PCI_IVAR_DEVID:
1434		*result = (cfg->device << 16) | cfg->vendor;
1435		break;
1436	case PCI_IVAR_CLASS:
1437		*result = cfg->baseclass;
1438		break;
1439	case PCI_IVAR_SUBCLASS:
1440		*result = cfg->subclass;
1441		break;
1442	case PCI_IVAR_PROGIF:
1443		*result = cfg->progif;
1444		break;
1445	case PCI_IVAR_REVID:
1446		*result = cfg->revid;
1447		break;
1448	case PCI_IVAR_INTPIN:
1449		*result = cfg->intpin;
1450		break;
1451	case PCI_IVAR_IRQ:
1452		*result = cfg->intline;
1453		break;
1454	case PCI_IVAR_BUS:
1455		*result = cfg->bus;
1456		break;
1457	case PCI_IVAR_SLOT:
1458		*result = cfg->slot;
1459		break;
1460	case PCI_IVAR_FUNCTION:
1461		*result = cfg->func;
1462		break;
1463	default:
1464		return (ENOENT);
1465	}
1466	return (0);
1467}
1468
1469int
1470pci_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1471{
1472	struct pci_devinfo *dinfo;
1473
1474	dinfo = device_get_ivars(child);
1475
1476	switch (which) {
1477	case PCI_IVAR_INTPIN:
1478		dinfo->cfg.intpin = value;
1479		return (0);
1480	case PCI_IVAR_ETHADDR:
1481	case PCI_IVAR_SUBVENDOR:
1482	case PCI_IVAR_SUBDEVICE:
1483	case PCI_IVAR_VENDOR:
1484	case PCI_IVAR_DEVICE:
1485	case PCI_IVAR_DEVID:
1486	case PCI_IVAR_CLASS:
1487	case PCI_IVAR_SUBCLASS:
1488	case PCI_IVAR_PROGIF:
1489	case PCI_IVAR_REVID:
1490	case PCI_IVAR_IRQ:
1491	case PCI_IVAR_BUS:
1492	case PCI_IVAR_SLOT:
1493	case PCI_IVAR_FUNCTION:
1494		return (EINVAL);	/* disallow for now */
1495
1496	default:
1497		return (ENOENT);
1498	}
1499}
1500
1501
1502#include "opt_ddb.h"
1503#ifdef DDB
1504#include <ddb/ddb.h>
1505#include <sys/cons.h>
1506
1507/*
1508 * List resources based on pci map registers, used for within ddb
1509 */
1510
1511DB_SHOW_COMMAND(pciregs, db_pci_dump)
1512{
1513	struct pci_devinfo *dinfo;
1514	struct devlist *devlist_head;
1515	struct pci_conf *p;
1516	const char *name;
1517	int i, error, none_count, quit;
1518
1519	none_count = 0;
1520	/* get the head of the device queue */
1521	devlist_head = &pci_devq;
1522
1523	/*
1524	 * Go through the list of devices and print out devices
1525	 */
1526	db_setup_paging(db_simple_pager, &quit, db_lines_per_page);
1527	for (error = 0, i = 0, quit = 0,
1528	     dinfo = STAILQ_FIRST(devlist_head);
1529	     (dinfo != NULL) && (error == 0) && (i < pci_numdevs) && !quit;
1530	     dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {
1531
1532		/* Populate pd_name and pd_unit */
1533		name = NULL;
1534		if (dinfo->cfg.dev)
1535			name = device_get_name(dinfo->cfg.dev);
1536
1537		p = &dinfo->conf;
1538		db_printf("%s%d@pci%d:%d:%d:\tclass=0x%06x card=0x%08x "
1539			"chip=0x%08x rev=0x%02x hdr=0x%02x\n",
1540			(name && *name) ? name : "none",
1541			(name && *name) ? (int)device_get_unit(dinfo->cfg.dev) :
1542			none_count++,
1543			p->pc_sel.pc_bus, p->pc_sel.pc_dev,
1544			p->pc_sel.pc_func, (p->pc_class << 16) |
1545			(p->pc_subclass << 8) | p->pc_progif,
1546			(p->pc_subdevice << 16) | p->pc_subvendor,
1547			(p->pc_device << 16) | p->pc_vendor,
1548			p->pc_revid, p->pc_hdr);
1549	}
1550}
1551#endif /* DDB */
1552
1553static struct resource *
1554pci_alloc_map(device_t dev, device_t child, int type, int *rid,
1555    u_long start, u_long end, u_long count, u_int flags)
1556{
1557	struct pci_devinfo *dinfo = device_get_ivars(child);
1558	struct resource_list *rl = &dinfo->resources;
1559	struct resource_list_entry *rle;
1560	struct resource *res;
1561	uint32_t map, testval;
1562	int mapsize;
1563
1564	/*
1565	 * Weed out the bogons, and figure out how large the BAR/map
1566	 * is.  Bars that read back 0 here are bogus and unimplemented.
1567	 * Note: atapci in legacy mode are special and handled elsewhere
1568	 * in the code.  If you have a atapci device in legacy mode and
1569	 * it fails here, that other code is broken.
1570	 */
1571	res = NULL;
1572	map = pci_read_config(child, *rid, 4);
1573	pci_write_config(child, *rid, 0xffffffff, 4);
1574	testval = pci_read_config(child, *rid, 4);
1575	if (testval == 0)
1576		return (NULL);
1577	if (pci_maptype(testval) & PCI_MAPMEM) {
1578		if (type != SYS_RES_MEMORY) {
1579			device_printf(child,
1580			    "failed: rid %#x is memory, requested %d\n",
1581			    *rid, type);
1582			goto out;
1583		}
1584	} else {
1585		if (type != SYS_RES_IOPORT) {
1586			device_printf(child,
1587			    "failed: rid %#x is ioport, requested %d\n",
1588			    *rid, type);
1589			goto out;
1590		}
1591	}
1592	/*
1593	 * For real BARs, we need to override the size that
1594	 * the driver requests, because that's what the BAR
1595	 * actually uses and we would otherwise have a
1596	 * situation where we might allocate the excess to
1597	 * another driver, which won't work.
1598	 */
1599	mapsize = pci_mapsize(testval);
1600	count = 1 << mapsize;
1601	if (RF_ALIGNMENT(flags) < mapsize)
1602		flags = (flags & ~RF_ALIGNMENT_MASK) | RF_ALIGNMENT_LOG2(mapsize);
1603
1604	/*
1605	 * Allocate enough resource, and then write back the
1606	 * appropriate bar for that resource.
1607	 */
1608	res = BUS_ALLOC_RESOURCE(device_get_parent(dev), child, type, rid,
1609	    start, end, count, flags);
1610	if (res == NULL) {
1611		device_printf(child, "%#lx bytes of rid %#x res %d failed.\n",
1612		    count, *rid, type);
1613		goto out;
1614	}
1615	resource_list_add(rl, type, *rid, start, end, count);
1616	rle = resource_list_find(rl, type, *rid);
1617	if (rle == NULL)
1618		panic("pci_alloc_map: unexpectedly can't find resource.");
1619	rle->res = res;
1620	if (bootverbose)
1621		device_printf(child,
1622		    "Lazy allocation of %#lx bytes rid %#x type %d at %#lx\n",
1623		    count, *rid, type, rman_get_start(res));
1624	map = rman_get_start(res);
1625out:;
1626	pci_write_config(child, *rid, map, 4);
1627	return (res);
1628}
1629
1630
1631struct resource *
1632pci_alloc_resource(device_t dev, device_t child, int type, int *rid,
1633		   u_long start, u_long end, u_long count, u_int flags)
1634{
1635	struct pci_devinfo *dinfo = device_get_ivars(child);
1636	struct resource_list *rl = &dinfo->resources;
1637	struct resource_list_entry *rle;
1638	pcicfgregs *cfg = &dinfo->cfg;
1639
1640	/*
1641	 * Perform lazy resource allocation
1642	 */
1643	if (device_get_parent(child) == dev) {
1644		switch (type) {
1645		case SYS_RES_IRQ:
1646			/*
1647			 * If the child device doesn't have an
1648			 * interrupt routed and is deserving of an
1649			 * interrupt, try to assign it one.
1650			 */
1651			if (!PCI_INTERRUPT_VALID(cfg->intline) &&
1652			    (cfg->intpin != 0)) {
1653				cfg->intline = PCI_ASSIGN_INTERRUPT(dev, child);
1654				if (PCI_INTERRUPT_VALID(cfg->intline)) {
1655					pci_write_config(child, PCIR_INTLINE,
1656					    cfg->intline, 1);
1657					resource_list_add(rl, SYS_RES_IRQ, 0,
1658					    cfg->intline, cfg->intline, 1);
1659				}
1660			}
1661			break;
1662		case SYS_RES_IOPORT:
1663		case SYS_RES_MEMORY:
1664			if (*rid < PCIR_BAR(cfg->nummaps)) {
1665				/*
1666				 * Enable the I/O mode.  We should
1667				 * also be assigning resources too
1668				 * when none are present.  The
1669				 * resource_list_alloc kind of sorta does
1670				 * this...
1671				 */
1672				if (PCI_ENABLE_IO(dev, child, type))
1673					return (NULL);
1674			}
1675			rle = resource_list_find(rl, type, *rid);
1676			if (rle == NULL)
1677				return (pci_alloc_map(dev, child, type, rid,
1678				    start, end, count, flags));
1679			break;
1680		}
1681		/*
1682		 * If we've already allocated the resource, then
1683		 * return it now.  But first we may need to activate
1684		 * it, since we don't allocate the resource as active
1685		 * above.  Normally this would be done down in the
1686		 * nexus, but since we short-circuit that path we have
1687		 * to do its job here.  Not sure if we should free the
1688		 * resource if it fails to activate.
1689		 */
1690		rle = resource_list_find(rl, type, *rid);
1691		if (rle != NULL && rle->res != NULL) {
1692			if (bootverbose)
1693				device_printf(child,
1694			    "Reserved %#lx bytes for rid %#x type %d at %#lx\n",
1695				    rman_get_size(rle->res), *rid, type,
1696				    rman_get_start(rle->res));
1697			if ((flags & RF_ACTIVE) &&
1698			    bus_generic_activate_resource(dev, child, type,
1699			    *rid, rle->res) != 0)
1700				return NULL;
1701			return (rle->res);
1702		}
1703	}
1704	return (resource_list_alloc(rl, dev, child, type, rid,
1705	    start, end, count, flags));
1706}
1707
1708void
1709pci_delete_resource(device_t dev, device_t child, int type, int rid)
1710{
1711	struct pci_devinfo *dinfo;
1712	struct resource_list *rl;
1713	struct resource_list_entry *rle;
1714
1715	if (device_get_parent(child) != dev)
1716		return;
1717
1718	dinfo = device_get_ivars(child);
1719	rl = &dinfo->resources;
1720	rle = resource_list_find(rl, type, rid);
1721	if (rle) {
1722		if (rle->res) {
1723			if (rman_get_device(rle->res) != dev ||
1724			    rman_get_flags(rle->res) & RF_ACTIVE) {
1725				device_printf(dev, "delete_resource: "
1726				    "Resource still owned by child, oops. "
1727				    "(type=%d, rid=%d, addr=%lx)\n",
1728				    rle->type, rle->rid,
1729				    rman_get_start(rle->res));
1730				return;
1731			}
1732			bus_release_resource(dev, type, rid, rle->res);
1733		}
1734		resource_list_delete(rl, type, rid);
1735	}
1736	/*
1737	 * Why do we turn off the PCI configuration BAR when we delete a
1738	 * resource? -- imp
1739	 */
1740	pci_write_config(child, rid, 0, 4);
1741	BUS_DELETE_RESOURCE(device_get_parent(dev), child, type, rid);
1742}
1743
1744struct resource_list *
1745pci_get_resource_list (device_t dev, device_t child)
1746{
1747	struct pci_devinfo *dinfo = device_get_ivars(child);
1748
1749	return (&dinfo->resources);
1750}
1751
1752uint32_t
1753pci_read_config_method(device_t dev, device_t child, int reg, int width)
1754{
1755	struct pci_devinfo *dinfo = device_get_ivars(child);
1756	pcicfgregs *cfg = &dinfo->cfg;
1757
1758	return (PCIB_READ_CONFIG(device_get_parent(dev),
1759	    cfg->bus, cfg->slot, cfg->func, reg, width));
1760}
1761
1762void
1763pci_write_config_method(device_t dev, device_t child, int reg,
1764    uint32_t val, int width)
1765{
1766	struct pci_devinfo *dinfo = device_get_ivars(child);
1767	pcicfgregs *cfg = &dinfo->cfg;
1768
1769	PCIB_WRITE_CONFIG(device_get_parent(dev),
1770	    cfg->bus, cfg->slot, cfg->func, reg, val, width);
1771}
1772
1773int
1774pci_child_location_str_method(device_t dev, device_t child, char *buf,
1775    size_t buflen)
1776{
1777	struct pci_devinfo *dinfo;
1778
1779	dinfo = device_get_ivars(child);
1780	snprintf(buf, buflen, "slot=%d function=%d", pci_get_slot(child),
1781	    pci_get_function(child));
1782	return (0);
1783}
1784
1785int
1786pci_child_pnpinfo_str_method(device_t dev, device_t child, char *buf,
1787    size_t buflen)
1788{
1789	struct pci_devinfo *dinfo;
1790	pcicfgregs *cfg;
1791
1792	dinfo = device_get_ivars(child);
1793	cfg = &dinfo->cfg;
1794	snprintf(buf, buflen, "vendor=0x%04x device=0x%04x subvendor=0x%04x "
1795	    "subdevice=0x%04x class=0x%02x%02x%02x", cfg->vendor, cfg->device,
1796	    cfg->subvendor, cfg->subdevice, cfg->baseclass, cfg->subclass,
1797	    cfg->progif);
1798	return (0);
1799}
1800
1801int
1802pci_assign_interrupt_method(device_t dev, device_t child)
1803{
1804	struct pci_devinfo *dinfo = device_get_ivars(child);
1805	pcicfgregs *cfg = &dinfo->cfg;
1806
1807	return (PCIB_ROUTE_INTERRUPT(device_get_parent(dev), child,
1808	    cfg->intpin));
1809}
1810
1811static int
1812pci_modevent(module_t mod, int what, void *arg)
1813{
1814	static struct cdev *pci_cdev;
1815
1816	switch (what) {
1817	case MOD_LOAD:
1818		STAILQ_INIT(&pci_devq);
1819		pci_generation = 0;
1820		pci_cdev = make_dev(&pcicdev, 0, UID_ROOT, GID_WHEEL, 0644,
1821		    "pci");
1822		pci_load_vendor_data();
1823		break;
1824
1825	case MOD_UNLOAD:
1826		destroy_dev(pci_cdev);
1827		break;
1828	}
1829
1830	return (0);
1831}
1832
1833static void
1834pci_cfg_restore(device_t dev, struct pci_devinfo *dinfo)
1835{
1836	int i;
1837
1838	/*
1839	 * Only do header type 0 devices.  Type 1 devices are bridges,
1840	 * which we know need special treatment.  Type 2 devices are
1841	 * cardbus bridges which also require special treatment.
1842	 * Other types are unknown, and we err on the side of safety
1843	 * by ignoring them.
1844	 */
1845	if (dinfo->cfg.hdrtype != 0)
1846		return;
1847
1848	/*
1849	 * Restore the device to full power mode.  We must do this
1850	 * before we restore the registers because moving from D3 to
1851	 * D0 will cause the chip's BARs and some other registers to
1852	 * be reset to some unknown power on reset values.  Cut down
1853	 * the noise on boot by doing nothing if we are already in
1854	 * state D0.
1855	 */
1856	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
1857		if (bootverbose)
1858			printf(
1859			    "pci%d:%d:%d: Transition from D%d to D0\n",
1860			    dinfo->cfg.bus, dinfo->cfg.slot, dinfo->cfg.func,
1861			    pci_get_powerstate(dev));
1862		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1863	}
1864	for (i = 0; i < dinfo->cfg.nummaps; i++)
1865		pci_write_config(dev, PCIR_BAR(i), dinfo->cfg.bar[i], 4);
1866	pci_write_config(dev, PCIR_BIOS, dinfo->cfg.bios, 4);
1867	pci_write_config(dev, PCIR_COMMAND, dinfo->cfg.cmdreg, 2);
1868	pci_write_config(dev, PCIR_INTLINE, dinfo->cfg.intline, 1);
1869	pci_write_config(dev, PCIR_INTPIN, dinfo->cfg.intpin, 1);
1870	pci_write_config(dev, PCIR_MINGNT, dinfo->cfg.mingnt, 1);
1871	pci_write_config(dev, PCIR_MAXLAT, dinfo->cfg.maxlat, 1);
1872	pci_write_config(dev, PCIR_CACHELNSZ, dinfo->cfg.cachelnsz, 1);
1873	pci_write_config(dev, PCIR_LATTIMER, dinfo->cfg.lattimer, 1);
1874	pci_write_config(dev, PCIR_PROGIF, dinfo->cfg.progif, 1);
1875	pci_write_config(dev, PCIR_REVID, dinfo->cfg.revid, 1);
1876}
1877
1878static void
1879pci_cfg_save(device_t dev, struct pci_devinfo *dinfo, int setstate)
1880{
1881	int i;
1882	uint32_t cls;
1883	int ps;
1884
1885	/*
1886	 * Only do header type 0 devices.  Type 1 devices are bridges, which
1887	 * we know need special treatment.  Type 2 devices are cardbus bridges
1888	 * which also require special treatment.  Other types are unknown, and
1889	 * we err on the side of safety by ignoring them.  Powering down
1890	 * bridges should not be undertaken lightly.
1891	 */
1892	if (dinfo->cfg.hdrtype != 0)
1893		return;
1894	for (i = 0; i < dinfo->cfg.nummaps; i++)
1895		dinfo->cfg.bar[i] = pci_read_config(dev, PCIR_BAR(i), 4);
1896	dinfo->cfg.bios = pci_read_config(dev, PCIR_BIOS, 4);
1897
1898	/*
1899	 * Some drivers apparently write to these registers w/o
1900	 * updating our cahced copy.  No harm happens if we update the
1901	 * copy, so do so here so we can restore them.  The COMMAND
1902	 * register is modified by the bus w/o updating the cache.  This
1903	 * should represent the normally writable portion of the 'defined'
1904	 * part of type 0 headers.  In theory we also need to save/restore
1905	 * the PCI capability structures we know about, but apart from power
1906	 * we don't know any that are writable.
1907	 */
1908	dinfo->cfg.subvendor = pci_read_config(dev, PCIR_SUBVEND_0, 2);
1909	dinfo->cfg.subdevice = pci_read_config(dev, PCIR_SUBDEV_0, 2);
1910	dinfo->cfg.vendor = pci_read_config(dev, PCIR_VENDOR, 2);
1911	dinfo->cfg.device = pci_read_config(dev, PCIR_DEVICE, 2);
1912	dinfo->cfg.cmdreg = pci_read_config(dev, PCIR_COMMAND, 2);
1913	dinfo->cfg.intline = pci_read_config(dev, PCIR_INTLINE, 1);
1914	dinfo->cfg.intpin = pci_read_config(dev, PCIR_INTPIN, 1);
1915	dinfo->cfg.mingnt = pci_read_config(dev, PCIR_MINGNT, 1);
1916	dinfo->cfg.maxlat = pci_read_config(dev, PCIR_MAXLAT, 1);
1917	dinfo->cfg.cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
1918	dinfo->cfg.lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
1919	dinfo->cfg.baseclass = pci_read_config(dev, PCIR_CLASS, 1);
1920	dinfo->cfg.subclass = pci_read_config(dev, PCIR_SUBCLASS, 1);
1921	dinfo->cfg.progif = pci_read_config(dev, PCIR_PROGIF, 1);
1922	dinfo->cfg.revid = pci_read_config(dev, PCIR_REVID, 1);
1923
1924	/*
1925	 * don't set the state for display devices and for memory devices
1926	 * since bad things happen.  we should (a) have drivers that can easily
1927	 * detach and (b) use generic drivers for these devices so that some
1928	 * device actually attaches.  We need to make sure that when we
1929	 * implement (a) we don't power the device down on a reattach.
1930	 */
1931	cls = pci_get_class(dev);
1932	if (setstate && cls != PCIC_DISPLAY && cls != PCIC_MEMORY) {
1933		/*
1934		 * PCI spec is clear that we can only go into D3 state from
1935		 * D0 state.  Transition from D[12] into D0 before going
1936		 * to D3 state.
1937		 */
1938		ps = pci_get_powerstate(dev);
1939		if (ps != PCI_POWERSTATE_D0 && ps != PCI_POWERSTATE_D3) {
1940			if (bootverbose)
1941				printf(
1942				    "pci%d:%d:%d: Transition from D%d to D0\n",
1943				    dinfo->cfg.bus, dinfo->cfg.slot,
1944				    dinfo->cfg.func, ps);
1945			pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1946		}
1947		if (pci_get_powerstate(dev) != PCI_POWERSTATE_D3) {
1948			if (bootverbose)
1949				printf(
1950				    "pci%d:%d:%d: Transition from D0 to D3\n",
1951				    dinfo->cfg.bus, dinfo->cfg.slot,
1952				    dinfo->cfg.func);
1953			pci_set_powerstate(dev, PCI_POWERSTATE_D3);
1954		}
1955	}
1956}
1957