xref: /freebsd/sys/dev/pci/pci.c (revision 38069501)
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$");
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/limits.h>
39 #include <sys/linker.h>
40 #include <sys/fcntl.h>
41 #include <sys/conf.h>
42 #include <sys/kernel.h>
43 #include <sys/queue.h>
44 #include <sys/sysctl.h>
45 #include <sys/endian.h>
46 
47 #include <vm/vm.h>
48 #include <vm/pmap.h>
49 #include <vm/vm_extern.h>
50 
51 #include <sys/bus.h>
52 #include <machine/bus.h>
53 #include <sys/rman.h>
54 #include <machine/resource.h>
55 #include <machine/stdarg.h>
56 
57 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
58 #include <machine/intr_machdep.h>
59 #endif
60 
61 #include <sys/pciio.h>
62 #include <dev/pci/pcireg.h>
63 #include <dev/pci/pcivar.h>
64 #include <dev/pci/pci_private.h>
65 
66 #ifdef PCI_IOV
67 #include <sys/nv.h>
68 #include <dev/pci/pci_iov_private.h>
69 #endif
70 
71 #include <dev/usb/controller/xhcireg.h>
72 #include <dev/usb/controller/ehcireg.h>
73 #include <dev/usb/controller/ohcireg.h>
74 #include <dev/usb/controller/uhcireg.h>
75 
76 #include "pcib_if.h"
77 #include "pci_if.h"
78 
79 #define	PCIR_IS_BIOS(cfg, reg)						\
80 	(((cfg)->hdrtype == PCIM_HDRTYPE_NORMAL && reg == PCIR_BIOS) ||	\
81 	 ((cfg)->hdrtype == PCIM_HDRTYPE_BRIDGE && reg == PCIR_BIOS_1))
82 
83 static int		pci_has_quirk(uint32_t devid, int quirk);
84 static pci_addr_t	pci_mapbase(uint64_t mapreg);
85 static const char	*pci_maptype(uint64_t mapreg);
86 static int		pci_maprange(uint64_t mapreg);
87 static pci_addr_t	pci_rombase(uint64_t mapreg);
88 static int		pci_romsize(uint64_t testval);
89 static void		pci_fixancient(pcicfgregs *cfg);
90 static int		pci_printf(pcicfgregs *cfg, const char *fmt, ...);
91 
92 static int		pci_porten(device_t dev);
93 static int		pci_memen(device_t dev);
94 static void		pci_assign_interrupt(device_t bus, device_t dev,
95 			    int force_route);
96 static int		pci_add_map(device_t bus, device_t dev, int reg,
97 			    struct resource_list *rl, int force, int prefetch);
98 static int		pci_probe(device_t dev);
99 static int		pci_attach(device_t dev);
100 static int		pci_detach(device_t dev);
101 static void		pci_load_vendor_data(void);
102 static int		pci_describe_parse_line(char **ptr, int *vendor,
103 			    int *device, char **desc);
104 static char		*pci_describe_device(device_t dev);
105 static int		pci_modevent(module_t mod, int what, void *arg);
106 static void		pci_hdrtypedata(device_t pcib, int b, int s, int f,
107 			    pcicfgregs *cfg);
108 static void		pci_read_cap(device_t pcib, pcicfgregs *cfg);
109 static int		pci_read_vpd_reg(device_t pcib, pcicfgregs *cfg,
110 			    int reg, uint32_t *data);
111 #if 0
112 static int		pci_write_vpd_reg(device_t pcib, pcicfgregs *cfg,
113 			    int reg, uint32_t data);
114 #endif
115 static void		pci_read_vpd(device_t pcib, pcicfgregs *cfg);
116 static void		pci_mask_msix(device_t dev, u_int index);
117 static void		pci_unmask_msix(device_t dev, u_int index);
118 static int		pci_msi_blacklisted(void);
119 static int		pci_msix_blacklisted(void);
120 static void		pci_resume_msi(device_t dev);
121 static void		pci_resume_msix(device_t dev);
122 static int		pci_remap_intr_method(device_t bus, device_t dev,
123 			    u_int irq);
124 
125 static int		pci_get_id_method(device_t dev, device_t child,
126 			    enum pci_id_type type, uintptr_t *rid);
127 
128 static struct pci_devinfo * pci_fill_devinfo(device_t pcib, device_t bus, int d,
129     int b, int s, int f, uint16_t vid, uint16_t did);
130 
131 static device_method_t pci_methods[] = {
132 	/* Device interface */
133 	DEVMETHOD(device_probe,		pci_probe),
134 	DEVMETHOD(device_attach,	pci_attach),
135 	DEVMETHOD(device_detach,	pci_detach),
136 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
137 	DEVMETHOD(device_suspend,	bus_generic_suspend),
138 	DEVMETHOD(device_resume,	pci_resume),
139 
140 	/* Bus interface */
141 	DEVMETHOD(bus_print_child,	pci_print_child),
142 	DEVMETHOD(bus_probe_nomatch,	pci_probe_nomatch),
143 	DEVMETHOD(bus_read_ivar,	pci_read_ivar),
144 	DEVMETHOD(bus_write_ivar,	pci_write_ivar),
145 	DEVMETHOD(bus_driver_added,	pci_driver_added),
146 	DEVMETHOD(bus_setup_intr,	pci_setup_intr),
147 	DEVMETHOD(bus_teardown_intr,	pci_teardown_intr),
148 
149 	DEVMETHOD(bus_get_dma_tag,	pci_get_dma_tag),
150 	DEVMETHOD(bus_get_resource_list,pci_get_resource_list),
151 	DEVMETHOD(bus_set_resource,	bus_generic_rl_set_resource),
152 	DEVMETHOD(bus_get_resource,	bus_generic_rl_get_resource),
153 	DEVMETHOD(bus_delete_resource,	pci_delete_resource),
154 	DEVMETHOD(bus_alloc_resource,	pci_alloc_resource),
155 	DEVMETHOD(bus_adjust_resource,	bus_generic_adjust_resource),
156 	DEVMETHOD(bus_release_resource,	pci_release_resource),
157 	DEVMETHOD(bus_activate_resource, pci_activate_resource),
158 	DEVMETHOD(bus_deactivate_resource, pci_deactivate_resource),
159 	DEVMETHOD(bus_child_deleted,	pci_child_deleted),
160 	DEVMETHOD(bus_child_detached,	pci_child_detached),
161 	DEVMETHOD(bus_child_pnpinfo_str, pci_child_pnpinfo_str_method),
162 	DEVMETHOD(bus_child_location_str, pci_child_location_str_method),
163 	DEVMETHOD(bus_remap_intr,	pci_remap_intr_method),
164 	DEVMETHOD(bus_suspend_child,	pci_suspend_child),
165 	DEVMETHOD(bus_resume_child,	pci_resume_child),
166 	DEVMETHOD(bus_rescan,		pci_rescan_method),
167 
168 	/* PCI interface */
169 	DEVMETHOD(pci_read_config,	pci_read_config_method),
170 	DEVMETHOD(pci_write_config,	pci_write_config_method),
171 	DEVMETHOD(pci_enable_busmaster,	pci_enable_busmaster_method),
172 	DEVMETHOD(pci_disable_busmaster, pci_disable_busmaster_method),
173 	DEVMETHOD(pci_enable_io,	pci_enable_io_method),
174 	DEVMETHOD(pci_disable_io,	pci_disable_io_method),
175 	DEVMETHOD(pci_get_vpd_ident,	pci_get_vpd_ident_method),
176 	DEVMETHOD(pci_get_vpd_readonly,	pci_get_vpd_readonly_method),
177 	DEVMETHOD(pci_get_powerstate,	pci_get_powerstate_method),
178 	DEVMETHOD(pci_set_powerstate,	pci_set_powerstate_method),
179 	DEVMETHOD(pci_assign_interrupt,	pci_assign_interrupt_method),
180 	DEVMETHOD(pci_find_cap,		pci_find_cap_method),
181 	DEVMETHOD(pci_find_extcap,	pci_find_extcap_method),
182 	DEVMETHOD(pci_find_htcap,	pci_find_htcap_method),
183 	DEVMETHOD(pci_alloc_msi,	pci_alloc_msi_method),
184 	DEVMETHOD(pci_alloc_msix,	pci_alloc_msix_method),
185 	DEVMETHOD(pci_enable_msi,	pci_enable_msi_method),
186 	DEVMETHOD(pci_enable_msix,	pci_enable_msix_method),
187 	DEVMETHOD(pci_disable_msi,	pci_disable_msi_method),
188 	DEVMETHOD(pci_remap_msix,	pci_remap_msix_method),
189 	DEVMETHOD(pci_release_msi,	pci_release_msi_method),
190 	DEVMETHOD(pci_msi_count,	pci_msi_count_method),
191 	DEVMETHOD(pci_msix_count,	pci_msix_count_method),
192 	DEVMETHOD(pci_msix_pba_bar,	pci_msix_pba_bar_method),
193 	DEVMETHOD(pci_msix_table_bar,	pci_msix_table_bar_method),
194 	DEVMETHOD(pci_get_id,		pci_get_id_method),
195 	DEVMETHOD(pci_alloc_devinfo,	pci_alloc_devinfo_method),
196 	DEVMETHOD(pci_child_added,	pci_child_added_method),
197 #ifdef PCI_IOV
198 	DEVMETHOD(pci_iov_attach,	pci_iov_attach_method),
199 	DEVMETHOD(pci_iov_detach,	pci_iov_detach_method),
200 	DEVMETHOD(pci_create_iov_child,	pci_create_iov_child_method),
201 #endif
202 
203 	DEVMETHOD_END
204 };
205 
206 DEFINE_CLASS_0(pci, pci_driver, pci_methods, sizeof(struct pci_softc));
207 
208 static devclass_t pci_devclass;
209 DRIVER_MODULE(pci, pcib, pci_driver, pci_devclass, pci_modevent, NULL);
210 MODULE_VERSION(pci, 1);
211 
212 static char	*pci_vendordata;
213 static size_t	pci_vendordata_size;
214 
215 struct pci_quirk {
216 	uint32_t devid;	/* Vendor/device of the card */
217 	int	type;
218 #define	PCI_QUIRK_MAP_REG	1 /* PCI map register in weird place */
219 #define	PCI_QUIRK_DISABLE_MSI	2 /* Neither MSI nor MSI-X work */
220 #define	PCI_QUIRK_ENABLE_MSI_VM	3 /* Older chipset in VM where MSI works */
221 #define	PCI_QUIRK_UNMAP_REG	4 /* Ignore PCI map register */
222 #define	PCI_QUIRK_DISABLE_MSIX	5 /* MSI-X doesn't work */
223 #define	PCI_QUIRK_MSI_INTX_BUG	6 /* PCIM_CMD_INTxDIS disables MSI */
224 	int	arg1;
225 	int	arg2;
226 };
227 
228 static const struct pci_quirk pci_quirks[] = {
229 	/* The Intel 82371AB and 82443MX have a map register at offset 0x90. */
230 	{ 0x71138086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
231 	{ 0x719b8086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
232 	/* As does the Serverworks OSB4 (the SMBus mapping register) */
233 	{ 0x02001166, PCI_QUIRK_MAP_REG,	0x90,	 0 },
234 
235 	/*
236 	 * MSI doesn't work with the ServerWorks CNB20-HE Host Bridge
237 	 * or the CMIC-SL (AKA ServerWorks GC_LE).
238 	 */
239 	{ 0x00141166, PCI_QUIRK_DISABLE_MSI,	0,	0 },
240 	{ 0x00171166, PCI_QUIRK_DISABLE_MSI,	0,	0 },
241 
242 	/*
243 	 * MSI doesn't work on earlier Intel chipsets including
244 	 * E7500, E7501, E7505, 845, 865, 875/E7210, and 855.
245 	 */
246 	{ 0x25408086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
247 	{ 0x254c8086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
248 	{ 0x25508086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
249 	{ 0x25608086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
250 	{ 0x25708086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
251 	{ 0x25788086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
252 	{ 0x35808086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
253 
254 	/*
255 	 * MSI doesn't work with devices behind the AMD 8131 HT-PCIX
256 	 * bridge.
257 	 */
258 	{ 0x74501022, PCI_QUIRK_DISABLE_MSI,	0,	0 },
259 
260 	/*
261 	 * MSI-X allocation doesn't work properly for devices passed through
262 	 * by VMware up to at least ESXi 5.1.
263 	 */
264 	{ 0x079015ad, PCI_QUIRK_DISABLE_MSIX,	0,	0 }, /* PCI/PCI-X */
265 	{ 0x07a015ad, PCI_QUIRK_DISABLE_MSIX,	0,	0 }, /* PCIe */
266 
267 	/*
268 	 * Some virtualization environments emulate an older chipset
269 	 * but support MSI just fine.  QEMU uses the Intel 82440.
270 	 */
271 	{ 0x12378086, PCI_QUIRK_ENABLE_MSI_VM,	0,	0 },
272 
273 	/*
274 	 * HPET MMIO base address may appear in Bar1 for AMD SB600 SMBus
275 	 * controller depending on SoftPciRst register (PM_IO 0x55 [7]).
276 	 * It prevents us from attaching hpet(4) when the bit is unset.
277 	 * Note this quirk only affects SB600 revision A13 and earlier.
278 	 * For SB600 A21 and later, firmware must set the bit to hide it.
279 	 * For SB700 and later, it is unused and hardcoded to zero.
280 	 */
281 	{ 0x43851002, PCI_QUIRK_UNMAP_REG,	0x14,	0 },
282 
283 	/*
284 	 * Atheros AR8161/AR8162/E2200/E2400/E2500 Ethernet controllers have
285 	 * a bug that MSI interrupt does not assert if PCIM_CMD_INTxDIS bit
286 	 * of the command register is set.
287 	 */
288 	{ 0x10911969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
289 	{ 0xE0911969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
290 	{ 0xE0A11969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
291 	{ 0xE0B11969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
292 	{ 0x10901969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
293 
294 	/*
295 	 * Broadcom BCM5714(S)/BCM5715(S)/BCM5780(S) Ethernet MACs don't
296 	 * issue MSI interrupts with PCIM_CMD_INTxDIS set either.
297 	 */
298 	{ 0x166814e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5714 */
299 	{ 0x166914e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5714S */
300 	{ 0x166a14e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5780 */
301 	{ 0x166b14e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5780S */
302 	{ 0x167814e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5715 */
303 	{ 0x167914e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5715S */
304 
305 	{ 0 }
306 };
307 
308 /* map register information */
309 #define	PCI_MAPMEM	0x01	/* memory map */
310 #define	PCI_MAPMEMP	0x02	/* prefetchable memory map */
311 #define	PCI_MAPPORT	0x04	/* port map */
312 
313 struct devlist pci_devq;
314 uint32_t pci_generation;
315 uint32_t pci_numdevs = 0;
316 static int pcie_chipset, pcix_chipset;
317 
318 /* sysctl vars */
319 SYSCTL_NODE(_hw, OID_AUTO, pci, CTLFLAG_RD, 0, "PCI bus tuning parameters");
320 
321 static int pci_enable_io_modes = 1;
322 SYSCTL_INT(_hw_pci, OID_AUTO, enable_io_modes, CTLFLAG_RWTUN,
323     &pci_enable_io_modes, 1,
324     "Enable I/O and memory bits in the config register.  Some BIOSes do not"
325     " enable these bits correctly.  We'd like to do this all the time, but"
326     " there are some peripherals that this causes problems with.");
327 
328 static int pci_do_realloc_bars = 0;
329 SYSCTL_INT(_hw_pci, OID_AUTO, realloc_bars, CTLFLAG_RWTUN,
330     &pci_do_realloc_bars, 0,
331     "Attempt to allocate a new range for any BARs whose original "
332     "firmware-assigned ranges fail to allocate during the initial device scan.");
333 
334 static int pci_do_power_nodriver = 0;
335 SYSCTL_INT(_hw_pci, OID_AUTO, do_power_nodriver, CTLFLAG_RWTUN,
336     &pci_do_power_nodriver, 0,
337     "Place a function into D3 state when no driver attaches to it.  0 means"
338     " disable.  1 means conservatively place devices into D3 state.  2 means"
339     " aggressively place devices into D3 state.  3 means put absolutely"
340     " everything in D3 state.");
341 
342 int pci_do_power_resume = 1;
343 SYSCTL_INT(_hw_pci, OID_AUTO, do_power_resume, CTLFLAG_RWTUN,
344     &pci_do_power_resume, 1,
345   "Transition from D3 -> D0 on resume.");
346 
347 int pci_do_power_suspend = 1;
348 SYSCTL_INT(_hw_pci, OID_AUTO, do_power_suspend, CTLFLAG_RWTUN,
349     &pci_do_power_suspend, 1,
350   "Transition from D0 -> D3 on suspend.");
351 
352 static int pci_do_msi = 1;
353 SYSCTL_INT(_hw_pci, OID_AUTO, enable_msi, CTLFLAG_RWTUN, &pci_do_msi, 1,
354     "Enable support for MSI interrupts");
355 
356 static int pci_do_msix = 1;
357 SYSCTL_INT(_hw_pci, OID_AUTO, enable_msix, CTLFLAG_RWTUN, &pci_do_msix, 1,
358     "Enable support for MSI-X interrupts");
359 
360 static int pci_msix_rewrite_table = 0;
361 SYSCTL_INT(_hw_pci, OID_AUTO, msix_rewrite_table, CTLFLAG_RWTUN,
362     &pci_msix_rewrite_table, 0,
363     "Rewrite entire MSI-X table when updating MSI-X entries");
364 
365 static int pci_honor_msi_blacklist = 1;
366 SYSCTL_INT(_hw_pci, OID_AUTO, honor_msi_blacklist, CTLFLAG_RDTUN,
367     &pci_honor_msi_blacklist, 1, "Honor chipset blacklist for MSI/MSI-X");
368 
369 #if defined(__i386__) || defined(__amd64__)
370 static int pci_usb_takeover = 1;
371 #else
372 static int pci_usb_takeover = 0;
373 #endif
374 SYSCTL_INT(_hw_pci, OID_AUTO, usb_early_takeover, CTLFLAG_RDTUN,
375     &pci_usb_takeover, 1,
376     "Enable early takeover of USB controllers. Disable this if you depend on"
377     " BIOS emulation of USB devices, that is you use USB devices (like"
378     " keyboard or mouse) but do not load USB drivers");
379 
380 static int pci_clear_bars;
381 SYSCTL_INT(_hw_pci, OID_AUTO, clear_bars, CTLFLAG_RDTUN, &pci_clear_bars, 0,
382     "Ignore firmware-assigned resources for BARs.");
383 
384 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
385 static int pci_clear_buses;
386 SYSCTL_INT(_hw_pci, OID_AUTO, clear_buses, CTLFLAG_RDTUN, &pci_clear_buses, 0,
387     "Ignore firmware-assigned bus numbers.");
388 #endif
389 
390 static int pci_enable_ari = 1;
391 SYSCTL_INT(_hw_pci, OID_AUTO, enable_ari, CTLFLAG_RDTUN, &pci_enable_ari,
392     0, "Enable support for PCIe Alternative RID Interpretation");
393 
394 static int
395 pci_has_quirk(uint32_t devid, int quirk)
396 {
397 	const struct pci_quirk *q;
398 
399 	for (q = &pci_quirks[0]; q->devid; q++) {
400 		if (q->devid == devid && q->type == quirk)
401 			return (1);
402 	}
403 	return (0);
404 }
405 
406 /* Find a device_t by bus/slot/function in domain 0 */
407 
408 device_t
409 pci_find_bsf(uint8_t bus, uint8_t slot, uint8_t func)
410 {
411 
412 	return (pci_find_dbsf(0, bus, slot, func));
413 }
414 
415 /* Find a device_t by domain/bus/slot/function */
416 
417 device_t
418 pci_find_dbsf(uint32_t domain, uint8_t bus, uint8_t slot, uint8_t func)
419 {
420 	struct pci_devinfo *dinfo;
421 
422 	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
423 		if ((dinfo->cfg.domain == domain) &&
424 		    (dinfo->cfg.bus == bus) &&
425 		    (dinfo->cfg.slot == slot) &&
426 		    (dinfo->cfg.func == func)) {
427 			return (dinfo->cfg.dev);
428 		}
429 	}
430 
431 	return (NULL);
432 }
433 
434 /* Find a device_t by vendor/device ID */
435 
436 device_t
437 pci_find_device(uint16_t vendor, uint16_t device)
438 {
439 	struct pci_devinfo *dinfo;
440 
441 	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
442 		if ((dinfo->cfg.vendor == vendor) &&
443 		    (dinfo->cfg.device == device)) {
444 			return (dinfo->cfg.dev);
445 		}
446 	}
447 
448 	return (NULL);
449 }
450 
451 device_t
452 pci_find_class(uint8_t class, uint8_t subclass)
453 {
454 	struct pci_devinfo *dinfo;
455 
456 	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
457 		if (dinfo->cfg.baseclass == class &&
458 		    dinfo->cfg.subclass == subclass) {
459 			return (dinfo->cfg.dev);
460 		}
461 	}
462 
463 	return (NULL);
464 }
465 
466 static int
467 pci_printf(pcicfgregs *cfg, const char *fmt, ...)
468 {
469 	va_list ap;
470 	int retval;
471 
472 	retval = printf("pci%d:%d:%d:%d: ", cfg->domain, cfg->bus, cfg->slot,
473 	    cfg->func);
474 	va_start(ap, fmt);
475 	retval += vprintf(fmt, ap);
476 	va_end(ap);
477 	return (retval);
478 }
479 
480 /* return base address of memory or port map */
481 
482 static pci_addr_t
483 pci_mapbase(uint64_t mapreg)
484 {
485 
486 	if (PCI_BAR_MEM(mapreg))
487 		return (mapreg & PCIM_BAR_MEM_BASE);
488 	else
489 		return (mapreg & PCIM_BAR_IO_BASE);
490 }
491 
492 /* return map type of memory or port map */
493 
494 static const char *
495 pci_maptype(uint64_t mapreg)
496 {
497 
498 	if (PCI_BAR_IO(mapreg))
499 		return ("I/O Port");
500 	if (mapreg & PCIM_BAR_MEM_PREFETCH)
501 		return ("Prefetchable Memory");
502 	return ("Memory");
503 }
504 
505 /* return log2 of map size decoded for memory or port map */
506 
507 int
508 pci_mapsize(uint64_t testval)
509 {
510 	int ln2size;
511 
512 	testval = pci_mapbase(testval);
513 	ln2size = 0;
514 	if (testval != 0) {
515 		while ((testval & 1) == 0)
516 		{
517 			ln2size++;
518 			testval >>= 1;
519 		}
520 	}
521 	return (ln2size);
522 }
523 
524 /* return base address of device ROM */
525 
526 static pci_addr_t
527 pci_rombase(uint64_t mapreg)
528 {
529 
530 	return (mapreg & PCIM_BIOS_ADDR_MASK);
531 }
532 
533 /* return log2 of map size decided for device ROM */
534 
535 static int
536 pci_romsize(uint64_t testval)
537 {
538 	int ln2size;
539 
540 	testval = pci_rombase(testval);
541 	ln2size = 0;
542 	if (testval != 0) {
543 		while ((testval & 1) == 0)
544 		{
545 			ln2size++;
546 			testval >>= 1;
547 		}
548 	}
549 	return (ln2size);
550 }
551 
552 /* return log2 of address range supported by map register */
553 
554 static int
555 pci_maprange(uint64_t mapreg)
556 {
557 	int ln2range = 0;
558 
559 	if (PCI_BAR_IO(mapreg))
560 		ln2range = 32;
561 	else
562 		switch (mapreg & PCIM_BAR_MEM_TYPE) {
563 		case PCIM_BAR_MEM_32:
564 			ln2range = 32;
565 			break;
566 		case PCIM_BAR_MEM_1MB:
567 			ln2range = 20;
568 			break;
569 		case PCIM_BAR_MEM_64:
570 			ln2range = 64;
571 			break;
572 		}
573 	return (ln2range);
574 }
575 
576 /* adjust some values from PCI 1.0 devices to match 2.0 standards ... */
577 
578 static void
579 pci_fixancient(pcicfgregs *cfg)
580 {
581 	if ((cfg->hdrtype & PCIM_HDRTYPE) != PCIM_HDRTYPE_NORMAL)
582 		return;
583 
584 	/* PCI to PCI bridges use header type 1 */
585 	if (cfg->baseclass == PCIC_BRIDGE && cfg->subclass == PCIS_BRIDGE_PCI)
586 		cfg->hdrtype = PCIM_HDRTYPE_BRIDGE;
587 }
588 
589 /* extract header type specific config data */
590 
591 static void
592 pci_hdrtypedata(device_t pcib, int b, int s, int f, pcicfgregs *cfg)
593 {
594 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, b, s, f, n, w)
595 	switch (cfg->hdrtype & PCIM_HDRTYPE) {
596 	case PCIM_HDRTYPE_NORMAL:
597 		cfg->subvendor      = REG(PCIR_SUBVEND_0, 2);
598 		cfg->subdevice      = REG(PCIR_SUBDEV_0, 2);
599 		cfg->mingnt         = REG(PCIR_MINGNT, 1);
600 		cfg->maxlat         = REG(PCIR_MAXLAT, 1);
601 		cfg->nummaps	    = PCI_MAXMAPS_0;
602 		break;
603 	case PCIM_HDRTYPE_BRIDGE:
604 		cfg->bridge.br_seclat = REG(PCIR_SECLAT_1, 1);
605 		cfg->bridge.br_subbus = REG(PCIR_SUBBUS_1, 1);
606 		cfg->bridge.br_secbus = REG(PCIR_SECBUS_1, 1);
607 		cfg->bridge.br_pribus = REG(PCIR_PRIBUS_1, 1);
608 		cfg->bridge.br_control = REG(PCIR_BRIDGECTL_1, 2);
609 		cfg->nummaps	    = PCI_MAXMAPS_1;
610 		break;
611 	case PCIM_HDRTYPE_CARDBUS:
612 		cfg->bridge.br_seclat = REG(PCIR_SECLAT_2, 1);
613 		cfg->bridge.br_subbus = REG(PCIR_SUBBUS_2, 1);
614 		cfg->bridge.br_secbus = REG(PCIR_SECBUS_2, 1);
615 		cfg->bridge.br_pribus = REG(PCIR_PRIBUS_2, 1);
616 		cfg->bridge.br_control = REG(PCIR_BRIDGECTL_2, 2);
617 		cfg->subvendor      = REG(PCIR_SUBVEND_2, 2);
618 		cfg->subdevice      = REG(PCIR_SUBDEV_2, 2);
619 		cfg->nummaps	    = PCI_MAXMAPS_2;
620 		break;
621 	}
622 #undef REG
623 }
624 
625 /* read configuration header into pcicfgregs structure */
626 struct pci_devinfo *
627 pci_read_device(device_t pcib, device_t bus, int d, int b, int s, int f)
628 {
629 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, b, s, f, n, w)
630 	uint16_t vid, did;
631 
632 	vid = REG(PCIR_VENDOR, 2);
633 	did = REG(PCIR_DEVICE, 2);
634 	if (vid != 0xffff)
635 		return (pci_fill_devinfo(pcib, bus, d, b, s, f, vid, did));
636 
637 	return (NULL);
638 }
639 
640 struct pci_devinfo *
641 pci_alloc_devinfo_method(device_t dev)
642 {
643 
644 	return (malloc(sizeof(struct pci_devinfo), M_DEVBUF,
645 	    M_WAITOK | M_ZERO));
646 }
647 
648 static struct pci_devinfo *
649 pci_fill_devinfo(device_t pcib, device_t bus, int d, int b, int s, int f,
650     uint16_t vid, uint16_t did)
651 {
652 	struct pci_devinfo *devlist_entry;
653 	pcicfgregs *cfg;
654 
655 	devlist_entry = PCI_ALLOC_DEVINFO(bus);
656 
657 	cfg = &devlist_entry->cfg;
658 
659 	cfg->domain		= d;
660 	cfg->bus		= b;
661 	cfg->slot		= s;
662 	cfg->func		= f;
663 	cfg->vendor		= vid;
664 	cfg->device		= did;
665 	cfg->cmdreg		= REG(PCIR_COMMAND, 2);
666 	cfg->statreg		= REG(PCIR_STATUS, 2);
667 	cfg->baseclass		= REG(PCIR_CLASS, 1);
668 	cfg->subclass		= REG(PCIR_SUBCLASS, 1);
669 	cfg->progif		= REG(PCIR_PROGIF, 1);
670 	cfg->revid		= REG(PCIR_REVID, 1);
671 	cfg->hdrtype		= REG(PCIR_HDRTYPE, 1);
672 	cfg->cachelnsz		= REG(PCIR_CACHELNSZ, 1);
673 	cfg->lattimer		= REG(PCIR_LATTIMER, 1);
674 	cfg->intpin		= REG(PCIR_INTPIN, 1);
675 	cfg->intline		= REG(PCIR_INTLINE, 1);
676 
677 	cfg->mfdev		= (cfg->hdrtype & PCIM_MFDEV) != 0;
678 	cfg->hdrtype		&= ~PCIM_MFDEV;
679 	STAILQ_INIT(&cfg->maps);
680 
681 	cfg->iov		= NULL;
682 
683 	pci_fixancient(cfg);
684 	pci_hdrtypedata(pcib, b, s, f, cfg);
685 
686 	if (REG(PCIR_STATUS, 2) & PCIM_STATUS_CAPPRESENT)
687 		pci_read_cap(pcib, cfg);
688 
689 	STAILQ_INSERT_TAIL(&pci_devq, devlist_entry, pci_links);
690 
691 	devlist_entry->conf.pc_sel.pc_domain = cfg->domain;
692 	devlist_entry->conf.pc_sel.pc_bus = cfg->bus;
693 	devlist_entry->conf.pc_sel.pc_dev = cfg->slot;
694 	devlist_entry->conf.pc_sel.pc_func = cfg->func;
695 	devlist_entry->conf.pc_hdr = cfg->hdrtype;
696 
697 	devlist_entry->conf.pc_subvendor = cfg->subvendor;
698 	devlist_entry->conf.pc_subdevice = cfg->subdevice;
699 	devlist_entry->conf.pc_vendor = cfg->vendor;
700 	devlist_entry->conf.pc_device = cfg->device;
701 
702 	devlist_entry->conf.pc_class = cfg->baseclass;
703 	devlist_entry->conf.pc_subclass = cfg->subclass;
704 	devlist_entry->conf.pc_progif = cfg->progif;
705 	devlist_entry->conf.pc_revid = cfg->revid;
706 
707 	pci_numdevs++;
708 	pci_generation++;
709 
710 	return (devlist_entry);
711 }
712 #undef REG
713 
714 static void
715 pci_ea_fill_info(device_t pcib, pcicfgregs *cfg)
716 {
717 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, \
718     cfg->ea.ea_location + (n), w)
719 	int num_ent;
720 	int ptr;
721 	int a, b;
722 	uint32_t val;
723 	int ent_size;
724 	uint32_t dw[4];
725 	uint64_t base, max_offset;
726 	struct pci_ea_entry *eae;
727 
728 	if (cfg->ea.ea_location == 0)
729 		return;
730 
731 	STAILQ_INIT(&cfg->ea.ea_entries);
732 
733 	/* Determine the number of entries */
734 	num_ent = REG(PCIR_EA_NUM_ENT, 2);
735 	num_ent &= PCIM_EA_NUM_ENT_MASK;
736 
737 	/* Find the first entry to care of */
738 	ptr = PCIR_EA_FIRST_ENT;
739 
740 	/* Skip DWORD 2 for type 1 functions */
741 	if ((cfg->hdrtype & PCIM_HDRTYPE) == PCIM_HDRTYPE_BRIDGE)
742 		ptr += 4;
743 
744 	for (a = 0; a < num_ent; a++) {
745 
746 		eae = malloc(sizeof(*eae), M_DEVBUF, M_WAITOK | M_ZERO);
747 		eae->eae_cfg_offset = cfg->ea.ea_location + ptr;
748 
749 		/* Read a number of dwords in the entry */
750 		val = REG(ptr, 4);
751 		ptr += 4;
752 		ent_size = (val & PCIM_EA_ES);
753 
754 		for (b = 0; b < ent_size; b++) {
755 			dw[b] = REG(ptr, 4);
756 			ptr += 4;
757 		}
758 
759 		eae->eae_flags = val;
760 		eae->eae_bei = (PCIM_EA_BEI & val) >> PCIM_EA_BEI_OFFSET;
761 
762 		base = dw[0] & PCIM_EA_FIELD_MASK;
763 		max_offset = dw[1] | ~PCIM_EA_FIELD_MASK;
764 		b = 2;
765 		if (((dw[0] & PCIM_EA_IS_64) != 0) && (b < ent_size)) {
766 			base |= (uint64_t)dw[b] << 32UL;
767 			b++;
768 		}
769 		if (((dw[1] & PCIM_EA_IS_64) != 0)
770 		    && (b < ent_size)) {
771 			max_offset |= (uint64_t)dw[b] << 32UL;
772 			b++;
773 		}
774 
775 		eae->eae_base = base;
776 		eae->eae_max_offset = max_offset;
777 
778 		STAILQ_INSERT_TAIL(&cfg->ea.ea_entries, eae, eae_link);
779 
780 		if (bootverbose) {
781 			printf("PCI(EA) dev %04x:%04x, bei %d, flags #%x, base #%jx, max_offset #%jx\n",
782 			    cfg->vendor, cfg->device, eae->eae_bei, eae->eae_flags,
783 			    (uintmax_t)eae->eae_base, (uintmax_t)eae->eae_max_offset);
784 		}
785 	}
786 }
787 #undef REG
788 
789 static void
790 pci_read_cap(device_t pcib, pcicfgregs *cfg)
791 {
792 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, n, w)
793 #define	WREG(n, v, w)	PCIB_WRITE_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, n, v, w)
794 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
795 	uint64_t addr;
796 #endif
797 	uint32_t val;
798 	int	ptr, nextptr, ptrptr;
799 
800 	switch (cfg->hdrtype & PCIM_HDRTYPE) {
801 	case PCIM_HDRTYPE_NORMAL:
802 	case PCIM_HDRTYPE_BRIDGE:
803 		ptrptr = PCIR_CAP_PTR;
804 		break;
805 	case PCIM_HDRTYPE_CARDBUS:
806 		ptrptr = PCIR_CAP_PTR_2;	/* cardbus capabilities ptr */
807 		break;
808 	default:
809 		return;		/* no extended capabilities support */
810 	}
811 	nextptr = REG(ptrptr, 1);	/* sanity check? */
812 
813 	/*
814 	 * Read capability entries.
815 	 */
816 	while (nextptr != 0) {
817 		/* Sanity check */
818 		if (nextptr > 255) {
819 			printf("illegal PCI extended capability offset %d\n",
820 			    nextptr);
821 			return;
822 		}
823 		/* Find the next entry */
824 		ptr = nextptr;
825 		nextptr = REG(ptr + PCICAP_NEXTPTR, 1);
826 
827 		/* Process this entry */
828 		switch (REG(ptr + PCICAP_ID, 1)) {
829 		case PCIY_PMG:		/* PCI power management */
830 			if (cfg->pp.pp_cap == 0) {
831 				cfg->pp.pp_cap = REG(ptr + PCIR_POWER_CAP, 2);
832 				cfg->pp.pp_status = ptr + PCIR_POWER_STATUS;
833 				cfg->pp.pp_bse = ptr + PCIR_POWER_BSE;
834 				if ((nextptr - ptr) > PCIR_POWER_DATA)
835 					cfg->pp.pp_data = ptr + PCIR_POWER_DATA;
836 			}
837 			break;
838 		case PCIY_HT:		/* HyperTransport */
839 			/* Determine HT-specific capability type. */
840 			val = REG(ptr + PCIR_HT_COMMAND, 2);
841 
842 			if ((val & 0xe000) == PCIM_HTCAP_SLAVE)
843 				cfg->ht.ht_slave = ptr;
844 
845 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
846 			switch (val & PCIM_HTCMD_CAP_MASK) {
847 			case PCIM_HTCAP_MSI_MAPPING:
848 				if (!(val & PCIM_HTCMD_MSI_FIXED)) {
849 					/* Sanity check the mapping window. */
850 					addr = REG(ptr + PCIR_HTMSI_ADDRESS_HI,
851 					    4);
852 					addr <<= 32;
853 					addr |= REG(ptr + PCIR_HTMSI_ADDRESS_LO,
854 					    4);
855 					if (addr != MSI_INTEL_ADDR_BASE)
856 						device_printf(pcib,
857 	    "HT device at pci%d:%d:%d:%d has non-default MSI window 0x%llx\n",
858 						    cfg->domain, cfg->bus,
859 						    cfg->slot, cfg->func,
860 						    (long long)addr);
861 				} else
862 					addr = MSI_INTEL_ADDR_BASE;
863 
864 				cfg->ht.ht_msimap = ptr;
865 				cfg->ht.ht_msictrl = val;
866 				cfg->ht.ht_msiaddr = addr;
867 				break;
868 			}
869 #endif
870 			break;
871 		case PCIY_MSI:		/* PCI MSI */
872 			cfg->msi.msi_location = ptr;
873 			cfg->msi.msi_ctrl = REG(ptr + PCIR_MSI_CTRL, 2);
874 			cfg->msi.msi_msgnum = 1 << ((cfg->msi.msi_ctrl &
875 						     PCIM_MSICTRL_MMC_MASK)>>1);
876 			break;
877 		case PCIY_MSIX:		/* PCI MSI-X */
878 			cfg->msix.msix_location = ptr;
879 			cfg->msix.msix_ctrl = REG(ptr + PCIR_MSIX_CTRL, 2);
880 			cfg->msix.msix_msgnum = (cfg->msix.msix_ctrl &
881 			    PCIM_MSIXCTRL_TABLE_SIZE) + 1;
882 			val = REG(ptr + PCIR_MSIX_TABLE, 4);
883 			cfg->msix.msix_table_bar = PCIR_BAR(val &
884 			    PCIM_MSIX_BIR_MASK);
885 			cfg->msix.msix_table_offset = val & ~PCIM_MSIX_BIR_MASK;
886 			val = REG(ptr + PCIR_MSIX_PBA, 4);
887 			cfg->msix.msix_pba_bar = PCIR_BAR(val &
888 			    PCIM_MSIX_BIR_MASK);
889 			cfg->msix.msix_pba_offset = val & ~PCIM_MSIX_BIR_MASK;
890 			break;
891 		case PCIY_VPD:		/* PCI Vital Product Data */
892 			cfg->vpd.vpd_reg = ptr;
893 			break;
894 		case PCIY_SUBVENDOR:
895 			/* Should always be true. */
896 			if ((cfg->hdrtype & PCIM_HDRTYPE) ==
897 			    PCIM_HDRTYPE_BRIDGE) {
898 				val = REG(ptr + PCIR_SUBVENDCAP_ID, 4);
899 				cfg->subvendor = val & 0xffff;
900 				cfg->subdevice = val >> 16;
901 			}
902 			break;
903 		case PCIY_PCIX:		/* PCI-X */
904 			/*
905 			 * Assume we have a PCI-X chipset if we have
906 			 * at least one PCI-PCI bridge with a PCI-X
907 			 * capability.  Note that some systems with
908 			 * PCI-express or HT chipsets might match on
909 			 * this check as well.
910 			 */
911 			if ((cfg->hdrtype & PCIM_HDRTYPE) ==
912 			    PCIM_HDRTYPE_BRIDGE)
913 				pcix_chipset = 1;
914 			cfg->pcix.pcix_location = ptr;
915 			break;
916 		case PCIY_EXPRESS:	/* PCI-express */
917 			/*
918 			 * Assume we have a PCI-express chipset if we have
919 			 * at least one PCI-express device.
920 			 */
921 			pcie_chipset = 1;
922 			cfg->pcie.pcie_location = ptr;
923 			val = REG(ptr + PCIER_FLAGS, 2);
924 			cfg->pcie.pcie_type = val & PCIEM_FLAGS_TYPE;
925 			break;
926 		case PCIY_EA:		/* Enhanced Allocation */
927 			cfg->ea.ea_location = ptr;
928 			pci_ea_fill_info(pcib, cfg);
929 			break;
930 		default:
931 			break;
932 		}
933 	}
934 
935 #if defined(__powerpc__)
936 	/*
937 	 * Enable the MSI mapping window for all HyperTransport
938 	 * slaves.  PCI-PCI bridges have their windows enabled via
939 	 * PCIB_MAP_MSI().
940 	 */
941 	if (cfg->ht.ht_slave != 0 && cfg->ht.ht_msimap != 0 &&
942 	    !(cfg->ht.ht_msictrl & PCIM_HTCMD_MSI_ENABLE)) {
943 		device_printf(pcib,
944 	    "Enabling MSI window for HyperTransport slave at pci%d:%d:%d:%d\n",
945 		    cfg->domain, cfg->bus, cfg->slot, cfg->func);
946 		 cfg->ht.ht_msictrl |= PCIM_HTCMD_MSI_ENABLE;
947 		 WREG(cfg->ht.ht_msimap + PCIR_HT_COMMAND, cfg->ht.ht_msictrl,
948 		     2);
949 	}
950 #endif
951 /* REG and WREG use carry through to next functions */
952 }
953 
954 /*
955  * PCI Vital Product Data
956  */
957 
958 #define	PCI_VPD_TIMEOUT		1000000
959 
960 static int
961 pci_read_vpd_reg(device_t pcib, pcicfgregs *cfg, int reg, uint32_t *data)
962 {
963 	int count = PCI_VPD_TIMEOUT;
964 
965 	KASSERT((reg & 3) == 0, ("VPD register must by 4 byte aligned"));
966 
967 	WREG(cfg->vpd.vpd_reg + PCIR_VPD_ADDR, reg, 2);
968 
969 	while ((REG(cfg->vpd.vpd_reg + PCIR_VPD_ADDR, 2) & 0x8000) != 0x8000) {
970 		if (--count < 0)
971 			return (ENXIO);
972 		DELAY(1);	/* limit looping */
973 	}
974 	*data = (REG(cfg->vpd.vpd_reg + PCIR_VPD_DATA, 4));
975 
976 	return (0);
977 }
978 
979 #if 0
980 static int
981 pci_write_vpd_reg(device_t pcib, pcicfgregs *cfg, int reg, uint32_t data)
982 {
983 	int count = PCI_VPD_TIMEOUT;
984 
985 	KASSERT((reg & 3) == 0, ("VPD register must by 4 byte aligned"));
986 
987 	WREG(cfg->vpd.vpd_reg + PCIR_VPD_DATA, data, 4);
988 	WREG(cfg->vpd.vpd_reg + PCIR_VPD_ADDR, reg | 0x8000, 2);
989 	while ((REG(cfg->vpd.vpd_reg + PCIR_VPD_ADDR, 2) & 0x8000) == 0x8000) {
990 		if (--count < 0)
991 			return (ENXIO);
992 		DELAY(1);	/* limit looping */
993 	}
994 
995 	return (0);
996 }
997 #endif
998 
999 #undef PCI_VPD_TIMEOUT
1000 
1001 struct vpd_readstate {
1002 	device_t	pcib;
1003 	pcicfgregs	*cfg;
1004 	uint32_t	val;
1005 	int		bytesinval;
1006 	int		off;
1007 	uint8_t		cksum;
1008 };
1009 
1010 static int
1011 vpd_nextbyte(struct vpd_readstate *vrs, uint8_t *data)
1012 {
1013 	uint32_t reg;
1014 	uint8_t byte;
1015 
1016 	if (vrs->bytesinval == 0) {
1017 		if (pci_read_vpd_reg(vrs->pcib, vrs->cfg, vrs->off, &reg))
1018 			return (ENXIO);
1019 		vrs->val = le32toh(reg);
1020 		vrs->off += 4;
1021 		byte = vrs->val & 0xff;
1022 		vrs->bytesinval = 3;
1023 	} else {
1024 		vrs->val = vrs->val >> 8;
1025 		byte = vrs->val & 0xff;
1026 		vrs->bytesinval--;
1027 	}
1028 
1029 	vrs->cksum += byte;
1030 	*data = byte;
1031 	return (0);
1032 }
1033 
1034 static void
1035 pci_read_vpd(device_t pcib, pcicfgregs *cfg)
1036 {
1037 	struct vpd_readstate vrs;
1038 	int state;
1039 	int name;
1040 	int remain;
1041 	int i;
1042 	int alloc, off;		/* alloc/off for RO/W arrays */
1043 	int cksumvalid;
1044 	int dflen;
1045 	uint8_t byte;
1046 	uint8_t byte2;
1047 
1048 	/* init vpd reader */
1049 	vrs.bytesinval = 0;
1050 	vrs.off = 0;
1051 	vrs.pcib = pcib;
1052 	vrs.cfg = cfg;
1053 	vrs.cksum = 0;
1054 
1055 	state = 0;
1056 	name = remain = i = 0;	/* shut up stupid gcc */
1057 	alloc = off = 0;	/* shut up stupid gcc */
1058 	dflen = 0;		/* shut up stupid gcc */
1059 	cksumvalid = -1;
1060 	while (state >= 0) {
1061 		if (vpd_nextbyte(&vrs, &byte)) {
1062 			state = -2;
1063 			break;
1064 		}
1065 #if 0
1066 		printf("vpd: val: %#x, off: %d, bytesinval: %d, byte: %#hhx, " \
1067 		    "state: %d, remain: %d, name: %#x, i: %d\n", vrs.val,
1068 		    vrs.off, vrs.bytesinval, byte, state, remain, name, i);
1069 #endif
1070 		switch (state) {
1071 		case 0:		/* item name */
1072 			if (byte & 0x80) {
1073 				if (vpd_nextbyte(&vrs, &byte2)) {
1074 					state = -2;
1075 					break;
1076 				}
1077 				remain = byte2;
1078 				if (vpd_nextbyte(&vrs, &byte2)) {
1079 					state = -2;
1080 					break;
1081 				}
1082 				remain |= byte2 << 8;
1083 				if (remain > (0x7f*4 - vrs.off)) {
1084 					state = -1;
1085 					pci_printf(cfg,
1086 					    "invalid VPD data, remain %#x\n",
1087 					    remain);
1088 				}
1089 				name = byte & 0x7f;
1090 			} else {
1091 				remain = byte & 0x7;
1092 				name = (byte >> 3) & 0xf;
1093 			}
1094 			switch (name) {
1095 			case 0x2:	/* String */
1096 				cfg->vpd.vpd_ident = malloc(remain + 1,
1097 				    M_DEVBUF, M_WAITOK);
1098 				i = 0;
1099 				state = 1;
1100 				break;
1101 			case 0xf:	/* End */
1102 				state = -1;
1103 				break;
1104 			case 0x10:	/* VPD-R */
1105 				alloc = 8;
1106 				off = 0;
1107 				cfg->vpd.vpd_ros = malloc(alloc *
1108 				    sizeof(*cfg->vpd.vpd_ros), M_DEVBUF,
1109 				    M_WAITOK | M_ZERO);
1110 				state = 2;
1111 				break;
1112 			case 0x11:	/* VPD-W */
1113 				alloc = 8;
1114 				off = 0;
1115 				cfg->vpd.vpd_w = malloc(alloc *
1116 				    sizeof(*cfg->vpd.vpd_w), M_DEVBUF,
1117 				    M_WAITOK | M_ZERO);
1118 				state = 5;
1119 				break;
1120 			default:	/* Invalid data, abort */
1121 				state = -1;
1122 				break;
1123 			}
1124 			break;
1125 
1126 		case 1:	/* Identifier String */
1127 			cfg->vpd.vpd_ident[i++] = byte;
1128 			remain--;
1129 			if (remain == 0)  {
1130 				cfg->vpd.vpd_ident[i] = '\0';
1131 				state = 0;
1132 			}
1133 			break;
1134 
1135 		case 2:	/* VPD-R Keyword Header */
1136 			if (off == alloc) {
1137 				cfg->vpd.vpd_ros = reallocf(cfg->vpd.vpd_ros,
1138 				    (alloc *= 2) * sizeof(*cfg->vpd.vpd_ros),
1139 				    M_DEVBUF, M_WAITOK | M_ZERO);
1140 			}
1141 			cfg->vpd.vpd_ros[off].keyword[0] = byte;
1142 			if (vpd_nextbyte(&vrs, &byte2)) {
1143 				state = -2;
1144 				break;
1145 			}
1146 			cfg->vpd.vpd_ros[off].keyword[1] = byte2;
1147 			if (vpd_nextbyte(&vrs, &byte2)) {
1148 				state = -2;
1149 				break;
1150 			}
1151 			cfg->vpd.vpd_ros[off].len = dflen = byte2;
1152 			if (dflen == 0 &&
1153 			    strncmp(cfg->vpd.vpd_ros[off].keyword, "RV",
1154 			    2) == 0) {
1155 				/*
1156 				 * if this happens, we can't trust the rest
1157 				 * of the VPD.
1158 				 */
1159 				pci_printf(cfg, "bad keyword length: %d\n",
1160 				    dflen);
1161 				cksumvalid = 0;
1162 				state = -1;
1163 				break;
1164 			} else if (dflen == 0) {
1165 				cfg->vpd.vpd_ros[off].value = malloc(1 *
1166 				    sizeof(*cfg->vpd.vpd_ros[off].value),
1167 				    M_DEVBUF, M_WAITOK);
1168 				cfg->vpd.vpd_ros[off].value[0] = '\x00';
1169 			} else
1170 				cfg->vpd.vpd_ros[off].value = malloc(
1171 				    (dflen + 1) *
1172 				    sizeof(*cfg->vpd.vpd_ros[off].value),
1173 				    M_DEVBUF, M_WAITOK);
1174 			remain -= 3;
1175 			i = 0;
1176 			/* keep in sync w/ state 3's transistions */
1177 			if (dflen == 0 && remain == 0)
1178 				state = 0;
1179 			else if (dflen == 0)
1180 				state = 2;
1181 			else
1182 				state = 3;
1183 			break;
1184 
1185 		case 3:	/* VPD-R Keyword Value */
1186 			cfg->vpd.vpd_ros[off].value[i++] = byte;
1187 			if (strncmp(cfg->vpd.vpd_ros[off].keyword,
1188 			    "RV", 2) == 0 && cksumvalid == -1) {
1189 				if (vrs.cksum == 0)
1190 					cksumvalid = 1;
1191 				else {
1192 					if (bootverbose)
1193 						pci_printf(cfg,
1194 					    "bad VPD cksum, remain %hhu\n",
1195 						    vrs.cksum);
1196 					cksumvalid = 0;
1197 					state = -1;
1198 					break;
1199 				}
1200 			}
1201 			dflen--;
1202 			remain--;
1203 			/* keep in sync w/ state 2's transistions */
1204 			if (dflen == 0)
1205 				cfg->vpd.vpd_ros[off++].value[i++] = '\0';
1206 			if (dflen == 0 && remain == 0) {
1207 				cfg->vpd.vpd_rocnt = off;
1208 				cfg->vpd.vpd_ros = reallocf(cfg->vpd.vpd_ros,
1209 				    off * sizeof(*cfg->vpd.vpd_ros),
1210 				    M_DEVBUF, M_WAITOK | M_ZERO);
1211 				state = 0;
1212 			} else if (dflen == 0)
1213 				state = 2;
1214 			break;
1215 
1216 		case 4:
1217 			remain--;
1218 			if (remain == 0)
1219 				state = 0;
1220 			break;
1221 
1222 		case 5:	/* VPD-W Keyword Header */
1223 			if (off == alloc) {
1224 				cfg->vpd.vpd_w = reallocf(cfg->vpd.vpd_w,
1225 				    (alloc *= 2) * sizeof(*cfg->vpd.vpd_w),
1226 				    M_DEVBUF, M_WAITOK | M_ZERO);
1227 			}
1228 			cfg->vpd.vpd_w[off].keyword[0] = byte;
1229 			if (vpd_nextbyte(&vrs, &byte2)) {
1230 				state = -2;
1231 				break;
1232 			}
1233 			cfg->vpd.vpd_w[off].keyword[1] = byte2;
1234 			if (vpd_nextbyte(&vrs, &byte2)) {
1235 				state = -2;
1236 				break;
1237 			}
1238 			cfg->vpd.vpd_w[off].len = dflen = byte2;
1239 			cfg->vpd.vpd_w[off].start = vrs.off - vrs.bytesinval;
1240 			cfg->vpd.vpd_w[off].value = malloc((dflen + 1) *
1241 			    sizeof(*cfg->vpd.vpd_w[off].value),
1242 			    M_DEVBUF, M_WAITOK);
1243 			remain -= 3;
1244 			i = 0;
1245 			/* keep in sync w/ state 6's transistions */
1246 			if (dflen == 0 && remain == 0)
1247 				state = 0;
1248 			else if (dflen == 0)
1249 				state = 5;
1250 			else
1251 				state = 6;
1252 			break;
1253 
1254 		case 6:	/* VPD-W Keyword Value */
1255 			cfg->vpd.vpd_w[off].value[i++] = byte;
1256 			dflen--;
1257 			remain--;
1258 			/* keep in sync w/ state 5's transistions */
1259 			if (dflen == 0)
1260 				cfg->vpd.vpd_w[off++].value[i++] = '\0';
1261 			if (dflen == 0 && remain == 0) {
1262 				cfg->vpd.vpd_wcnt = off;
1263 				cfg->vpd.vpd_w = reallocf(cfg->vpd.vpd_w,
1264 				    off * sizeof(*cfg->vpd.vpd_w),
1265 				    M_DEVBUF, M_WAITOK | M_ZERO);
1266 				state = 0;
1267 			} else if (dflen == 0)
1268 				state = 5;
1269 			break;
1270 
1271 		default:
1272 			pci_printf(cfg, "invalid state: %d\n", state);
1273 			state = -1;
1274 			break;
1275 		}
1276 	}
1277 
1278 	if (cksumvalid == 0 || state < -1) {
1279 		/* read-only data bad, clean up */
1280 		if (cfg->vpd.vpd_ros != NULL) {
1281 			for (off = 0; cfg->vpd.vpd_ros[off].value; off++)
1282 				free(cfg->vpd.vpd_ros[off].value, M_DEVBUF);
1283 			free(cfg->vpd.vpd_ros, M_DEVBUF);
1284 			cfg->vpd.vpd_ros = NULL;
1285 		}
1286 	}
1287 	if (state < -1) {
1288 		/* I/O error, clean up */
1289 		pci_printf(cfg, "failed to read VPD data.\n");
1290 		if (cfg->vpd.vpd_ident != NULL) {
1291 			free(cfg->vpd.vpd_ident, M_DEVBUF);
1292 			cfg->vpd.vpd_ident = NULL;
1293 		}
1294 		if (cfg->vpd.vpd_w != NULL) {
1295 			for (off = 0; cfg->vpd.vpd_w[off].value; off++)
1296 				free(cfg->vpd.vpd_w[off].value, M_DEVBUF);
1297 			free(cfg->vpd.vpd_w, M_DEVBUF);
1298 			cfg->vpd.vpd_w = NULL;
1299 		}
1300 	}
1301 	cfg->vpd.vpd_cached = 1;
1302 #undef REG
1303 #undef WREG
1304 }
1305 
1306 int
1307 pci_get_vpd_ident_method(device_t dev, device_t child, const char **identptr)
1308 {
1309 	struct pci_devinfo *dinfo = device_get_ivars(child);
1310 	pcicfgregs *cfg = &dinfo->cfg;
1311 
1312 	if (!cfg->vpd.vpd_cached && cfg->vpd.vpd_reg != 0)
1313 		pci_read_vpd(device_get_parent(dev), cfg);
1314 
1315 	*identptr = cfg->vpd.vpd_ident;
1316 
1317 	if (*identptr == NULL)
1318 		return (ENXIO);
1319 
1320 	return (0);
1321 }
1322 
1323 int
1324 pci_get_vpd_readonly_method(device_t dev, device_t child, const char *kw,
1325 	const char **vptr)
1326 {
1327 	struct pci_devinfo *dinfo = device_get_ivars(child);
1328 	pcicfgregs *cfg = &dinfo->cfg;
1329 	int i;
1330 
1331 	if (!cfg->vpd.vpd_cached && cfg->vpd.vpd_reg != 0)
1332 		pci_read_vpd(device_get_parent(dev), cfg);
1333 
1334 	for (i = 0; i < cfg->vpd.vpd_rocnt; i++)
1335 		if (memcmp(kw, cfg->vpd.vpd_ros[i].keyword,
1336 		    sizeof(cfg->vpd.vpd_ros[i].keyword)) == 0) {
1337 			*vptr = cfg->vpd.vpd_ros[i].value;
1338 			return (0);
1339 		}
1340 
1341 	*vptr = NULL;
1342 	return (ENXIO);
1343 }
1344 
1345 struct pcicfg_vpd *
1346 pci_fetch_vpd_list(device_t dev)
1347 {
1348 	struct pci_devinfo *dinfo = device_get_ivars(dev);
1349 	pcicfgregs *cfg = &dinfo->cfg;
1350 
1351 	if (!cfg->vpd.vpd_cached && cfg->vpd.vpd_reg != 0)
1352 		pci_read_vpd(device_get_parent(device_get_parent(dev)), cfg);
1353 	return (&cfg->vpd);
1354 }
1355 
1356 /*
1357  * Find the requested HyperTransport capability and return the offset
1358  * in configuration space via the pointer provided.  The function
1359  * returns 0 on success and an error code otherwise.
1360  */
1361 int
1362 pci_find_htcap_method(device_t dev, device_t child, int capability, int *capreg)
1363 {
1364 	int ptr, error;
1365 	uint16_t val;
1366 
1367 	error = pci_find_cap(child, PCIY_HT, &ptr);
1368 	if (error)
1369 		return (error);
1370 
1371 	/*
1372 	 * Traverse the capabilities list checking each HT capability
1373 	 * to see if it matches the requested HT capability.
1374 	 */
1375 	while (ptr != 0) {
1376 		val = pci_read_config(child, ptr + PCIR_HT_COMMAND, 2);
1377 		if (capability == PCIM_HTCAP_SLAVE ||
1378 		    capability == PCIM_HTCAP_HOST)
1379 			val &= 0xe000;
1380 		else
1381 			val &= PCIM_HTCMD_CAP_MASK;
1382 		if (val == capability) {
1383 			if (capreg != NULL)
1384 				*capreg = ptr;
1385 			return (0);
1386 		}
1387 
1388 		/* Skip to the next HT capability. */
1389 		while (ptr != 0) {
1390 			ptr = pci_read_config(child, ptr + PCICAP_NEXTPTR, 1);
1391 			if (pci_read_config(child, ptr + PCICAP_ID, 1) ==
1392 			    PCIY_HT)
1393 				break;
1394 		}
1395 	}
1396 	return (ENOENT);
1397 }
1398 
1399 /*
1400  * Find the requested capability and return the offset in
1401  * configuration space via the pointer provided.  The function returns
1402  * 0 on success and an error code otherwise.
1403  */
1404 int
1405 pci_find_cap_method(device_t dev, device_t child, int capability,
1406     int *capreg)
1407 {
1408 	struct pci_devinfo *dinfo = device_get_ivars(child);
1409 	pcicfgregs *cfg = &dinfo->cfg;
1410 	u_int32_t status;
1411 	u_int8_t ptr;
1412 
1413 	/*
1414 	 * Check the CAP_LIST bit of the PCI status register first.
1415 	 */
1416 	status = pci_read_config(child, PCIR_STATUS, 2);
1417 	if (!(status & PCIM_STATUS_CAPPRESENT))
1418 		return (ENXIO);
1419 
1420 	/*
1421 	 * Determine the start pointer of the capabilities list.
1422 	 */
1423 	switch (cfg->hdrtype & PCIM_HDRTYPE) {
1424 	case PCIM_HDRTYPE_NORMAL:
1425 	case PCIM_HDRTYPE_BRIDGE:
1426 		ptr = PCIR_CAP_PTR;
1427 		break;
1428 	case PCIM_HDRTYPE_CARDBUS:
1429 		ptr = PCIR_CAP_PTR_2;
1430 		break;
1431 	default:
1432 		/* XXX: panic? */
1433 		return (ENXIO);		/* no extended capabilities support */
1434 	}
1435 	ptr = pci_read_config(child, ptr, 1);
1436 
1437 	/*
1438 	 * Traverse the capabilities list.
1439 	 */
1440 	while (ptr != 0) {
1441 		if (pci_read_config(child, ptr + PCICAP_ID, 1) == capability) {
1442 			if (capreg != NULL)
1443 				*capreg = ptr;
1444 			return (0);
1445 		}
1446 		ptr = pci_read_config(child, ptr + PCICAP_NEXTPTR, 1);
1447 	}
1448 
1449 	return (ENOENT);
1450 }
1451 
1452 /*
1453  * Find the requested extended capability and return the offset in
1454  * configuration space via the pointer provided.  The function returns
1455  * 0 on success and an error code otherwise.
1456  */
1457 int
1458 pci_find_extcap_method(device_t dev, device_t child, int capability,
1459     int *capreg)
1460 {
1461 	struct pci_devinfo *dinfo = device_get_ivars(child);
1462 	pcicfgregs *cfg = &dinfo->cfg;
1463 	uint32_t ecap;
1464 	uint16_t ptr;
1465 
1466 	/* Only supported for PCI-express devices. */
1467 	if (cfg->pcie.pcie_location == 0)
1468 		return (ENXIO);
1469 
1470 	ptr = PCIR_EXTCAP;
1471 	ecap = pci_read_config(child, ptr, 4);
1472 	if (ecap == 0xffffffff || ecap == 0)
1473 		return (ENOENT);
1474 	for (;;) {
1475 		if (PCI_EXTCAP_ID(ecap) == capability) {
1476 			if (capreg != NULL)
1477 				*capreg = ptr;
1478 			return (0);
1479 		}
1480 		ptr = PCI_EXTCAP_NEXTPTR(ecap);
1481 		if (ptr == 0)
1482 			break;
1483 		ecap = pci_read_config(child, ptr, 4);
1484 	}
1485 
1486 	return (ENOENT);
1487 }
1488 
1489 /*
1490  * Support for MSI-X message interrupts.
1491  */
1492 static void
1493 pci_write_msix_entry(device_t dev, u_int index, uint64_t address, uint32_t data)
1494 {
1495 	struct pci_devinfo *dinfo = device_get_ivars(dev);
1496 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1497 	uint32_t offset;
1498 
1499 	KASSERT(msix->msix_table_len > index, ("bogus index"));
1500 	offset = msix->msix_table_offset + index * 16;
1501 	bus_write_4(msix->msix_table_res, offset, address & 0xffffffff);
1502 	bus_write_4(msix->msix_table_res, offset + 4, address >> 32);
1503 	bus_write_4(msix->msix_table_res, offset + 8, data);
1504 }
1505 
1506 void
1507 pci_enable_msix_method(device_t dev, device_t child, u_int index,
1508     uint64_t address, uint32_t data)
1509 {
1510 
1511 	if (pci_msix_rewrite_table) {
1512 		struct pci_devinfo *dinfo = device_get_ivars(child);
1513 		struct pcicfg_msix *msix = &dinfo->cfg.msix;
1514 
1515 		/*
1516 		 * Some VM hosts require MSIX to be disabled in the
1517 		 * control register before updating the MSIX table
1518 		 * entries are allowed. It is not enough to only
1519 		 * disable MSIX while updating a single entry. MSIX
1520 		 * must be disabled while updating all entries in the
1521 		 * table.
1522 		 */
1523 		pci_write_config(child,
1524 		    msix->msix_location + PCIR_MSIX_CTRL,
1525 		    msix->msix_ctrl & ~PCIM_MSIXCTRL_MSIX_ENABLE, 2);
1526 		pci_resume_msix(child);
1527 	} else
1528 		pci_write_msix_entry(child, index, address, data);
1529 
1530 	/* Enable MSI -> HT mapping. */
1531 	pci_ht_map_msi(child, address);
1532 }
1533 
1534 void
1535 pci_mask_msix(device_t dev, u_int index)
1536 {
1537 	struct pci_devinfo *dinfo = device_get_ivars(dev);
1538 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1539 	uint32_t offset, val;
1540 
1541 	KASSERT(msix->msix_msgnum > index, ("bogus index"));
1542 	offset = msix->msix_table_offset + index * 16 + 12;
1543 	val = bus_read_4(msix->msix_table_res, offset);
1544 	if (!(val & PCIM_MSIX_VCTRL_MASK)) {
1545 		val |= PCIM_MSIX_VCTRL_MASK;
1546 		bus_write_4(msix->msix_table_res, offset, val);
1547 	}
1548 }
1549 
1550 void
1551 pci_unmask_msix(device_t dev, u_int index)
1552 {
1553 	struct pci_devinfo *dinfo = device_get_ivars(dev);
1554 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1555 	uint32_t offset, val;
1556 
1557 	KASSERT(msix->msix_table_len > index, ("bogus index"));
1558 	offset = msix->msix_table_offset + index * 16 + 12;
1559 	val = bus_read_4(msix->msix_table_res, offset);
1560 	if (val & PCIM_MSIX_VCTRL_MASK) {
1561 		val &= ~PCIM_MSIX_VCTRL_MASK;
1562 		bus_write_4(msix->msix_table_res, offset, val);
1563 	}
1564 }
1565 
1566 int
1567 pci_pending_msix(device_t dev, u_int index)
1568 {
1569 	struct pci_devinfo *dinfo = device_get_ivars(dev);
1570 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1571 	uint32_t offset, bit;
1572 
1573 	KASSERT(msix->msix_table_len > index, ("bogus index"));
1574 	offset = msix->msix_pba_offset + (index / 32) * 4;
1575 	bit = 1 << index % 32;
1576 	return (bus_read_4(msix->msix_pba_res, offset) & bit);
1577 }
1578 
1579 /*
1580  * Restore MSI-X registers and table during resume.  If MSI-X is
1581  * enabled then walk the virtual table to restore the actual MSI-X
1582  * table.
1583  */
1584 static void
1585 pci_resume_msix(device_t dev)
1586 {
1587 	struct pci_devinfo *dinfo = device_get_ivars(dev);
1588 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1589 	struct msix_table_entry *mte;
1590 	struct msix_vector *mv;
1591 	int i;
1592 
1593 	if (msix->msix_alloc > 0) {
1594 		/* First, mask all vectors. */
1595 		for (i = 0; i < msix->msix_msgnum; i++)
1596 			pci_mask_msix(dev, i);
1597 
1598 		/* Second, program any messages with at least one handler. */
1599 		for (i = 0; i < msix->msix_table_len; i++) {
1600 			mte = &msix->msix_table[i];
1601 			if (mte->mte_vector == 0 || mte->mte_handlers == 0)
1602 				continue;
1603 			mv = &msix->msix_vectors[mte->mte_vector - 1];
1604 			pci_write_msix_entry(dev, i, mv->mv_address,
1605 			    mv->mv_data);
1606 			pci_unmask_msix(dev, i);
1607 		}
1608 	}
1609 	pci_write_config(dev, msix->msix_location + PCIR_MSIX_CTRL,
1610 	    msix->msix_ctrl, 2);
1611 }
1612 
1613 /*
1614  * Attempt to allocate *count MSI-X messages.  The actual number allocated is
1615  * returned in *count.  After this function returns, each message will be
1616  * available to the driver as SYS_RES_IRQ resources starting at rid 1.
1617  */
1618 int
1619 pci_alloc_msix_method(device_t dev, device_t child, int *count)
1620 {
1621 	struct pci_devinfo *dinfo = device_get_ivars(child);
1622 	pcicfgregs *cfg = &dinfo->cfg;
1623 	struct resource_list_entry *rle;
1624 	int actual, error, i, irq, max;
1625 
1626 	/* Don't let count == 0 get us into trouble. */
1627 	if (*count == 0)
1628 		return (EINVAL);
1629 
1630 	/* If rid 0 is allocated, then fail. */
1631 	rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, 0);
1632 	if (rle != NULL && rle->res != NULL)
1633 		return (ENXIO);
1634 
1635 	/* Already have allocated messages? */
1636 	if (cfg->msi.msi_alloc != 0 || cfg->msix.msix_alloc != 0)
1637 		return (ENXIO);
1638 
1639 	/* If MSI-X is blacklisted for this system, fail. */
1640 	if (pci_msix_blacklisted())
1641 		return (ENXIO);
1642 
1643 	/* MSI-X capability present? */
1644 	if (cfg->msix.msix_location == 0 || !pci_do_msix)
1645 		return (ENODEV);
1646 
1647 	/* Make sure the appropriate BARs are mapped. */
1648 	rle = resource_list_find(&dinfo->resources, SYS_RES_MEMORY,
1649 	    cfg->msix.msix_table_bar);
1650 	if (rle == NULL || rle->res == NULL ||
1651 	    !(rman_get_flags(rle->res) & RF_ACTIVE))
1652 		return (ENXIO);
1653 	cfg->msix.msix_table_res = rle->res;
1654 	if (cfg->msix.msix_pba_bar != cfg->msix.msix_table_bar) {
1655 		rle = resource_list_find(&dinfo->resources, SYS_RES_MEMORY,
1656 		    cfg->msix.msix_pba_bar);
1657 		if (rle == NULL || rle->res == NULL ||
1658 		    !(rman_get_flags(rle->res) & RF_ACTIVE))
1659 			return (ENXIO);
1660 	}
1661 	cfg->msix.msix_pba_res = rle->res;
1662 
1663 	if (bootverbose)
1664 		device_printf(child,
1665 		    "attempting to allocate %d MSI-X vectors (%d supported)\n",
1666 		    *count, cfg->msix.msix_msgnum);
1667 	max = min(*count, cfg->msix.msix_msgnum);
1668 	for (i = 0; i < max; i++) {
1669 		/* Allocate a message. */
1670 		error = PCIB_ALLOC_MSIX(device_get_parent(dev), child, &irq);
1671 		if (error) {
1672 			if (i == 0)
1673 				return (error);
1674 			break;
1675 		}
1676 		resource_list_add(&dinfo->resources, SYS_RES_IRQ, i + 1, irq,
1677 		    irq, 1);
1678 	}
1679 	actual = i;
1680 
1681 	if (bootverbose) {
1682 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, 1);
1683 		if (actual == 1)
1684 			device_printf(child, "using IRQ %ju for MSI-X\n",
1685 			    rle->start);
1686 		else {
1687 			int run;
1688 
1689 			/*
1690 			 * Be fancy and try to print contiguous runs of
1691 			 * IRQ values as ranges.  'irq' is the previous IRQ.
1692 			 * 'run' is true if we are in a range.
1693 			 */
1694 			device_printf(child, "using IRQs %ju", rle->start);
1695 			irq = rle->start;
1696 			run = 0;
1697 			for (i = 1; i < actual; i++) {
1698 				rle = resource_list_find(&dinfo->resources,
1699 				    SYS_RES_IRQ, i + 1);
1700 
1701 				/* Still in a run? */
1702 				if (rle->start == irq + 1) {
1703 					run = 1;
1704 					irq++;
1705 					continue;
1706 				}
1707 
1708 				/* Finish previous range. */
1709 				if (run) {
1710 					printf("-%d", irq);
1711 					run = 0;
1712 				}
1713 
1714 				/* Start new range. */
1715 				printf(",%ju", rle->start);
1716 				irq = rle->start;
1717 			}
1718 
1719 			/* Unfinished range? */
1720 			if (run)
1721 				printf("-%d", irq);
1722 			printf(" for MSI-X\n");
1723 		}
1724 	}
1725 
1726 	/* Mask all vectors. */
1727 	for (i = 0; i < cfg->msix.msix_msgnum; i++)
1728 		pci_mask_msix(child, i);
1729 
1730 	/* Allocate and initialize vector data and virtual table. */
1731 	cfg->msix.msix_vectors = malloc(sizeof(struct msix_vector) * actual,
1732 	    M_DEVBUF, M_WAITOK | M_ZERO);
1733 	cfg->msix.msix_table = malloc(sizeof(struct msix_table_entry) * actual,
1734 	    M_DEVBUF, M_WAITOK | M_ZERO);
1735 	for (i = 0; i < actual; i++) {
1736 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, i + 1);
1737 		cfg->msix.msix_vectors[i].mv_irq = rle->start;
1738 		cfg->msix.msix_table[i].mte_vector = i + 1;
1739 	}
1740 
1741 	/* Update control register to enable MSI-X. */
1742 	cfg->msix.msix_ctrl |= PCIM_MSIXCTRL_MSIX_ENABLE;
1743 	pci_write_config(child, cfg->msix.msix_location + PCIR_MSIX_CTRL,
1744 	    cfg->msix.msix_ctrl, 2);
1745 
1746 	/* Update counts of alloc'd messages. */
1747 	cfg->msix.msix_alloc = actual;
1748 	cfg->msix.msix_table_len = actual;
1749 	*count = actual;
1750 	return (0);
1751 }
1752 
1753 /*
1754  * By default, pci_alloc_msix() will assign the allocated IRQ
1755  * resources consecutively to the first N messages in the MSI-X table.
1756  * However, device drivers may want to use different layouts if they
1757  * either receive fewer messages than they asked for, or they wish to
1758  * populate the MSI-X table sparsely.  This method allows the driver
1759  * to specify what layout it wants.  It must be called after a
1760  * successful pci_alloc_msix() but before any of the associated
1761  * SYS_RES_IRQ resources are allocated via bus_alloc_resource().
1762  *
1763  * The 'vectors' array contains 'count' message vectors.  The array
1764  * maps directly to the MSI-X table in that index 0 in the array
1765  * specifies the vector for the first message in the MSI-X table, etc.
1766  * The vector value in each array index can either be 0 to indicate
1767  * that no vector should be assigned to a message slot, or it can be a
1768  * number from 1 to N (where N is the count returned from a
1769  * succcessful call to pci_alloc_msix()) to indicate which message
1770  * vector (IRQ) to be used for the corresponding message.
1771  *
1772  * On successful return, each message with a non-zero vector will have
1773  * an associated SYS_RES_IRQ whose rid is equal to the array index +
1774  * 1.  Additionally, if any of the IRQs allocated via the previous
1775  * call to pci_alloc_msix() are not used in the mapping, those IRQs
1776  * will be freed back to the system automatically.
1777  *
1778  * For example, suppose a driver has a MSI-X table with 6 messages and
1779  * asks for 6 messages, but pci_alloc_msix() only returns a count of
1780  * 3.  Call the three vectors allocated by pci_alloc_msix() A, B, and
1781  * C.  After the call to pci_alloc_msix(), the device will be setup to
1782  * have an MSI-X table of ABC--- (where - means no vector assigned).
1783  * If the driver then passes a vector array of { 1, 0, 1, 2, 0, 2 },
1784  * then the MSI-X table will look like A-AB-B, and the 'C' vector will
1785  * be freed back to the system.  This device will also have valid
1786  * SYS_RES_IRQ rids of 1, 3, 4, and 6.
1787  *
1788  * In any case, the SYS_RES_IRQ rid X will always map to the message
1789  * at MSI-X table index X - 1 and will only be valid if a vector is
1790  * assigned to that table entry.
1791  */
1792 int
1793 pci_remap_msix_method(device_t dev, device_t child, int count,
1794     const u_int *vectors)
1795 {
1796 	struct pci_devinfo *dinfo = device_get_ivars(child);
1797 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1798 	struct resource_list_entry *rle;
1799 	int i, irq, j, *used;
1800 
1801 	/*
1802 	 * Have to have at least one message in the table but the
1803 	 * table can't be bigger than the actual MSI-X table in the
1804 	 * device.
1805 	 */
1806 	if (count == 0 || count > msix->msix_msgnum)
1807 		return (EINVAL);
1808 
1809 	/* Sanity check the vectors. */
1810 	for (i = 0; i < count; i++)
1811 		if (vectors[i] > msix->msix_alloc)
1812 			return (EINVAL);
1813 
1814 	/*
1815 	 * Make sure there aren't any holes in the vectors to be used.
1816 	 * It's a big pain to support it, and it doesn't really make
1817 	 * sense anyway.  Also, at least one vector must be used.
1818 	 */
1819 	used = malloc(sizeof(int) * msix->msix_alloc, M_DEVBUF, M_WAITOK |
1820 	    M_ZERO);
1821 	for (i = 0; i < count; i++)
1822 		if (vectors[i] != 0)
1823 			used[vectors[i] - 1] = 1;
1824 	for (i = 0; i < msix->msix_alloc - 1; i++)
1825 		if (used[i] == 0 && used[i + 1] == 1) {
1826 			free(used, M_DEVBUF);
1827 			return (EINVAL);
1828 		}
1829 	if (used[0] != 1) {
1830 		free(used, M_DEVBUF);
1831 		return (EINVAL);
1832 	}
1833 
1834 	/* Make sure none of the resources are allocated. */
1835 	for (i = 0; i < msix->msix_table_len; i++) {
1836 		if (msix->msix_table[i].mte_vector == 0)
1837 			continue;
1838 		if (msix->msix_table[i].mte_handlers > 0) {
1839 			free(used, M_DEVBUF);
1840 			return (EBUSY);
1841 		}
1842 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, i + 1);
1843 		KASSERT(rle != NULL, ("missing resource"));
1844 		if (rle->res != NULL) {
1845 			free(used, M_DEVBUF);
1846 			return (EBUSY);
1847 		}
1848 	}
1849 
1850 	/* Free the existing resource list entries. */
1851 	for (i = 0; i < msix->msix_table_len; i++) {
1852 		if (msix->msix_table[i].mte_vector == 0)
1853 			continue;
1854 		resource_list_delete(&dinfo->resources, SYS_RES_IRQ, i + 1);
1855 	}
1856 
1857 	/*
1858 	 * Build the new virtual table keeping track of which vectors are
1859 	 * used.
1860 	 */
1861 	free(msix->msix_table, M_DEVBUF);
1862 	msix->msix_table = malloc(sizeof(struct msix_table_entry) * count,
1863 	    M_DEVBUF, M_WAITOK | M_ZERO);
1864 	for (i = 0; i < count; i++)
1865 		msix->msix_table[i].mte_vector = vectors[i];
1866 	msix->msix_table_len = count;
1867 
1868 	/* Free any unused IRQs and resize the vectors array if necessary. */
1869 	j = msix->msix_alloc - 1;
1870 	if (used[j] == 0) {
1871 		struct msix_vector *vec;
1872 
1873 		while (used[j] == 0) {
1874 			PCIB_RELEASE_MSIX(device_get_parent(dev), child,
1875 			    msix->msix_vectors[j].mv_irq);
1876 			j--;
1877 		}
1878 		vec = malloc(sizeof(struct msix_vector) * (j + 1), M_DEVBUF,
1879 		    M_WAITOK);
1880 		bcopy(msix->msix_vectors, vec, sizeof(struct msix_vector) *
1881 		    (j + 1));
1882 		free(msix->msix_vectors, M_DEVBUF);
1883 		msix->msix_vectors = vec;
1884 		msix->msix_alloc = j + 1;
1885 	}
1886 	free(used, M_DEVBUF);
1887 
1888 	/* Map the IRQs onto the rids. */
1889 	for (i = 0; i < count; i++) {
1890 		if (vectors[i] == 0)
1891 			continue;
1892 		irq = msix->msix_vectors[vectors[i] - 1].mv_irq;
1893 		resource_list_add(&dinfo->resources, SYS_RES_IRQ, i + 1, irq,
1894 		    irq, 1);
1895 	}
1896 
1897 	if (bootverbose) {
1898 		device_printf(child, "Remapped MSI-X IRQs as: ");
1899 		for (i = 0; i < count; i++) {
1900 			if (i != 0)
1901 				printf(", ");
1902 			if (vectors[i] == 0)
1903 				printf("---");
1904 			else
1905 				printf("%d",
1906 				    msix->msix_vectors[vectors[i] - 1].mv_irq);
1907 		}
1908 		printf("\n");
1909 	}
1910 
1911 	return (0);
1912 }
1913 
1914 static int
1915 pci_release_msix(device_t dev, device_t child)
1916 {
1917 	struct pci_devinfo *dinfo = device_get_ivars(child);
1918 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1919 	struct resource_list_entry *rle;
1920 	int i;
1921 
1922 	/* Do we have any messages to release? */
1923 	if (msix->msix_alloc == 0)
1924 		return (ENODEV);
1925 
1926 	/* Make sure none of the resources are allocated. */
1927 	for (i = 0; i < msix->msix_table_len; i++) {
1928 		if (msix->msix_table[i].mte_vector == 0)
1929 			continue;
1930 		if (msix->msix_table[i].mte_handlers > 0)
1931 			return (EBUSY);
1932 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, i + 1);
1933 		KASSERT(rle != NULL, ("missing resource"));
1934 		if (rle->res != NULL)
1935 			return (EBUSY);
1936 	}
1937 
1938 	/* Update control register to disable MSI-X. */
1939 	msix->msix_ctrl &= ~PCIM_MSIXCTRL_MSIX_ENABLE;
1940 	pci_write_config(child, msix->msix_location + PCIR_MSIX_CTRL,
1941 	    msix->msix_ctrl, 2);
1942 
1943 	/* Free the resource list entries. */
1944 	for (i = 0; i < msix->msix_table_len; i++) {
1945 		if (msix->msix_table[i].mte_vector == 0)
1946 			continue;
1947 		resource_list_delete(&dinfo->resources, SYS_RES_IRQ, i + 1);
1948 	}
1949 	free(msix->msix_table, M_DEVBUF);
1950 	msix->msix_table_len = 0;
1951 
1952 	/* Release the IRQs. */
1953 	for (i = 0; i < msix->msix_alloc; i++)
1954 		PCIB_RELEASE_MSIX(device_get_parent(dev), child,
1955 		    msix->msix_vectors[i].mv_irq);
1956 	free(msix->msix_vectors, M_DEVBUF);
1957 	msix->msix_alloc = 0;
1958 	return (0);
1959 }
1960 
1961 /*
1962  * Return the max supported MSI-X messages this device supports.
1963  * Basically, assuming the MD code can alloc messages, this function
1964  * should return the maximum value that pci_alloc_msix() can return.
1965  * Thus, it is subject to the tunables, etc.
1966  */
1967 int
1968 pci_msix_count_method(device_t dev, device_t child)
1969 {
1970 	struct pci_devinfo *dinfo = device_get_ivars(child);
1971 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1972 
1973 	if (pci_do_msix && msix->msix_location != 0)
1974 		return (msix->msix_msgnum);
1975 	return (0);
1976 }
1977 
1978 int
1979 pci_msix_pba_bar_method(device_t dev, device_t child)
1980 {
1981 	struct pci_devinfo *dinfo = device_get_ivars(child);
1982 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1983 
1984 	if (pci_do_msix && msix->msix_location != 0)
1985 		return (msix->msix_pba_bar);
1986 	return (-1);
1987 }
1988 
1989 int
1990 pci_msix_table_bar_method(device_t dev, device_t child)
1991 {
1992 	struct pci_devinfo *dinfo = device_get_ivars(child);
1993 	struct pcicfg_msix *msix = &dinfo->cfg.msix;
1994 
1995 	if (pci_do_msix && msix->msix_location != 0)
1996 		return (msix->msix_table_bar);
1997 	return (-1);
1998 }
1999 
2000 /*
2001  * HyperTransport MSI mapping control
2002  */
2003 void
2004 pci_ht_map_msi(device_t dev, uint64_t addr)
2005 {
2006 	struct pci_devinfo *dinfo = device_get_ivars(dev);
2007 	struct pcicfg_ht *ht = &dinfo->cfg.ht;
2008 
2009 	if (!ht->ht_msimap)
2010 		return;
2011 
2012 	if (addr && !(ht->ht_msictrl & PCIM_HTCMD_MSI_ENABLE) &&
2013 	    ht->ht_msiaddr >> 20 == addr >> 20) {
2014 		/* Enable MSI -> HT mapping. */
2015 		ht->ht_msictrl |= PCIM_HTCMD_MSI_ENABLE;
2016 		pci_write_config(dev, ht->ht_msimap + PCIR_HT_COMMAND,
2017 		    ht->ht_msictrl, 2);
2018 	}
2019 
2020 	if (!addr && ht->ht_msictrl & PCIM_HTCMD_MSI_ENABLE) {
2021 		/* Disable MSI -> HT mapping. */
2022 		ht->ht_msictrl &= ~PCIM_HTCMD_MSI_ENABLE;
2023 		pci_write_config(dev, ht->ht_msimap + PCIR_HT_COMMAND,
2024 		    ht->ht_msictrl, 2);
2025 	}
2026 }
2027 
2028 int
2029 pci_get_max_payload(device_t dev)
2030 {
2031 	struct pci_devinfo *dinfo = device_get_ivars(dev);
2032 	int cap;
2033 	uint16_t val;
2034 
2035 	cap = dinfo->cfg.pcie.pcie_location;
2036 	if (cap == 0)
2037 		return (0);
2038 	val = pci_read_config(dev, cap + PCIER_DEVICE_CTL, 2);
2039 	val &= PCIEM_CTL_MAX_PAYLOAD;
2040 	val >>= 5;
2041 	return (1 << (val + 7));
2042 }
2043 
2044 int
2045 pci_get_max_read_req(device_t dev)
2046 {
2047 	struct pci_devinfo *dinfo = device_get_ivars(dev);
2048 	int cap;
2049 	uint16_t val;
2050 
2051 	cap = dinfo->cfg.pcie.pcie_location;
2052 	if (cap == 0)
2053 		return (0);
2054 	val = pci_read_config(dev, cap + PCIER_DEVICE_CTL, 2);
2055 	val &= PCIEM_CTL_MAX_READ_REQUEST;
2056 	val >>= 12;
2057 	return (1 << (val + 7));
2058 }
2059 
2060 int
2061 pci_set_max_read_req(device_t dev, int size)
2062 {
2063 	struct pci_devinfo *dinfo = device_get_ivars(dev);
2064 	int cap;
2065 	uint16_t val;
2066 
2067 	cap = dinfo->cfg.pcie.pcie_location;
2068 	if (cap == 0)
2069 		return (0);
2070 	if (size < 128)
2071 		size = 128;
2072 	if (size > 4096)
2073 		size = 4096;
2074 	size = (1 << (fls(size) - 1));
2075 	val = pci_read_config(dev, cap + PCIER_DEVICE_CTL, 2);
2076 	val &= ~PCIEM_CTL_MAX_READ_REQUEST;
2077 	val |= (fls(size) - 8) << 12;
2078 	pci_write_config(dev, cap + PCIER_DEVICE_CTL, val, 2);
2079 	return (size);
2080 }
2081 
2082 uint32_t
2083 pcie_read_config(device_t dev, int reg, int width)
2084 {
2085 	struct pci_devinfo *dinfo = device_get_ivars(dev);
2086 	int cap;
2087 
2088 	cap = dinfo->cfg.pcie.pcie_location;
2089 	if (cap == 0) {
2090 		if (width == 2)
2091 			return (0xffff);
2092 		return (0xffffffff);
2093 	}
2094 
2095 	return (pci_read_config(dev, cap + reg, width));
2096 }
2097 
2098 void
2099 pcie_write_config(device_t dev, int reg, uint32_t value, int width)
2100 {
2101 	struct pci_devinfo *dinfo = device_get_ivars(dev);
2102 	int cap;
2103 
2104 	cap = dinfo->cfg.pcie.pcie_location;
2105 	if (cap == 0)
2106 		return;
2107 	pci_write_config(dev, cap + reg, value, width);
2108 }
2109 
2110 /*
2111  * Adjusts a PCI-e capability register by clearing the bits in mask
2112  * and setting the bits in (value & mask).  Bits not set in mask are
2113  * not adjusted.
2114  *
2115  * Returns the old value on success or all ones on failure.
2116  */
2117 uint32_t
2118 pcie_adjust_config(device_t dev, int reg, uint32_t mask, uint32_t value,
2119     int width)
2120 {
2121 	struct pci_devinfo *dinfo = device_get_ivars(dev);
2122 	uint32_t old, new;
2123 	int cap;
2124 
2125 	cap = dinfo->cfg.pcie.pcie_location;
2126 	if (cap == 0) {
2127 		if (width == 2)
2128 			return (0xffff);
2129 		return (0xffffffff);
2130 	}
2131 
2132 	old = pci_read_config(dev, cap + reg, width);
2133 	new = old & ~mask;
2134 	new |= (value & mask);
2135 	pci_write_config(dev, cap + reg, new, width);
2136 	return (old);
2137 }
2138 
2139 /*
2140  * Support for MSI message signalled interrupts.
2141  */
2142 void
2143 pci_enable_msi_method(device_t dev, device_t child, uint64_t address,
2144     uint16_t data)
2145 {
2146 	struct pci_devinfo *dinfo = device_get_ivars(child);
2147 	struct pcicfg_msi *msi = &dinfo->cfg.msi;
2148 
2149 	/* Write data and address values. */
2150 	pci_write_config(child, msi->msi_location + PCIR_MSI_ADDR,
2151 	    address & 0xffffffff, 4);
2152 	if (msi->msi_ctrl & PCIM_MSICTRL_64BIT) {
2153 		pci_write_config(child, msi->msi_location + PCIR_MSI_ADDR_HIGH,
2154 		    address >> 32, 4);
2155 		pci_write_config(child, msi->msi_location + PCIR_MSI_DATA_64BIT,
2156 		    data, 2);
2157 	} else
2158 		pci_write_config(child, msi->msi_location + PCIR_MSI_DATA, data,
2159 		    2);
2160 
2161 	/* Enable MSI in the control register. */
2162 	msi->msi_ctrl |= PCIM_MSICTRL_MSI_ENABLE;
2163 	pci_write_config(child, msi->msi_location + PCIR_MSI_CTRL,
2164 	    msi->msi_ctrl, 2);
2165 
2166 	/* Enable MSI -> HT mapping. */
2167 	pci_ht_map_msi(child, address);
2168 }
2169 
2170 void
2171 pci_disable_msi_method(device_t dev, device_t child)
2172 {
2173 	struct pci_devinfo *dinfo = device_get_ivars(child);
2174 	struct pcicfg_msi *msi = &dinfo->cfg.msi;
2175 
2176 	/* Disable MSI -> HT mapping. */
2177 	pci_ht_map_msi(child, 0);
2178 
2179 	/* Disable MSI in the control register. */
2180 	msi->msi_ctrl &= ~PCIM_MSICTRL_MSI_ENABLE;
2181 	pci_write_config(child, msi->msi_location + PCIR_MSI_CTRL,
2182 	    msi->msi_ctrl, 2);
2183 }
2184 
2185 /*
2186  * Restore MSI registers during resume.  If MSI is enabled then
2187  * restore the data and address registers in addition to the control
2188  * register.
2189  */
2190 static void
2191 pci_resume_msi(device_t dev)
2192 {
2193 	struct pci_devinfo *dinfo = device_get_ivars(dev);
2194 	struct pcicfg_msi *msi = &dinfo->cfg.msi;
2195 	uint64_t address;
2196 	uint16_t data;
2197 
2198 	if (msi->msi_ctrl & PCIM_MSICTRL_MSI_ENABLE) {
2199 		address = msi->msi_addr;
2200 		data = msi->msi_data;
2201 		pci_write_config(dev, msi->msi_location + PCIR_MSI_ADDR,
2202 		    address & 0xffffffff, 4);
2203 		if (msi->msi_ctrl & PCIM_MSICTRL_64BIT) {
2204 			pci_write_config(dev, msi->msi_location +
2205 			    PCIR_MSI_ADDR_HIGH, address >> 32, 4);
2206 			pci_write_config(dev, msi->msi_location +
2207 			    PCIR_MSI_DATA_64BIT, data, 2);
2208 		} else
2209 			pci_write_config(dev, msi->msi_location + PCIR_MSI_DATA,
2210 			    data, 2);
2211 	}
2212 	pci_write_config(dev, msi->msi_location + PCIR_MSI_CTRL, msi->msi_ctrl,
2213 	    2);
2214 }
2215 
2216 static int
2217 pci_remap_intr_method(device_t bus, device_t dev, u_int irq)
2218 {
2219 	struct pci_devinfo *dinfo = device_get_ivars(dev);
2220 	pcicfgregs *cfg = &dinfo->cfg;
2221 	struct resource_list_entry *rle;
2222 	struct msix_table_entry *mte;
2223 	struct msix_vector *mv;
2224 	uint64_t addr;
2225 	uint32_t data;
2226 	int error, i, j;
2227 
2228 	/*
2229 	 * Handle MSI first.  We try to find this IRQ among our list
2230 	 * of MSI IRQs.  If we find it, we request updated address and
2231 	 * data registers and apply the results.
2232 	 */
2233 	if (cfg->msi.msi_alloc > 0) {
2234 
2235 		/* If we don't have any active handlers, nothing to do. */
2236 		if (cfg->msi.msi_handlers == 0)
2237 			return (0);
2238 		for (i = 0; i < cfg->msi.msi_alloc; i++) {
2239 			rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ,
2240 			    i + 1);
2241 			if (rle->start == irq) {
2242 				error = PCIB_MAP_MSI(device_get_parent(bus),
2243 				    dev, irq, &addr, &data);
2244 				if (error)
2245 					return (error);
2246 				pci_disable_msi(dev);
2247 				dinfo->cfg.msi.msi_addr = addr;
2248 				dinfo->cfg.msi.msi_data = data;
2249 				pci_enable_msi(dev, addr, data);
2250 				return (0);
2251 			}
2252 		}
2253 		return (ENOENT);
2254 	}
2255 
2256 	/*
2257 	 * For MSI-X, we check to see if we have this IRQ.  If we do,
2258 	 * we request the updated mapping info.  If that works, we go
2259 	 * through all the slots that use this IRQ and update them.
2260 	 */
2261 	if (cfg->msix.msix_alloc > 0) {
2262 		for (i = 0; i < cfg->msix.msix_alloc; i++) {
2263 			mv = &cfg->msix.msix_vectors[i];
2264 			if (mv->mv_irq == irq) {
2265 				error = PCIB_MAP_MSI(device_get_parent(bus),
2266 				    dev, irq, &addr, &data);
2267 				if (error)
2268 					return (error);
2269 				mv->mv_address = addr;
2270 				mv->mv_data = data;
2271 				for (j = 0; j < cfg->msix.msix_table_len; j++) {
2272 					mte = &cfg->msix.msix_table[j];
2273 					if (mte->mte_vector != i + 1)
2274 						continue;
2275 					if (mte->mte_handlers == 0)
2276 						continue;
2277 					pci_mask_msix(dev, j);
2278 					pci_enable_msix(dev, j, addr, data);
2279 					pci_unmask_msix(dev, j);
2280 				}
2281 			}
2282 		}
2283 		return (ENOENT);
2284 	}
2285 
2286 	return (ENOENT);
2287 }
2288 
2289 /*
2290  * Returns true if the specified device is blacklisted because MSI
2291  * doesn't work.
2292  */
2293 int
2294 pci_msi_device_blacklisted(device_t dev)
2295 {
2296 
2297 	if (!pci_honor_msi_blacklist)
2298 		return (0);
2299 
2300 	return (pci_has_quirk(pci_get_devid(dev), PCI_QUIRK_DISABLE_MSI));
2301 }
2302 
2303 /*
2304  * Determine if MSI is blacklisted globally on this system.  Currently,
2305  * we just check for blacklisted chipsets as represented by the
2306  * host-PCI bridge at device 0:0:0.  In the future, it may become
2307  * necessary to check other system attributes, such as the kenv values
2308  * that give the motherboard manufacturer and model number.
2309  */
2310 static int
2311 pci_msi_blacklisted(void)
2312 {
2313 	device_t dev;
2314 
2315 	if (!pci_honor_msi_blacklist)
2316 		return (0);
2317 
2318 	/* Blacklist all non-PCI-express and non-PCI-X chipsets. */
2319 	if (!(pcie_chipset || pcix_chipset)) {
2320 		if (vm_guest != VM_GUEST_NO) {
2321 			/*
2322 			 * Whitelist older chipsets in virtual
2323 			 * machines known to support MSI.
2324 			 */
2325 			dev = pci_find_bsf(0, 0, 0);
2326 			if (dev != NULL)
2327 				return (!pci_has_quirk(pci_get_devid(dev),
2328 					PCI_QUIRK_ENABLE_MSI_VM));
2329 		}
2330 		return (1);
2331 	}
2332 
2333 	dev = pci_find_bsf(0, 0, 0);
2334 	if (dev != NULL)
2335 		return (pci_msi_device_blacklisted(dev));
2336 	return (0);
2337 }
2338 
2339 /*
2340  * Returns true if the specified device is blacklisted because MSI-X
2341  * doesn't work.  Note that this assumes that if MSI doesn't work,
2342  * MSI-X doesn't either.
2343  */
2344 int
2345 pci_msix_device_blacklisted(device_t dev)
2346 {
2347 
2348 	if (!pci_honor_msi_blacklist)
2349 		return (0);
2350 
2351 	if (pci_has_quirk(pci_get_devid(dev), PCI_QUIRK_DISABLE_MSIX))
2352 		return (1);
2353 
2354 	return (pci_msi_device_blacklisted(dev));
2355 }
2356 
2357 /*
2358  * Determine if MSI-X is blacklisted globally on this system.  If MSI
2359  * is blacklisted, assume that MSI-X is as well.  Check for additional
2360  * chipsets where MSI works but MSI-X does not.
2361  */
2362 static int
2363 pci_msix_blacklisted(void)
2364 {
2365 	device_t dev;
2366 
2367 	if (!pci_honor_msi_blacklist)
2368 		return (0);
2369 
2370 	dev = pci_find_bsf(0, 0, 0);
2371 	if (dev != NULL && pci_has_quirk(pci_get_devid(dev),
2372 	    PCI_QUIRK_DISABLE_MSIX))
2373 		return (1);
2374 
2375 	return (pci_msi_blacklisted());
2376 }
2377 
2378 /*
2379  * Attempt to allocate *count MSI messages.  The actual number allocated is
2380  * returned in *count.  After this function returns, each message will be
2381  * available to the driver as SYS_RES_IRQ resources starting at a rid 1.
2382  */
2383 int
2384 pci_alloc_msi_method(device_t dev, device_t child, int *count)
2385 {
2386 	struct pci_devinfo *dinfo = device_get_ivars(child);
2387 	pcicfgregs *cfg = &dinfo->cfg;
2388 	struct resource_list_entry *rle;
2389 	int actual, error, i, irqs[32];
2390 	uint16_t ctrl;
2391 
2392 	/* Don't let count == 0 get us into trouble. */
2393 	if (*count == 0)
2394 		return (EINVAL);
2395 
2396 	/* If rid 0 is allocated, then fail. */
2397 	rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, 0);
2398 	if (rle != NULL && rle->res != NULL)
2399 		return (ENXIO);
2400 
2401 	/* Already have allocated messages? */
2402 	if (cfg->msi.msi_alloc != 0 || cfg->msix.msix_alloc != 0)
2403 		return (ENXIO);
2404 
2405 	/* If MSI is blacklisted for this system, fail. */
2406 	if (pci_msi_blacklisted())
2407 		return (ENXIO);
2408 
2409 	/* MSI capability present? */
2410 	if (cfg->msi.msi_location == 0 || !pci_do_msi)
2411 		return (ENODEV);
2412 
2413 	if (bootverbose)
2414 		device_printf(child,
2415 		    "attempting to allocate %d MSI vectors (%d supported)\n",
2416 		    *count, cfg->msi.msi_msgnum);
2417 
2418 	/* Don't ask for more than the device supports. */
2419 	actual = min(*count, cfg->msi.msi_msgnum);
2420 
2421 	/* Don't ask for more than 32 messages. */
2422 	actual = min(actual, 32);
2423 
2424 	/* MSI requires power of 2 number of messages. */
2425 	if (!powerof2(actual))
2426 		return (EINVAL);
2427 
2428 	for (;;) {
2429 		/* Try to allocate N messages. */
2430 		error = PCIB_ALLOC_MSI(device_get_parent(dev), child, actual,
2431 		    actual, irqs);
2432 		if (error == 0)
2433 			break;
2434 		if (actual == 1)
2435 			return (error);
2436 
2437 		/* Try N / 2. */
2438 		actual >>= 1;
2439 	}
2440 
2441 	/*
2442 	 * We now have N actual messages mapped onto SYS_RES_IRQ
2443 	 * resources in the irqs[] array, so add new resources
2444 	 * starting at rid 1.
2445 	 */
2446 	for (i = 0; i < actual; i++)
2447 		resource_list_add(&dinfo->resources, SYS_RES_IRQ, i + 1,
2448 		    irqs[i], irqs[i], 1);
2449 
2450 	if (bootverbose) {
2451 		if (actual == 1)
2452 			device_printf(child, "using IRQ %d for MSI\n", irqs[0]);
2453 		else {
2454 			int run;
2455 
2456 			/*
2457 			 * Be fancy and try to print contiguous runs
2458 			 * of IRQ values as ranges.  'run' is true if
2459 			 * we are in a range.
2460 			 */
2461 			device_printf(child, "using IRQs %d", irqs[0]);
2462 			run = 0;
2463 			for (i = 1; i < actual; i++) {
2464 
2465 				/* Still in a run? */
2466 				if (irqs[i] == irqs[i - 1] + 1) {
2467 					run = 1;
2468 					continue;
2469 				}
2470 
2471 				/* Finish previous range. */
2472 				if (run) {
2473 					printf("-%d", irqs[i - 1]);
2474 					run = 0;
2475 				}
2476 
2477 				/* Start new range. */
2478 				printf(",%d", irqs[i]);
2479 			}
2480 
2481 			/* Unfinished range? */
2482 			if (run)
2483 				printf("-%d", irqs[actual - 1]);
2484 			printf(" for MSI\n");
2485 		}
2486 	}
2487 
2488 	/* Update control register with actual count. */
2489 	ctrl = cfg->msi.msi_ctrl;
2490 	ctrl &= ~PCIM_MSICTRL_MME_MASK;
2491 	ctrl |= (ffs(actual) - 1) << 4;
2492 	cfg->msi.msi_ctrl = ctrl;
2493 	pci_write_config(child, cfg->msi.msi_location + PCIR_MSI_CTRL, ctrl, 2);
2494 
2495 	/* Update counts of alloc'd messages. */
2496 	cfg->msi.msi_alloc = actual;
2497 	cfg->msi.msi_handlers = 0;
2498 	*count = actual;
2499 	return (0);
2500 }
2501 
2502 /* Release the MSI messages associated with this device. */
2503 int
2504 pci_release_msi_method(device_t dev, device_t child)
2505 {
2506 	struct pci_devinfo *dinfo = device_get_ivars(child);
2507 	struct pcicfg_msi *msi = &dinfo->cfg.msi;
2508 	struct resource_list_entry *rle;
2509 	int error, i, irqs[32];
2510 
2511 	/* Try MSI-X first. */
2512 	error = pci_release_msix(dev, child);
2513 	if (error != ENODEV)
2514 		return (error);
2515 
2516 	/* Do we have any messages to release? */
2517 	if (msi->msi_alloc == 0)
2518 		return (ENODEV);
2519 	KASSERT(msi->msi_alloc <= 32, ("more than 32 alloc'd messages"));
2520 
2521 	/* Make sure none of the resources are allocated. */
2522 	if (msi->msi_handlers > 0)
2523 		return (EBUSY);
2524 	for (i = 0; i < msi->msi_alloc; i++) {
2525 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, i + 1);
2526 		KASSERT(rle != NULL, ("missing MSI resource"));
2527 		if (rle->res != NULL)
2528 			return (EBUSY);
2529 		irqs[i] = rle->start;
2530 	}
2531 
2532 	/* Update control register with 0 count. */
2533 	KASSERT(!(msi->msi_ctrl & PCIM_MSICTRL_MSI_ENABLE),
2534 	    ("%s: MSI still enabled", __func__));
2535 	msi->msi_ctrl &= ~PCIM_MSICTRL_MME_MASK;
2536 	pci_write_config(child, msi->msi_location + PCIR_MSI_CTRL,
2537 	    msi->msi_ctrl, 2);
2538 
2539 	/* Release the messages. */
2540 	PCIB_RELEASE_MSI(device_get_parent(dev), child, msi->msi_alloc, irqs);
2541 	for (i = 0; i < msi->msi_alloc; i++)
2542 		resource_list_delete(&dinfo->resources, SYS_RES_IRQ, i + 1);
2543 
2544 	/* Update alloc count. */
2545 	msi->msi_alloc = 0;
2546 	msi->msi_addr = 0;
2547 	msi->msi_data = 0;
2548 	return (0);
2549 }
2550 
2551 /*
2552  * Return the max supported MSI messages this device supports.
2553  * Basically, assuming the MD code can alloc messages, this function
2554  * should return the maximum value that pci_alloc_msi() can return.
2555  * Thus, it is subject to the tunables, etc.
2556  */
2557 int
2558 pci_msi_count_method(device_t dev, device_t child)
2559 {
2560 	struct pci_devinfo *dinfo = device_get_ivars(child);
2561 	struct pcicfg_msi *msi = &dinfo->cfg.msi;
2562 
2563 	if (pci_do_msi && msi->msi_location != 0)
2564 		return (msi->msi_msgnum);
2565 	return (0);
2566 }
2567 
2568 /* free pcicfgregs structure and all depending data structures */
2569 
2570 int
2571 pci_freecfg(struct pci_devinfo *dinfo)
2572 {
2573 	struct devlist *devlist_head;
2574 	struct pci_map *pm, *next;
2575 	int i;
2576 
2577 	devlist_head = &pci_devq;
2578 
2579 	if (dinfo->cfg.vpd.vpd_reg) {
2580 		free(dinfo->cfg.vpd.vpd_ident, M_DEVBUF);
2581 		for (i = 0; i < dinfo->cfg.vpd.vpd_rocnt; i++)
2582 			free(dinfo->cfg.vpd.vpd_ros[i].value, M_DEVBUF);
2583 		free(dinfo->cfg.vpd.vpd_ros, M_DEVBUF);
2584 		for (i = 0; i < dinfo->cfg.vpd.vpd_wcnt; i++)
2585 			free(dinfo->cfg.vpd.vpd_w[i].value, M_DEVBUF);
2586 		free(dinfo->cfg.vpd.vpd_w, M_DEVBUF);
2587 	}
2588 	STAILQ_FOREACH_SAFE(pm, &dinfo->cfg.maps, pm_link, next) {
2589 		free(pm, M_DEVBUF);
2590 	}
2591 	STAILQ_REMOVE(devlist_head, dinfo, pci_devinfo, pci_links);
2592 	free(dinfo, M_DEVBUF);
2593 
2594 	/* increment the generation count */
2595 	pci_generation++;
2596 
2597 	/* we're losing one device */
2598 	pci_numdevs--;
2599 	return (0);
2600 }
2601 
2602 /*
2603  * PCI power manangement
2604  */
2605 int
2606 pci_set_powerstate_method(device_t dev, device_t child, int state)
2607 {
2608 	struct pci_devinfo *dinfo = device_get_ivars(child);
2609 	pcicfgregs *cfg = &dinfo->cfg;
2610 	uint16_t status;
2611 	int oldstate, highest, delay;
2612 
2613 	if (cfg->pp.pp_cap == 0)
2614 		return (EOPNOTSUPP);
2615 
2616 	/*
2617 	 * Optimize a no state change request away.  While it would be OK to
2618 	 * write to the hardware in theory, some devices have shown odd
2619 	 * behavior when going from D3 -> D3.
2620 	 */
2621 	oldstate = pci_get_powerstate(child);
2622 	if (oldstate == state)
2623 		return (0);
2624 
2625 	/*
2626 	 * The PCI power management specification states that after a state
2627 	 * transition between PCI power states, system software must
2628 	 * guarantee a minimal delay before the function accesses the device.
2629 	 * Compute the worst case delay that we need to guarantee before we
2630 	 * access the device.  Many devices will be responsive much more
2631 	 * quickly than this delay, but there are some that don't respond
2632 	 * instantly to state changes.  Transitions to/from D3 state require
2633 	 * 10ms, while D2 requires 200us, and D0/1 require none.  The delay
2634 	 * is done below with DELAY rather than a sleeper function because
2635 	 * this function can be called from contexts where we cannot sleep.
2636 	 */
2637 	highest = (oldstate > state) ? oldstate : state;
2638 	if (highest == PCI_POWERSTATE_D3)
2639 	    delay = 10000;
2640 	else if (highest == PCI_POWERSTATE_D2)
2641 	    delay = 200;
2642 	else
2643 	    delay = 0;
2644 	status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2)
2645 	    & ~PCIM_PSTAT_DMASK;
2646 	switch (state) {
2647 	case PCI_POWERSTATE_D0:
2648 		status |= PCIM_PSTAT_D0;
2649 		break;
2650 	case PCI_POWERSTATE_D1:
2651 		if ((cfg->pp.pp_cap & PCIM_PCAP_D1SUPP) == 0)
2652 			return (EOPNOTSUPP);
2653 		status |= PCIM_PSTAT_D1;
2654 		break;
2655 	case PCI_POWERSTATE_D2:
2656 		if ((cfg->pp.pp_cap & PCIM_PCAP_D2SUPP) == 0)
2657 			return (EOPNOTSUPP);
2658 		status |= PCIM_PSTAT_D2;
2659 		break;
2660 	case PCI_POWERSTATE_D3:
2661 		status |= PCIM_PSTAT_D3;
2662 		break;
2663 	default:
2664 		return (EINVAL);
2665 	}
2666 
2667 	if (bootverbose)
2668 		pci_printf(cfg, "Transition from D%d to D%d\n", oldstate,
2669 		    state);
2670 
2671 	PCI_WRITE_CONFIG(dev, child, cfg->pp.pp_status, status, 2);
2672 	if (delay)
2673 		DELAY(delay);
2674 	return (0);
2675 }
2676 
2677 int
2678 pci_get_powerstate_method(device_t dev, device_t child)
2679 {
2680 	struct pci_devinfo *dinfo = device_get_ivars(child);
2681 	pcicfgregs *cfg = &dinfo->cfg;
2682 	uint16_t status;
2683 	int result;
2684 
2685 	if (cfg->pp.pp_cap != 0) {
2686 		status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2);
2687 		switch (status & PCIM_PSTAT_DMASK) {
2688 		case PCIM_PSTAT_D0:
2689 			result = PCI_POWERSTATE_D0;
2690 			break;
2691 		case PCIM_PSTAT_D1:
2692 			result = PCI_POWERSTATE_D1;
2693 			break;
2694 		case PCIM_PSTAT_D2:
2695 			result = PCI_POWERSTATE_D2;
2696 			break;
2697 		case PCIM_PSTAT_D3:
2698 			result = PCI_POWERSTATE_D3;
2699 			break;
2700 		default:
2701 			result = PCI_POWERSTATE_UNKNOWN;
2702 			break;
2703 		}
2704 	} else {
2705 		/* No support, device is always at D0 */
2706 		result = PCI_POWERSTATE_D0;
2707 	}
2708 	return (result);
2709 }
2710 
2711 /*
2712  * Some convenience functions for PCI device drivers.
2713  */
2714 
2715 static __inline void
2716 pci_set_command_bit(device_t dev, device_t child, uint16_t bit)
2717 {
2718 	uint16_t	command;
2719 
2720 	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
2721 	command |= bit;
2722 	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
2723 }
2724 
2725 static __inline void
2726 pci_clear_command_bit(device_t dev, device_t child, uint16_t bit)
2727 {
2728 	uint16_t	command;
2729 
2730 	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
2731 	command &= ~bit;
2732 	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
2733 }
2734 
2735 int
2736 pci_enable_busmaster_method(device_t dev, device_t child)
2737 {
2738 	pci_set_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
2739 	return (0);
2740 }
2741 
2742 int
2743 pci_disable_busmaster_method(device_t dev, device_t child)
2744 {
2745 	pci_clear_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
2746 	return (0);
2747 }
2748 
2749 int
2750 pci_enable_io_method(device_t dev, device_t child, int space)
2751 {
2752 	uint16_t bit;
2753 
2754 	switch(space) {
2755 	case SYS_RES_IOPORT:
2756 		bit = PCIM_CMD_PORTEN;
2757 		break;
2758 	case SYS_RES_MEMORY:
2759 		bit = PCIM_CMD_MEMEN;
2760 		break;
2761 	default:
2762 		return (EINVAL);
2763 	}
2764 	pci_set_command_bit(dev, child, bit);
2765 	return (0);
2766 }
2767 
2768 int
2769 pci_disable_io_method(device_t dev, device_t child, int space)
2770 {
2771 	uint16_t bit;
2772 
2773 	switch(space) {
2774 	case SYS_RES_IOPORT:
2775 		bit = PCIM_CMD_PORTEN;
2776 		break;
2777 	case SYS_RES_MEMORY:
2778 		bit = PCIM_CMD_MEMEN;
2779 		break;
2780 	default:
2781 		return (EINVAL);
2782 	}
2783 	pci_clear_command_bit(dev, child, bit);
2784 	return (0);
2785 }
2786 
2787 /*
2788  * New style pci driver.  Parent device is either a pci-host-bridge or a
2789  * pci-pci-bridge.  Both kinds are represented by instances of pcib.
2790  */
2791 
2792 void
2793 pci_print_verbose(struct pci_devinfo *dinfo)
2794 {
2795 
2796 	if (bootverbose) {
2797 		pcicfgregs *cfg = &dinfo->cfg;
2798 
2799 		printf("found->\tvendor=0x%04x, dev=0x%04x, revid=0x%02x\n",
2800 		    cfg->vendor, cfg->device, cfg->revid);
2801 		printf("\tdomain=%d, bus=%d, slot=%d, func=%d\n",
2802 		    cfg->domain, cfg->bus, cfg->slot, cfg->func);
2803 		printf("\tclass=%02x-%02x-%02x, hdrtype=0x%02x, mfdev=%d\n",
2804 		    cfg->baseclass, cfg->subclass, cfg->progif, cfg->hdrtype,
2805 		    cfg->mfdev);
2806 		printf("\tcmdreg=0x%04x, statreg=0x%04x, cachelnsz=%d (dwords)\n",
2807 		    cfg->cmdreg, cfg->statreg, cfg->cachelnsz);
2808 		printf("\tlattimer=0x%02x (%d ns), mingnt=0x%02x (%d ns), maxlat=0x%02x (%d ns)\n",
2809 		    cfg->lattimer, cfg->lattimer * 30, cfg->mingnt,
2810 		    cfg->mingnt * 250, cfg->maxlat, cfg->maxlat * 250);
2811 		if (cfg->intpin > 0)
2812 			printf("\tintpin=%c, irq=%d\n",
2813 			    cfg->intpin +'a' -1, cfg->intline);
2814 		if (cfg->pp.pp_cap) {
2815 			uint16_t status;
2816 
2817 			status = pci_read_config(cfg->dev, cfg->pp.pp_status, 2);
2818 			printf("\tpowerspec %d  supports D0%s%s D3  current D%d\n",
2819 			    cfg->pp.pp_cap & PCIM_PCAP_SPEC,
2820 			    cfg->pp.pp_cap & PCIM_PCAP_D1SUPP ? " D1" : "",
2821 			    cfg->pp.pp_cap & PCIM_PCAP_D2SUPP ? " D2" : "",
2822 			    status & PCIM_PSTAT_DMASK);
2823 		}
2824 		if (cfg->msi.msi_location) {
2825 			int ctrl;
2826 
2827 			ctrl = cfg->msi.msi_ctrl;
2828 			printf("\tMSI supports %d message%s%s%s\n",
2829 			    cfg->msi.msi_msgnum,
2830 			    (cfg->msi.msi_msgnum == 1) ? "" : "s",
2831 			    (ctrl & PCIM_MSICTRL_64BIT) ? ", 64 bit" : "",
2832 			    (ctrl & PCIM_MSICTRL_VECTOR) ? ", vector masks":"");
2833 		}
2834 		if (cfg->msix.msix_location) {
2835 			printf("\tMSI-X supports %d message%s ",
2836 			    cfg->msix.msix_msgnum,
2837 			    (cfg->msix.msix_msgnum == 1) ? "" : "s");
2838 			if (cfg->msix.msix_table_bar == cfg->msix.msix_pba_bar)
2839 				printf("in map 0x%x\n",
2840 				    cfg->msix.msix_table_bar);
2841 			else
2842 				printf("in maps 0x%x and 0x%x\n",
2843 				    cfg->msix.msix_table_bar,
2844 				    cfg->msix.msix_pba_bar);
2845 		}
2846 	}
2847 }
2848 
2849 static int
2850 pci_porten(device_t dev)
2851 {
2852 	return (pci_read_config(dev, PCIR_COMMAND, 2) & PCIM_CMD_PORTEN) != 0;
2853 }
2854 
2855 static int
2856 pci_memen(device_t dev)
2857 {
2858 	return (pci_read_config(dev, PCIR_COMMAND, 2) & PCIM_CMD_MEMEN) != 0;
2859 }
2860 
2861 void
2862 pci_read_bar(device_t dev, int reg, pci_addr_t *mapp, pci_addr_t *testvalp,
2863     int *bar64)
2864 {
2865 	struct pci_devinfo *dinfo;
2866 	pci_addr_t map, testval;
2867 	int ln2range;
2868 	uint16_t cmd;
2869 
2870 	/*
2871 	 * The device ROM BAR is special.  It is always a 32-bit
2872 	 * memory BAR.  Bit 0 is special and should not be set when
2873 	 * sizing the BAR.
2874 	 */
2875 	dinfo = device_get_ivars(dev);
2876 	if (PCIR_IS_BIOS(&dinfo->cfg, reg)) {
2877 		map = pci_read_config(dev, reg, 4);
2878 		pci_write_config(dev, reg, 0xfffffffe, 4);
2879 		testval = pci_read_config(dev, reg, 4);
2880 		pci_write_config(dev, reg, map, 4);
2881 		*mapp = map;
2882 		*testvalp = testval;
2883 		if (bar64 != NULL)
2884 			*bar64 = 0;
2885 		return;
2886 	}
2887 
2888 	map = pci_read_config(dev, reg, 4);
2889 	ln2range = pci_maprange(map);
2890 	if (ln2range == 64)
2891 		map |= (pci_addr_t)pci_read_config(dev, reg + 4, 4) << 32;
2892 
2893 	/*
2894 	 * Disable decoding via the command register before
2895 	 * determining the BAR's length since we will be placing it in
2896 	 * a weird state.
2897 	 */
2898 	cmd = pci_read_config(dev, PCIR_COMMAND, 2);
2899 	pci_write_config(dev, PCIR_COMMAND,
2900 	    cmd & ~(PCI_BAR_MEM(map) ? PCIM_CMD_MEMEN : PCIM_CMD_PORTEN), 2);
2901 
2902 	/*
2903 	 * Determine the BAR's length by writing all 1's.  The bottom
2904 	 * log_2(size) bits of the BAR will stick as 0 when we read
2905 	 * the value back.
2906 	 *
2907 	 * NB: according to the PCI Local Bus Specification, rev. 3.0:
2908 	 * "Software writes 0FFFFFFFFh to both registers, reads them back,
2909 	 * and combines the result into a 64-bit value." (section 6.2.5.1)
2910 	 *
2911 	 * Writes to both registers must be performed before attempting to
2912 	 * read back the size value.
2913 	 */
2914 	testval = 0;
2915 	pci_write_config(dev, reg, 0xffffffff, 4);
2916 	if (ln2range == 64) {
2917 		pci_write_config(dev, reg + 4, 0xffffffff, 4);
2918 		testval |= (pci_addr_t)pci_read_config(dev, reg + 4, 4) << 32;
2919 	}
2920 	testval |= pci_read_config(dev, reg, 4);
2921 
2922 	/*
2923 	 * Restore the original value of the BAR.  We may have reprogrammed
2924 	 * the BAR of the low-level console device and when booting verbose,
2925 	 * we need the console device addressable.
2926 	 */
2927 	pci_write_config(dev, reg, map, 4);
2928 	if (ln2range == 64)
2929 		pci_write_config(dev, reg + 4, map >> 32, 4);
2930 	pci_write_config(dev, PCIR_COMMAND, cmd, 2);
2931 
2932 	*mapp = map;
2933 	*testvalp = testval;
2934 	if (bar64 != NULL)
2935 		*bar64 = (ln2range == 64);
2936 }
2937 
2938 static void
2939 pci_write_bar(device_t dev, struct pci_map *pm, pci_addr_t base)
2940 {
2941 	struct pci_devinfo *dinfo;
2942 	int ln2range;
2943 
2944 	/* The device ROM BAR is always a 32-bit memory BAR. */
2945 	dinfo = device_get_ivars(dev);
2946 	if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg))
2947 		ln2range = 32;
2948 	else
2949 		ln2range = pci_maprange(pm->pm_value);
2950 	pci_write_config(dev, pm->pm_reg, base, 4);
2951 	if (ln2range == 64)
2952 		pci_write_config(dev, pm->pm_reg + 4, base >> 32, 4);
2953 	pm->pm_value = pci_read_config(dev, pm->pm_reg, 4);
2954 	if (ln2range == 64)
2955 		pm->pm_value |= (pci_addr_t)pci_read_config(dev,
2956 		    pm->pm_reg + 4, 4) << 32;
2957 }
2958 
2959 struct pci_map *
2960 pci_find_bar(device_t dev, int reg)
2961 {
2962 	struct pci_devinfo *dinfo;
2963 	struct pci_map *pm;
2964 
2965 	dinfo = device_get_ivars(dev);
2966 	STAILQ_FOREACH(pm, &dinfo->cfg.maps, pm_link) {
2967 		if (pm->pm_reg == reg)
2968 			return (pm);
2969 	}
2970 	return (NULL);
2971 }
2972 
2973 int
2974 pci_bar_enabled(device_t dev, struct pci_map *pm)
2975 {
2976 	struct pci_devinfo *dinfo;
2977 	uint16_t cmd;
2978 
2979 	dinfo = device_get_ivars(dev);
2980 	if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg) &&
2981 	    !(pm->pm_value & PCIM_BIOS_ENABLE))
2982 		return (0);
2983 	cmd = pci_read_config(dev, PCIR_COMMAND, 2);
2984 	if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg) || PCI_BAR_MEM(pm->pm_value))
2985 		return ((cmd & PCIM_CMD_MEMEN) != 0);
2986 	else
2987 		return ((cmd & PCIM_CMD_PORTEN) != 0);
2988 }
2989 
2990 struct pci_map *
2991 pci_add_bar(device_t dev, int reg, pci_addr_t value, pci_addr_t size)
2992 {
2993 	struct pci_devinfo *dinfo;
2994 	struct pci_map *pm, *prev;
2995 
2996 	dinfo = device_get_ivars(dev);
2997 	pm = malloc(sizeof(*pm), M_DEVBUF, M_WAITOK | M_ZERO);
2998 	pm->pm_reg = reg;
2999 	pm->pm_value = value;
3000 	pm->pm_size = size;
3001 	STAILQ_FOREACH(prev, &dinfo->cfg.maps, pm_link) {
3002 		KASSERT(prev->pm_reg != pm->pm_reg, ("duplicate map %02x",
3003 		    reg));
3004 		if (STAILQ_NEXT(prev, pm_link) == NULL ||
3005 		    STAILQ_NEXT(prev, pm_link)->pm_reg > pm->pm_reg)
3006 			break;
3007 	}
3008 	if (prev != NULL)
3009 		STAILQ_INSERT_AFTER(&dinfo->cfg.maps, prev, pm, pm_link);
3010 	else
3011 		STAILQ_INSERT_TAIL(&dinfo->cfg.maps, pm, pm_link);
3012 	return (pm);
3013 }
3014 
3015 static void
3016 pci_restore_bars(device_t dev)
3017 {
3018 	struct pci_devinfo *dinfo;
3019 	struct pci_map *pm;
3020 	int ln2range;
3021 
3022 	dinfo = device_get_ivars(dev);
3023 	STAILQ_FOREACH(pm, &dinfo->cfg.maps, pm_link) {
3024 		if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg))
3025 			ln2range = 32;
3026 		else
3027 			ln2range = pci_maprange(pm->pm_value);
3028 		pci_write_config(dev, pm->pm_reg, pm->pm_value, 4);
3029 		if (ln2range == 64)
3030 			pci_write_config(dev, pm->pm_reg + 4,
3031 			    pm->pm_value >> 32, 4);
3032 	}
3033 }
3034 
3035 /*
3036  * Add a resource based on a pci map register. Return 1 if the map
3037  * register is a 32bit map register or 2 if it is a 64bit register.
3038  */
3039 static int
3040 pci_add_map(device_t bus, device_t dev, int reg, struct resource_list *rl,
3041     int force, int prefetch)
3042 {
3043 	struct pci_map *pm;
3044 	pci_addr_t base, map, testval;
3045 	pci_addr_t start, end, count;
3046 	int barlen, basezero, flags, maprange, mapsize, type;
3047 	uint16_t cmd;
3048 	struct resource *res;
3049 
3050 	/*
3051 	 * The BAR may already exist if the device is a CardBus card
3052 	 * whose CIS is stored in this BAR.
3053 	 */
3054 	pm = pci_find_bar(dev, reg);
3055 	if (pm != NULL) {
3056 		maprange = pci_maprange(pm->pm_value);
3057 		barlen = maprange == 64 ? 2 : 1;
3058 		return (barlen);
3059 	}
3060 
3061 	pci_read_bar(dev, reg, &map, &testval, NULL);
3062 	if (PCI_BAR_MEM(map)) {
3063 		type = SYS_RES_MEMORY;
3064 		if (map & PCIM_BAR_MEM_PREFETCH)
3065 			prefetch = 1;
3066 	} else
3067 		type = SYS_RES_IOPORT;
3068 	mapsize = pci_mapsize(testval);
3069 	base = pci_mapbase(map);
3070 #ifdef __PCI_BAR_ZERO_VALID
3071 	basezero = 0;
3072 #else
3073 	basezero = base == 0;
3074 #endif
3075 	maprange = pci_maprange(map);
3076 	barlen = maprange == 64 ? 2 : 1;
3077 
3078 	/*
3079 	 * For I/O registers, if bottom bit is set, and the next bit up
3080 	 * isn't clear, we know we have a BAR that doesn't conform to the
3081 	 * spec, so ignore it.  Also, sanity check the size of the data
3082 	 * areas to the type of memory involved.  Memory must be at least
3083 	 * 16 bytes in size, while I/O ranges must be at least 4.
3084 	 */
3085 	if (PCI_BAR_IO(testval) && (testval & PCIM_BAR_IO_RESERVED) != 0)
3086 		return (barlen);
3087 	if ((type == SYS_RES_MEMORY && mapsize < 4) ||
3088 	    (type == SYS_RES_IOPORT && mapsize < 2))
3089 		return (barlen);
3090 
3091 	/* Save a record of this BAR. */
3092 	pm = pci_add_bar(dev, reg, map, mapsize);
3093 	if (bootverbose) {
3094 		printf("\tmap[%02x]: type %s, range %2d, base %#jx, size %2d",
3095 		    reg, pci_maptype(map), maprange, (uintmax_t)base, mapsize);
3096 		if (type == SYS_RES_IOPORT && !pci_porten(dev))
3097 			printf(", port disabled\n");
3098 		else if (type == SYS_RES_MEMORY && !pci_memen(dev))
3099 			printf(", memory disabled\n");
3100 		else
3101 			printf(", enabled\n");
3102 	}
3103 
3104 	/*
3105 	 * If base is 0, then we have problems if this architecture does
3106 	 * not allow that.  It is best to ignore such entries for the
3107 	 * moment.  These will be allocated later if the driver specifically
3108 	 * requests them.  However, some removable buses look better when
3109 	 * all resources are allocated, so allow '0' to be overriden.
3110 	 *
3111 	 * Similarly treat maps whose values is the same as the test value
3112 	 * read back.  These maps have had all f's written to them by the
3113 	 * BIOS in an attempt to disable the resources.
3114 	 */
3115 	if (!force && (basezero || map == testval))
3116 		return (barlen);
3117 	if ((u_long)base != base) {
3118 		device_printf(bus,
3119 		    "pci%d:%d:%d:%d bar %#x too many address bits",
3120 		    pci_get_domain(dev), pci_get_bus(dev), pci_get_slot(dev),
3121 		    pci_get_function(dev), reg);
3122 		return (barlen);
3123 	}
3124 
3125 	/*
3126 	 * This code theoretically does the right thing, but has
3127 	 * undesirable side effects in some cases where peripherals
3128 	 * respond oddly to having these bits enabled.  Let the user
3129 	 * be able to turn them off (since pci_enable_io_modes is 1 by
3130 	 * default).
3131 	 */
3132 	if (pci_enable_io_modes) {
3133 		/* Turn on resources that have been left off by a lazy BIOS */
3134 		if (type == SYS_RES_IOPORT && !pci_porten(dev)) {
3135 			cmd = pci_read_config(dev, PCIR_COMMAND, 2);
3136 			cmd |= PCIM_CMD_PORTEN;
3137 			pci_write_config(dev, PCIR_COMMAND, cmd, 2);
3138 		}
3139 		if (type == SYS_RES_MEMORY && !pci_memen(dev)) {
3140 			cmd = pci_read_config(dev, PCIR_COMMAND, 2);
3141 			cmd |= PCIM_CMD_MEMEN;
3142 			pci_write_config(dev, PCIR_COMMAND, cmd, 2);
3143 		}
3144 	} else {
3145 		if (type == SYS_RES_IOPORT && !pci_porten(dev))
3146 			return (barlen);
3147 		if (type == SYS_RES_MEMORY && !pci_memen(dev))
3148 			return (barlen);
3149 	}
3150 
3151 	count = (pci_addr_t)1 << mapsize;
3152 	flags = RF_ALIGNMENT_LOG2(mapsize);
3153 	if (prefetch)
3154 		flags |= RF_PREFETCHABLE;
3155 	if (basezero || base == pci_mapbase(testval) || pci_clear_bars) {
3156 		start = 0;	/* Let the parent decide. */
3157 		end = ~0;
3158 	} else {
3159 		start = base;
3160 		end = base + count - 1;
3161 	}
3162 	resource_list_add(rl, type, reg, start, end, count);
3163 
3164 	/*
3165 	 * Try to allocate the resource for this BAR from our parent
3166 	 * so that this resource range is already reserved.  The
3167 	 * driver for this device will later inherit this resource in
3168 	 * pci_alloc_resource().
3169 	 */
3170 	res = resource_list_reserve(rl, bus, dev, type, &reg, start, end, count,
3171 	    flags);
3172 	if (pci_do_realloc_bars && res == NULL && (start != 0 || end != ~0)) {
3173 		/*
3174 		 * If the allocation fails, try to allocate a resource for
3175 		 * this BAR using any available range.  The firmware felt
3176 		 * it was important enough to assign a resource, so don't
3177 		 * disable decoding if we can help it.
3178 		 */
3179 		resource_list_delete(rl, type, reg);
3180 		resource_list_add(rl, type, reg, 0, ~0, count);
3181 		res = resource_list_reserve(rl, bus, dev, type, &reg, 0, ~0,
3182 		    count, flags);
3183 	}
3184 	if (res == NULL) {
3185 		/*
3186 		 * If the allocation fails, delete the resource list entry
3187 		 * and disable decoding for this device.
3188 		 *
3189 		 * If the driver requests this resource in the future,
3190 		 * pci_reserve_map() will try to allocate a fresh
3191 		 * resource range.
3192 		 */
3193 		resource_list_delete(rl, type, reg);
3194 		pci_disable_io(dev, type);
3195 		if (bootverbose)
3196 			device_printf(bus,
3197 			    "pci%d:%d:%d:%d bar %#x failed to allocate\n",
3198 			    pci_get_domain(dev), pci_get_bus(dev),
3199 			    pci_get_slot(dev), pci_get_function(dev), reg);
3200 	} else {
3201 		start = rman_get_start(res);
3202 		pci_write_bar(dev, pm, start);
3203 	}
3204 	return (barlen);
3205 }
3206 
3207 /*
3208  * For ATA devices we need to decide early what addressing mode to use.
3209  * Legacy demands that the primary and secondary ATA ports sits on the
3210  * same addresses that old ISA hardware did. This dictates that we use
3211  * those addresses and ignore the BAR's if we cannot set PCI native
3212  * addressing mode.
3213  */
3214 static void
3215 pci_ata_maps(device_t bus, device_t dev, struct resource_list *rl, int force,
3216     uint32_t prefetchmask)
3217 {
3218 	int rid, type, progif;
3219 #if 0
3220 	/* if this device supports PCI native addressing use it */
3221 	progif = pci_read_config(dev, PCIR_PROGIF, 1);
3222 	if ((progif & 0x8a) == 0x8a) {
3223 		if (pci_mapbase(pci_read_config(dev, PCIR_BAR(0), 4)) &&
3224 		    pci_mapbase(pci_read_config(dev, PCIR_BAR(2), 4))) {
3225 			printf("Trying ATA native PCI addressing mode\n");
3226 			pci_write_config(dev, PCIR_PROGIF, progif | 0x05, 1);
3227 		}
3228 	}
3229 #endif
3230 	progif = pci_read_config(dev, PCIR_PROGIF, 1);
3231 	type = SYS_RES_IOPORT;
3232 	if (progif & PCIP_STORAGE_IDE_MODEPRIM) {
3233 		pci_add_map(bus, dev, PCIR_BAR(0), rl, force,
3234 		    prefetchmask & (1 << 0));
3235 		pci_add_map(bus, dev, PCIR_BAR(1), rl, force,
3236 		    prefetchmask & (1 << 1));
3237 	} else {
3238 		rid = PCIR_BAR(0);
3239 		resource_list_add(rl, type, rid, 0x1f0, 0x1f7, 8);
3240 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x1f0,
3241 		    0x1f7, 8, 0);
3242 		rid = PCIR_BAR(1);
3243 		resource_list_add(rl, type, rid, 0x3f6, 0x3f6, 1);
3244 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x3f6,
3245 		    0x3f6, 1, 0);
3246 	}
3247 	if (progif & PCIP_STORAGE_IDE_MODESEC) {
3248 		pci_add_map(bus, dev, PCIR_BAR(2), rl, force,
3249 		    prefetchmask & (1 << 2));
3250 		pci_add_map(bus, dev, PCIR_BAR(3), rl, force,
3251 		    prefetchmask & (1 << 3));
3252 	} else {
3253 		rid = PCIR_BAR(2);
3254 		resource_list_add(rl, type, rid, 0x170, 0x177, 8);
3255 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x170,
3256 		    0x177, 8, 0);
3257 		rid = PCIR_BAR(3);
3258 		resource_list_add(rl, type, rid, 0x376, 0x376, 1);
3259 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x376,
3260 		    0x376, 1, 0);
3261 	}
3262 	pci_add_map(bus, dev, PCIR_BAR(4), rl, force,
3263 	    prefetchmask & (1 << 4));
3264 	pci_add_map(bus, dev, PCIR_BAR(5), rl, force,
3265 	    prefetchmask & (1 << 5));
3266 }
3267 
3268 static void
3269 pci_assign_interrupt(device_t bus, device_t dev, int force_route)
3270 {
3271 	struct pci_devinfo *dinfo = device_get_ivars(dev);
3272 	pcicfgregs *cfg = &dinfo->cfg;
3273 	char tunable_name[64];
3274 	int irq;
3275 
3276 	/* Has to have an intpin to have an interrupt. */
3277 	if (cfg->intpin == 0)
3278 		return;
3279 
3280 	/* Let the user override the IRQ with a tunable. */
3281 	irq = PCI_INVALID_IRQ;
3282 	snprintf(tunable_name, sizeof(tunable_name),
3283 	    "hw.pci%d.%d.%d.INT%c.irq",
3284 	    cfg->domain, cfg->bus, cfg->slot, cfg->intpin + 'A' - 1);
3285 	if (TUNABLE_INT_FETCH(tunable_name, &irq) && (irq >= 255 || irq <= 0))
3286 		irq = PCI_INVALID_IRQ;
3287 
3288 	/*
3289 	 * If we didn't get an IRQ via the tunable, then we either use the
3290 	 * IRQ value in the intline register or we ask the bus to route an
3291 	 * interrupt for us.  If force_route is true, then we only use the
3292 	 * value in the intline register if the bus was unable to assign an
3293 	 * IRQ.
3294 	 */
3295 	if (!PCI_INTERRUPT_VALID(irq)) {
3296 		if (!PCI_INTERRUPT_VALID(cfg->intline) || force_route)
3297 			irq = PCI_ASSIGN_INTERRUPT(bus, dev);
3298 		if (!PCI_INTERRUPT_VALID(irq))
3299 			irq = cfg->intline;
3300 	}
3301 
3302 	/* If after all that we don't have an IRQ, just bail. */
3303 	if (!PCI_INTERRUPT_VALID(irq))
3304 		return;
3305 
3306 	/* Update the config register if it changed. */
3307 	if (irq != cfg->intline) {
3308 		cfg->intline = irq;
3309 		pci_write_config(dev, PCIR_INTLINE, irq, 1);
3310 	}
3311 
3312 	/* Add this IRQ as rid 0 interrupt resource. */
3313 	resource_list_add(&dinfo->resources, SYS_RES_IRQ, 0, irq, irq, 1);
3314 }
3315 
3316 /* Perform early OHCI takeover from SMM. */
3317 static void
3318 ohci_early_takeover(device_t self)
3319 {
3320 	struct resource *res;
3321 	uint32_t ctl;
3322 	int rid;
3323 	int i;
3324 
3325 	rid = PCIR_BAR(0);
3326 	res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3327 	if (res == NULL)
3328 		return;
3329 
3330 	ctl = bus_read_4(res, OHCI_CONTROL);
3331 	if (ctl & OHCI_IR) {
3332 		if (bootverbose)
3333 			printf("ohci early: "
3334 			    "SMM active, request owner change\n");
3335 		bus_write_4(res, OHCI_COMMAND_STATUS, OHCI_OCR);
3336 		for (i = 0; (i < 100) && (ctl & OHCI_IR); i++) {
3337 			DELAY(1000);
3338 			ctl = bus_read_4(res, OHCI_CONTROL);
3339 		}
3340 		if (ctl & OHCI_IR) {
3341 			if (bootverbose)
3342 				printf("ohci early: "
3343 				    "SMM does not respond, resetting\n");
3344 			bus_write_4(res, OHCI_CONTROL, OHCI_HCFS_RESET);
3345 		}
3346 		/* Disable interrupts */
3347 		bus_write_4(res, OHCI_INTERRUPT_DISABLE, OHCI_ALL_INTRS);
3348 	}
3349 
3350 	bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3351 }
3352 
3353 /* Perform early UHCI takeover from SMM. */
3354 static void
3355 uhci_early_takeover(device_t self)
3356 {
3357 	struct resource *res;
3358 	int rid;
3359 
3360 	/*
3361 	 * Set the PIRQD enable bit and switch off all the others. We don't
3362 	 * want legacy support to interfere with us XXX Does this also mean
3363 	 * that the BIOS won't touch the keyboard anymore if it is connected
3364 	 * to the ports of the root hub?
3365 	 */
3366 	pci_write_config(self, PCI_LEGSUP, PCI_LEGSUP_USBPIRQDEN, 2);
3367 
3368 	/* Disable interrupts */
3369 	rid = PCI_UHCI_BASE_REG;
3370 	res = bus_alloc_resource_any(self, SYS_RES_IOPORT, &rid, RF_ACTIVE);
3371 	if (res != NULL) {
3372 		bus_write_2(res, UHCI_INTR, 0);
3373 		bus_release_resource(self, SYS_RES_IOPORT, rid, res);
3374 	}
3375 }
3376 
3377 /* Perform early EHCI takeover from SMM. */
3378 static void
3379 ehci_early_takeover(device_t self)
3380 {
3381 	struct resource *res;
3382 	uint32_t cparams;
3383 	uint32_t eec;
3384 	uint8_t eecp;
3385 	uint8_t bios_sem;
3386 	uint8_t offs;
3387 	int rid;
3388 	int i;
3389 
3390 	rid = PCIR_BAR(0);
3391 	res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3392 	if (res == NULL)
3393 		return;
3394 
3395 	cparams = bus_read_4(res, EHCI_HCCPARAMS);
3396 
3397 	/* Synchronise with the BIOS if it owns the controller. */
3398 	for (eecp = EHCI_HCC_EECP(cparams); eecp != 0;
3399 	    eecp = EHCI_EECP_NEXT(eec)) {
3400 		eec = pci_read_config(self, eecp, 4);
3401 		if (EHCI_EECP_ID(eec) != EHCI_EC_LEGSUP) {
3402 			continue;
3403 		}
3404 		bios_sem = pci_read_config(self, eecp +
3405 		    EHCI_LEGSUP_BIOS_SEM, 1);
3406 		if (bios_sem == 0) {
3407 			continue;
3408 		}
3409 		if (bootverbose)
3410 			printf("ehci early: "
3411 			    "SMM active, request owner change\n");
3412 
3413 		pci_write_config(self, eecp + EHCI_LEGSUP_OS_SEM, 1, 1);
3414 
3415 		for (i = 0; (i < 100) && (bios_sem != 0); i++) {
3416 			DELAY(1000);
3417 			bios_sem = pci_read_config(self, eecp +
3418 			    EHCI_LEGSUP_BIOS_SEM, 1);
3419 		}
3420 
3421 		if (bios_sem != 0) {
3422 			if (bootverbose)
3423 				printf("ehci early: "
3424 				    "SMM does not respond\n");
3425 		}
3426 		/* Disable interrupts */
3427 		offs = EHCI_CAPLENGTH(bus_read_4(res, EHCI_CAPLEN_HCIVERSION));
3428 		bus_write_4(res, offs + EHCI_USBINTR, 0);
3429 	}
3430 	bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3431 }
3432 
3433 /* Perform early XHCI takeover from SMM. */
3434 static void
3435 xhci_early_takeover(device_t self)
3436 {
3437 	struct resource *res;
3438 	uint32_t cparams;
3439 	uint32_t eec;
3440 	uint8_t eecp;
3441 	uint8_t bios_sem;
3442 	uint8_t offs;
3443 	int rid;
3444 	int i;
3445 
3446 	rid = PCIR_BAR(0);
3447 	res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3448 	if (res == NULL)
3449 		return;
3450 
3451 	cparams = bus_read_4(res, XHCI_HCSPARAMS0);
3452 
3453 	eec = -1;
3454 
3455 	/* Synchronise with the BIOS if it owns the controller. */
3456 	for (eecp = XHCI_HCS0_XECP(cparams) << 2; eecp != 0 && XHCI_XECP_NEXT(eec);
3457 	    eecp += XHCI_XECP_NEXT(eec) << 2) {
3458 		eec = bus_read_4(res, eecp);
3459 
3460 		if (XHCI_XECP_ID(eec) != XHCI_ID_USB_LEGACY)
3461 			continue;
3462 
3463 		bios_sem = bus_read_1(res, eecp + XHCI_XECP_BIOS_SEM);
3464 		if (bios_sem == 0)
3465 			continue;
3466 
3467 		if (bootverbose)
3468 			printf("xhci early: "
3469 			    "SMM active, request owner change\n");
3470 
3471 		bus_write_1(res, eecp + XHCI_XECP_OS_SEM, 1);
3472 
3473 		/* wait a maximum of 5 second */
3474 
3475 		for (i = 0; (i < 5000) && (bios_sem != 0); i++) {
3476 			DELAY(1000);
3477 			bios_sem = bus_read_1(res, eecp +
3478 			    XHCI_XECP_BIOS_SEM);
3479 		}
3480 
3481 		if (bios_sem != 0) {
3482 			if (bootverbose)
3483 				printf("xhci early: "
3484 				    "SMM does not respond\n");
3485 		}
3486 
3487 		/* Disable interrupts */
3488 		offs = bus_read_1(res, XHCI_CAPLENGTH);
3489 		bus_write_4(res, offs + XHCI_USBCMD, 0);
3490 		bus_read_4(res, offs + XHCI_USBSTS);
3491 	}
3492 	bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3493 }
3494 
3495 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
3496 static void
3497 pci_reserve_secbus(device_t bus, device_t dev, pcicfgregs *cfg,
3498     struct resource_list *rl)
3499 {
3500 	struct resource *res;
3501 	char *cp;
3502 	rman_res_t start, end, count;
3503 	int rid, sec_bus, sec_reg, sub_bus, sub_reg, sup_bus;
3504 
3505 	switch (cfg->hdrtype & PCIM_HDRTYPE) {
3506 	case PCIM_HDRTYPE_BRIDGE:
3507 		sec_reg = PCIR_SECBUS_1;
3508 		sub_reg = PCIR_SUBBUS_1;
3509 		break;
3510 	case PCIM_HDRTYPE_CARDBUS:
3511 		sec_reg = PCIR_SECBUS_2;
3512 		sub_reg = PCIR_SUBBUS_2;
3513 		break;
3514 	default:
3515 		return;
3516 	}
3517 
3518 	/*
3519 	 * If the existing bus range is valid, attempt to reserve it
3520 	 * from our parent.  If this fails for any reason, clear the
3521 	 * secbus and subbus registers.
3522 	 *
3523 	 * XXX: Should we reset sub_bus to sec_bus if it is < sec_bus?
3524 	 * This would at least preserve the existing sec_bus if it is
3525 	 * valid.
3526 	 */
3527 	sec_bus = PCI_READ_CONFIG(bus, dev, sec_reg, 1);
3528 	sub_bus = PCI_READ_CONFIG(bus, dev, sub_reg, 1);
3529 
3530 	/* Quirk handling. */
3531 	switch (pci_get_devid(dev)) {
3532 	case 0x12258086:		/* Intel 82454KX/GX (Orion) */
3533 		sup_bus = pci_read_config(dev, 0x41, 1);
3534 		if (sup_bus != 0xff) {
3535 			sec_bus = sup_bus + 1;
3536 			sub_bus = sup_bus + 1;
3537 			PCI_WRITE_CONFIG(bus, dev, sec_reg, sec_bus, 1);
3538 			PCI_WRITE_CONFIG(bus, dev, sub_reg, sub_bus, 1);
3539 		}
3540 		break;
3541 
3542 	case 0x00dd10de:
3543 		/* Compaq R3000 BIOS sets wrong subordinate bus number. */
3544 		if ((cp = kern_getenv("smbios.planar.maker")) == NULL)
3545 			break;
3546 		if (strncmp(cp, "Compal", 6) != 0) {
3547 			freeenv(cp);
3548 			break;
3549 		}
3550 		freeenv(cp);
3551 		if ((cp = kern_getenv("smbios.planar.product")) == NULL)
3552 			break;
3553 		if (strncmp(cp, "08A0", 4) != 0) {
3554 			freeenv(cp);
3555 			break;
3556 		}
3557 		freeenv(cp);
3558 		if (sub_bus < 0xa) {
3559 			sub_bus = 0xa;
3560 			PCI_WRITE_CONFIG(bus, dev, sub_reg, sub_bus, 1);
3561 		}
3562 		break;
3563 	}
3564 
3565 	if (bootverbose)
3566 		printf("\tsecbus=%d, subbus=%d\n", sec_bus, sub_bus);
3567 	if (sec_bus > 0 && sub_bus >= sec_bus) {
3568 		start = sec_bus;
3569 		end = sub_bus;
3570 		count = end - start + 1;
3571 
3572 		resource_list_add(rl, PCI_RES_BUS, 0, 0, ~0, count);
3573 
3574 		/*
3575 		 * If requested, clear secondary bus registers in
3576 		 * bridge devices to force a complete renumbering
3577 		 * rather than reserving the existing range.  However,
3578 		 * preserve the existing size.
3579 		 */
3580 		if (pci_clear_buses)
3581 			goto clear;
3582 
3583 		rid = 0;
3584 		res = resource_list_reserve(rl, bus, dev, PCI_RES_BUS, &rid,
3585 		    start, end, count, 0);
3586 		if (res != NULL)
3587 			return;
3588 
3589 		if (bootverbose)
3590 			device_printf(bus,
3591 			    "pci%d:%d:%d:%d secbus failed to allocate\n",
3592 			    pci_get_domain(dev), pci_get_bus(dev),
3593 			    pci_get_slot(dev), pci_get_function(dev));
3594 	}
3595 
3596 clear:
3597 	PCI_WRITE_CONFIG(bus, dev, sec_reg, 0, 1);
3598 	PCI_WRITE_CONFIG(bus, dev, sub_reg, 0, 1);
3599 }
3600 
3601 static struct resource *
3602 pci_alloc_secbus(device_t dev, device_t child, int *rid, rman_res_t start,
3603     rman_res_t end, rman_res_t count, u_int flags)
3604 {
3605 	struct pci_devinfo *dinfo;
3606 	pcicfgregs *cfg;
3607 	struct resource_list *rl;
3608 	struct resource *res;
3609 	int sec_reg, sub_reg;
3610 
3611 	dinfo = device_get_ivars(child);
3612 	cfg = &dinfo->cfg;
3613 	rl = &dinfo->resources;
3614 	switch (cfg->hdrtype & PCIM_HDRTYPE) {
3615 	case PCIM_HDRTYPE_BRIDGE:
3616 		sec_reg = PCIR_SECBUS_1;
3617 		sub_reg = PCIR_SUBBUS_1;
3618 		break;
3619 	case PCIM_HDRTYPE_CARDBUS:
3620 		sec_reg = PCIR_SECBUS_2;
3621 		sub_reg = PCIR_SUBBUS_2;
3622 		break;
3623 	default:
3624 		return (NULL);
3625 	}
3626 
3627 	if (*rid != 0)
3628 		return (NULL);
3629 
3630 	if (resource_list_find(rl, PCI_RES_BUS, *rid) == NULL)
3631 		resource_list_add(rl, PCI_RES_BUS, *rid, start, end, count);
3632 	if (!resource_list_reserved(rl, PCI_RES_BUS, *rid)) {
3633 		res = resource_list_reserve(rl, dev, child, PCI_RES_BUS, rid,
3634 		    start, end, count, flags & ~RF_ACTIVE);
3635 		if (res == NULL) {
3636 			resource_list_delete(rl, PCI_RES_BUS, *rid);
3637 			device_printf(child, "allocating %ju bus%s failed\n",
3638 			    count, count == 1 ? "" : "es");
3639 			return (NULL);
3640 		}
3641 		if (bootverbose)
3642 			device_printf(child,
3643 			    "Lazy allocation of %ju bus%s at %ju\n", count,
3644 			    count == 1 ? "" : "es", rman_get_start(res));
3645 		PCI_WRITE_CONFIG(dev, child, sec_reg, rman_get_start(res), 1);
3646 		PCI_WRITE_CONFIG(dev, child, sub_reg, rman_get_end(res), 1);
3647 	}
3648 	return (resource_list_alloc(rl, dev, child, PCI_RES_BUS, rid, start,
3649 	    end, count, flags));
3650 }
3651 #endif
3652 
3653 static int
3654 pci_ea_bei_to_rid(device_t dev, int bei)
3655 {
3656 #ifdef PCI_IOV
3657 	struct pci_devinfo *dinfo;
3658 	int iov_pos;
3659 	struct pcicfg_iov *iov;
3660 
3661 	dinfo = device_get_ivars(dev);
3662 	iov = dinfo->cfg.iov;
3663 	if (iov != NULL)
3664 		iov_pos = iov->iov_pos;
3665 	else
3666 		iov_pos = 0;
3667 #endif
3668 
3669 	/* Check if matches BAR */
3670 	if ((bei >= PCIM_EA_BEI_BAR_0) &&
3671 	    (bei <= PCIM_EA_BEI_BAR_5))
3672 		return (PCIR_BAR(bei));
3673 
3674 	/* Check ROM */
3675 	if (bei == PCIM_EA_BEI_ROM)
3676 		return (PCIR_BIOS);
3677 
3678 #ifdef PCI_IOV
3679 	/* Check if matches VF_BAR */
3680 	if ((iov != NULL) && (bei >= PCIM_EA_BEI_VF_BAR_0) &&
3681 	    (bei <= PCIM_EA_BEI_VF_BAR_5))
3682 		return (PCIR_SRIOV_BAR(bei - PCIM_EA_BEI_VF_BAR_0) +
3683 		    iov_pos);
3684 #endif
3685 
3686 	return (-1);
3687 }
3688 
3689 int
3690 pci_ea_is_enabled(device_t dev, int rid)
3691 {
3692 	struct pci_ea_entry *ea;
3693 	struct pci_devinfo *dinfo;
3694 
3695 	dinfo = device_get_ivars(dev);
3696 
3697 	STAILQ_FOREACH(ea, &dinfo->cfg.ea.ea_entries, eae_link) {
3698 		if (pci_ea_bei_to_rid(dev, ea->eae_bei) == rid)
3699 			return ((ea->eae_flags & PCIM_EA_ENABLE) > 0);
3700 	}
3701 
3702 	return (0);
3703 }
3704 
3705 void
3706 pci_add_resources_ea(device_t bus, device_t dev, int alloc_iov)
3707 {
3708 	struct pci_ea_entry *ea;
3709 	struct pci_devinfo *dinfo;
3710 	pci_addr_t start, end, count;
3711 	struct resource_list *rl;
3712 	int type, flags, rid;
3713 	struct resource *res;
3714 	uint32_t tmp;
3715 #ifdef PCI_IOV
3716 	struct pcicfg_iov *iov;
3717 #endif
3718 
3719 	dinfo = device_get_ivars(dev);
3720 	rl = &dinfo->resources;
3721 	flags = 0;
3722 
3723 #ifdef PCI_IOV
3724 	iov = dinfo->cfg.iov;
3725 #endif
3726 
3727 	if (dinfo->cfg.ea.ea_location == 0)
3728 		return;
3729 
3730 	STAILQ_FOREACH(ea, &dinfo->cfg.ea.ea_entries, eae_link) {
3731 
3732 		/*
3733 		 * TODO: Ignore EA-BAR if is not enabled.
3734 		 *   Currently the EA implementation supports
3735 		 *   only situation, where EA structure contains
3736 		 *   predefined entries. In case they are not enabled
3737 		 *   leave them unallocated and proceed with
3738 		 *   a legacy-BAR mechanism.
3739 		 */
3740 		if ((ea->eae_flags & PCIM_EA_ENABLE) == 0)
3741 			continue;
3742 
3743 		switch ((ea->eae_flags & PCIM_EA_PP) >> PCIM_EA_PP_OFFSET) {
3744 		case PCIM_EA_P_MEM_PREFETCH:
3745 		case PCIM_EA_P_VF_MEM_PREFETCH:
3746 			flags = RF_PREFETCHABLE;
3747 			/* FALLTHROUGH */
3748 		case PCIM_EA_P_VF_MEM:
3749 		case PCIM_EA_P_MEM:
3750 			type = SYS_RES_MEMORY;
3751 			break;
3752 		case PCIM_EA_P_IO:
3753 			type = SYS_RES_IOPORT;
3754 			break;
3755 		default:
3756 			continue;
3757 		}
3758 
3759 		if (alloc_iov != 0) {
3760 #ifdef PCI_IOV
3761 			/* Allocating IOV, confirm BEI matches */
3762 			if ((ea->eae_bei < PCIM_EA_BEI_VF_BAR_0) ||
3763 			    (ea->eae_bei > PCIM_EA_BEI_VF_BAR_5))
3764 				continue;
3765 #else
3766 			continue;
3767 #endif
3768 		} else {
3769 			/* Allocating BAR, confirm BEI matches */
3770 			if (((ea->eae_bei < PCIM_EA_BEI_BAR_0) ||
3771 			    (ea->eae_bei > PCIM_EA_BEI_BAR_5)) &&
3772 			    (ea->eae_bei != PCIM_EA_BEI_ROM))
3773 				continue;
3774 		}
3775 
3776 		rid = pci_ea_bei_to_rid(dev, ea->eae_bei);
3777 		if (rid < 0)
3778 			continue;
3779 
3780 		/* Skip resources already allocated by EA */
3781 		if ((resource_list_find(rl, SYS_RES_MEMORY, rid) != NULL) ||
3782 		    (resource_list_find(rl, SYS_RES_IOPORT, rid) != NULL))
3783 			continue;
3784 
3785 		start = ea->eae_base;
3786 		count = ea->eae_max_offset + 1;
3787 #ifdef PCI_IOV
3788 		if (iov != NULL)
3789 			count = count * iov->iov_num_vfs;
3790 #endif
3791 		end = start + count - 1;
3792 		if (count == 0)
3793 			continue;
3794 
3795 		resource_list_add(rl, type, rid, start, end, count);
3796 		res = resource_list_reserve(rl, bus, dev, type, &rid, start, end, count,
3797 		    flags);
3798 		if (res == NULL) {
3799 			resource_list_delete(rl, type, rid);
3800 
3801 			/*
3802 			 * Failed to allocate using EA, disable entry.
3803 			 * Another attempt to allocation will be performed
3804 			 * further, but this time using legacy BAR registers
3805 			 */
3806 			tmp = pci_read_config(dev, ea->eae_cfg_offset, 4);
3807 			tmp &= ~PCIM_EA_ENABLE;
3808 			pci_write_config(dev, ea->eae_cfg_offset, tmp, 4);
3809 
3810 			/*
3811 			 * Disabling entry might fail in case it is hardwired.
3812 			 * Read flags again to match current status.
3813 			 */
3814 			ea->eae_flags = pci_read_config(dev, ea->eae_cfg_offset, 4);
3815 
3816 			continue;
3817 		}
3818 
3819 		/* As per specification, fill BAR with zeros */
3820 		pci_write_config(dev, rid, 0, 4);
3821 	}
3822 }
3823 
3824 void
3825 pci_add_resources(device_t bus, device_t dev, int force, uint32_t prefetchmask)
3826 {
3827 	struct pci_devinfo *dinfo;
3828 	pcicfgregs *cfg;
3829 	struct resource_list *rl;
3830 	const struct pci_quirk *q;
3831 	uint32_t devid;
3832 	int i;
3833 
3834 	dinfo = device_get_ivars(dev);
3835 	cfg = &dinfo->cfg;
3836 	rl = &dinfo->resources;
3837 	devid = (cfg->device << 16) | cfg->vendor;
3838 
3839 	/* Allocate resources using Enhanced Allocation */
3840 	pci_add_resources_ea(bus, dev, 0);
3841 
3842 	/* ATA devices needs special map treatment */
3843 	if ((pci_get_class(dev) == PCIC_STORAGE) &&
3844 	    (pci_get_subclass(dev) == PCIS_STORAGE_IDE) &&
3845 	    ((pci_get_progif(dev) & PCIP_STORAGE_IDE_MASTERDEV) ||
3846 	     (!pci_read_config(dev, PCIR_BAR(0), 4) &&
3847 	      !pci_read_config(dev, PCIR_BAR(2), 4))) )
3848 		pci_ata_maps(bus, dev, rl, force, prefetchmask);
3849 	else
3850 		for (i = 0; i < cfg->nummaps;) {
3851 			/* Skip resources already managed by EA */
3852 			if ((resource_list_find(rl, SYS_RES_MEMORY, PCIR_BAR(i)) != NULL) ||
3853 			    (resource_list_find(rl, SYS_RES_IOPORT, PCIR_BAR(i)) != NULL) ||
3854 			    pci_ea_is_enabled(dev, PCIR_BAR(i))) {
3855 				i++;
3856 				continue;
3857 			}
3858 
3859 			/*
3860 			 * Skip quirked resources.
3861 			 */
3862 			for (q = &pci_quirks[0]; q->devid != 0; q++)
3863 				if (q->devid == devid &&
3864 				    q->type == PCI_QUIRK_UNMAP_REG &&
3865 				    q->arg1 == PCIR_BAR(i))
3866 					break;
3867 			if (q->devid != 0) {
3868 				i++;
3869 				continue;
3870 			}
3871 			i += pci_add_map(bus, dev, PCIR_BAR(i), rl, force,
3872 			    prefetchmask & (1 << i));
3873 		}
3874 
3875 	/*
3876 	 * Add additional, quirked resources.
3877 	 */
3878 	for (q = &pci_quirks[0]; q->devid != 0; q++)
3879 		if (q->devid == devid && q->type == PCI_QUIRK_MAP_REG)
3880 			pci_add_map(bus, dev, q->arg1, rl, force, 0);
3881 
3882 	if (cfg->intpin > 0 && PCI_INTERRUPT_VALID(cfg->intline)) {
3883 #ifdef __PCI_REROUTE_INTERRUPT
3884 		/*
3885 		 * Try to re-route interrupts. Sometimes the BIOS or
3886 		 * firmware may leave bogus values in these registers.
3887 		 * If the re-route fails, then just stick with what we
3888 		 * have.
3889 		 */
3890 		pci_assign_interrupt(bus, dev, 1);
3891 #else
3892 		pci_assign_interrupt(bus, dev, 0);
3893 #endif
3894 	}
3895 
3896 	if (pci_usb_takeover && pci_get_class(dev) == PCIC_SERIALBUS &&
3897 	    pci_get_subclass(dev) == PCIS_SERIALBUS_USB) {
3898 		if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_XHCI)
3899 			xhci_early_takeover(dev);
3900 		else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_EHCI)
3901 			ehci_early_takeover(dev);
3902 		else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_OHCI)
3903 			ohci_early_takeover(dev);
3904 		else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_UHCI)
3905 			uhci_early_takeover(dev);
3906 	}
3907 
3908 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
3909 	/*
3910 	 * Reserve resources for secondary bus ranges behind bridge
3911 	 * devices.
3912 	 */
3913 	pci_reserve_secbus(bus, dev, cfg, rl);
3914 #endif
3915 }
3916 
3917 static struct pci_devinfo *
3918 pci_identify_function(device_t pcib, device_t dev, int domain, int busno,
3919     int slot, int func)
3920 {
3921 	struct pci_devinfo *dinfo;
3922 
3923 	dinfo = pci_read_device(pcib, dev, domain, busno, slot, func);
3924 	if (dinfo != NULL)
3925 		pci_add_child(dev, dinfo);
3926 
3927 	return (dinfo);
3928 }
3929 
3930 void
3931 pci_add_children(device_t dev, int domain, int busno)
3932 {
3933 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
3934 	device_t pcib = device_get_parent(dev);
3935 	struct pci_devinfo *dinfo;
3936 	int maxslots;
3937 	int s, f, pcifunchigh;
3938 	uint8_t hdrtype;
3939 	int first_func;
3940 
3941 	/*
3942 	 * Try to detect a device at slot 0, function 0.  If it exists, try to
3943 	 * enable ARI.  We must enable ARI before detecting the rest of the
3944 	 * functions on this bus as ARI changes the set of slots and functions
3945 	 * that are legal on this bus.
3946 	 */
3947 	dinfo = pci_identify_function(pcib, dev, domain, busno, 0, 0);
3948 	if (dinfo != NULL && pci_enable_ari)
3949 		PCIB_TRY_ENABLE_ARI(pcib, dinfo->cfg.dev);
3950 
3951 	/*
3952 	 * Start looking for new devices on slot 0 at function 1 because we
3953 	 * just identified the device at slot 0, function 0.
3954 	 */
3955 	first_func = 1;
3956 
3957 	maxslots = PCIB_MAXSLOTS(pcib);
3958 	for (s = 0; s <= maxslots; s++, first_func = 0) {
3959 		pcifunchigh = 0;
3960 		f = 0;
3961 		DELAY(1);
3962 		hdrtype = REG(PCIR_HDRTYPE, 1);
3963 		if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
3964 			continue;
3965 		if (hdrtype & PCIM_MFDEV)
3966 			pcifunchigh = PCIB_MAXFUNCS(pcib);
3967 		for (f = first_func; f <= pcifunchigh; f++)
3968 			pci_identify_function(pcib, dev, domain, busno, s, f);
3969 	}
3970 #undef REG
3971 }
3972 
3973 int
3974 pci_rescan_method(device_t dev)
3975 {
3976 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
3977 	device_t pcib = device_get_parent(dev);
3978 	struct pci_softc *sc;
3979 	device_t child, *devlist, *unchanged;
3980 	int devcount, error, i, j, maxslots, oldcount;
3981 	int busno, domain, s, f, pcifunchigh;
3982 	uint8_t hdrtype;
3983 
3984 	/* No need to check for ARI on a rescan. */
3985 	error = device_get_children(dev, &devlist, &devcount);
3986 	if (error)
3987 		return (error);
3988 	if (devcount != 0) {
3989 		unchanged = malloc(devcount * sizeof(device_t), M_TEMP,
3990 		    M_NOWAIT | M_ZERO);
3991 		if (unchanged == NULL) {
3992 			free(devlist, M_TEMP);
3993 			return (ENOMEM);
3994 		}
3995 	} else
3996 		unchanged = NULL;
3997 
3998 	sc = device_get_softc(dev);
3999 	domain = pcib_get_domain(dev);
4000 	busno = pcib_get_bus(dev);
4001 	maxslots = PCIB_MAXSLOTS(pcib);
4002 	for (s = 0; s <= maxslots; s++) {
4003 		/* If function 0 is not present, skip to the next slot. */
4004 		f = 0;
4005 		if (REG(PCIR_VENDOR, 2) == 0xffff)
4006 			continue;
4007 		pcifunchigh = 0;
4008 		hdrtype = REG(PCIR_HDRTYPE, 1);
4009 		if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
4010 			continue;
4011 		if (hdrtype & PCIM_MFDEV)
4012 			pcifunchigh = PCIB_MAXFUNCS(pcib);
4013 		for (f = 0; f <= pcifunchigh; f++) {
4014 			if (REG(PCIR_VENDOR, 2) == 0xffff)
4015 				continue;
4016 
4017 			/*
4018 			 * Found a valid function.  Check if a
4019 			 * device_t for this device already exists.
4020 			 */
4021 			for (i = 0; i < devcount; i++) {
4022 				child = devlist[i];
4023 				if (child == NULL)
4024 					continue;
4025 				if (pci_get_slot(child) == s &&
4026 				    pci_get_function(child) == f) {
4027 					unchanged[i] = child;
4028 					goto next_func;
4029 				}
4030 			}
4031 
4032 			pci_identify_function(pcib, dev, domain, busno, s, f);
4033 		next_func:;
4034 		}
4035 	}
4036 
4037 	/* Remove devices that are no longer present. */
4038 	for (i = 0; i < devcount; i++) {
4039 		if (unchanged[i] != NULL)
4040 			continue;
4041 		device_delete_child(dev, devlist[i]);
4042 	}
4043 
4044 	free(devlist, M_TEMP);
4045 	oldcount = devcount;
4046 
4047 	/* Try to attach the devices just added. */
4048 	error = device_get_children(dev, &devlist, &devcount);
4049 	if (error) {
4050 		free(unchanged, M_TEMP);
4051 		return (error);
4052 	}
4053 
4054 	for (i = 0; i < devcount; i++) {
4055 		for (j = 0; j < oldcount; j++) {
4056 			if (devlist[i] == unchanged[j])
4057 				goto next_device;
4058 		}
4059 
4060 		device_probe_and_attach(devlist[i]);
4061 	next_device:;
4062 	}
4063 
4064 	free(unchanged, M_TEMP);
4065 	free(devlist, M_TEMP);
4066 	return (0);
4067 #undef REG
4068 }
4069 
4070 #ifdef PCI_IOV
4071 device_t
4072 pci_add_iov_child(device_t bus, device_t pf, uint16_t rid, uint16_t vid,
4073     uint16_t did)
4074 {
4075 	struct pci_devinfo *pf_dinfo, *vf_dinfo;
4076 	device_t pcib;
4077 	int busno, slot, func;
4078 
4079 	pf_dinfo = device_get_ivars(pf);
4080 
4081 	pcib = device_get_parent(bus);
4082 
4083 	PCIB_DECODE_RID(pcib, rid, &busno, &slot, &func);
4084 
4085 	vf_dinfo = pci_fill_devinfo(pcib, bus, pci_get_domain(pcib), busno,
4086 	    slot, func, vid, did);
4087 
4088 	vf_dinfo->cfg.flags |= PCICFG_VF;
4089 	pci_add_child(bus, vf_dinfo);
4090 
4091 	return (vf_dinfo->cfg.dev);
4092 }
4093 
4094 device_t
4095 pci_create_iov_child_method(device_t bus, device_t pf, uint16_t rid,
4096     uint16_t vid, uint16_t did)
4097 {
4098 
4099 	return (pci_add_iov_child(bus, pf, rid, vid, did));
4100 }
4101 #endif
4102 
4103 void
4104 pci_add_child(device_t bus, struct pci_devinfo *dinfo)
4105 {
4106 	dinfo->cfg.dev = device_add_child(bus, NULL, -1);
4107 	device_set_ivars(dinfo->cfg.dev, dinfo);
4108 	resource_list_init(&dinfo->resources);
4109 	pci_cfg_save(dinfo->cfg.dev, dinfo, 0);
4110 	pci_cfg_restore(dinfo->cfg.dev, dinfo);
4111 	pci_print_verbose(dinfo);
4112 	pci_add_resources(bus, dinfo->cfg.dev, 0, 0);
4113 	pci_child_added(dinfo->cfg.dev);
4114 	EVENTHANDLER_INVOKE(pci_add_device, dinfo->cfg.dev);
4115 }
4116 
4117 void
4118 pci_child_added_method(device_t dev, device_t child)
4119 {
4120 
4121 }
4122 
4123 static int
4124 pci_probe(device_t dev)
4125 {
4126 
4127 	device_set_desc(dev, "PCI bus");
4128 
4129 	/* Allow other subclasses to override this driver. */
4130 	return (BUS_PROBE_GENERIC);
4131 }
4132 
4133 int
4134 pci_attach_common(device_t dev)
4135 {
4136 	struct pci_softc *sc;
4137 	int busno, domain;
4138 #ifdef PCI_DMA_BOUNDARY
4139 	int error, tag_valid;
4140 #endif
4141 #ifdef PCI_RES_BUS
4142 	int rid;
4143 #endif
4144 
4145 	sc = device_get_softc(dev);
4146 	domain = pcib_get_domain(dev);
4147 	busno = pcib_get_bus(dev);
4148 #ifdef PCI_RES_BUS
4149 	rid = 0;
4150 	sc->sc_bus = bus_alloc_resource(dev, PCI_RES_BUS, &rid, busno, busno,
4151 	    1, 0);
4152 	if (sc->sc_bus == NULL) {
4153 		device_printf(dev, "failed to allocate bus number\n");
4154 		return (ENXIO);
4155 	}
4156 #endif
4157 	if (bootverbose)
4158 		device_printf(dev, "domain=%d, physical bus=%d\n",
4159 		    domain, busno);
4160 #ifdef PCI_DMA_BOUNDARY
4161 	tag_valid = 0;
4162 	if (device_get_devclass(device_get_parent(device_get_parent(dev))) !=
4163 	    devclass_find("pci")) {
4164 		error = bus_dma_tag_create(bus_get_dma_tag(dev), 1,
4165 		    PCI_DMA_BOUNDARY, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
4166 		    NULL, NULL, BUS_SPACE_MAXSIZE, BUS_SPACE_UNRESTRICTED,
4167 		    BUS_SPACE_MAXSIZE, 0, NULL, NULL, &sc->sc_dma_tag);
4168 		if (error)
4169 			device_printf(dev, "Failed to create DMA tag: %d\n",
4170 			    error);
4171 		else
4172 			tag_valid = 1;
4173 	}
4174 	if (!tag_valid)
4175 #endif
4176 		sc->sc_dma_tag = bus_get_dma_tag(dev);
4177 	return (0);
4178 }
4179 
4180 static int
4181 pci_attach(device_t dev)
4182 {
4183 	int busno, domain, error;
4184 
4185 	error = pci_attach_common(dev);
4186 	if (error)
4187 		return (error);
4188 
4189 	/*
4190 	 * Since there can be multiple independently numbered PCI
4191 	 * buses on systems with multiple PCI domains, we can't use
4192 	 * the unit number to decide which bus we are probing. We ask
4193 	 * the parent pcib what our domain and bus numbers are.
4194 	 */
4195 	domain = pcib_get_domain(dev);
4196 	busno = pcib_get_bus(dev);
4197 	pci_add_children(dev, domain, busno);
4198 	return (bus_generic_attach(dev));
4199 }
4200 
4201 static int
4202 pci_detach(device_t dev)
4203 {
4204 #ifdef PCI_RES_BUS
4205 	struct pci_softc *sc;
4206 #endif
4207 	int error;
4208 
4209 	error = bus_generic_detach(dev);
4210 	if (error)
4211 		return (error);
4212 #ifdef PCI_RES_BUS
4213 	sc = device_get_softc(dev);
4214 	error = bus_release_resource(dev, PCI_RES_BUS, 0, sc->sc_bus);
4215 	if (error)
4216 		return (error);
4217 #endif
4218 	return (device_delete_children(dev));
4219 }
4220 
4221 static void
4222 pci_set_power_child(device_t dev, device_t child, int state)
4223 {
4224 	device_t pcib;
4225 	int dstate;
4226 
4227 	/*
4228 	 * Set the device to the given state.  If the firmware suggests
4229 	 * a different power state, use it instead.  If power management
4230 	 * is not present, the firmware is responsible for managing
4231 	 * device power.  Skip children who aren't attached since they
4232 	 * are handled separately.
4233 	 */
4234 	pcib = device_get_parent(dev);
4235 	dstate = state;
4236 	if (device_is_attached(child) &&
4237 	    PCIB_POWER_FOR_SLEEP(pcib, child, &dstate) == 0)
4238 		pci_set_powerstate(child, dstate);
4239 }
4240 
4241 int
4242 pci_suspend_child(device_t dev, device_t child)
4243 {
4244 	struct pci_devinfo *dinfo;
4245 	int error;
4246 
4247 	dinfo = device_get_ivars(child);
4248 
4249 	/*
4250 	 * Save the PCI configuration space for the child and set the
4251 	 * device in the appropriate power state for this sleep state.
4252 	 */
4253 	pci_cfg_save(child, dinfo, 0);
4254 
4255 	/* Suspend devices before potentially powering them down. */
4256 	error = bus_generic_suspend_child(dev, child);
4257 
4258 	if (error)
4259 		return (error);
4260 
4261 	if (pci_do_power_suspend)
4262 		pci_set_power_child(dev, child, PCI_POWERSTATE_D3);
4263 
4264 	return (0);
4265 }
4266 
4267 int
4268 pci_resume_child(device_t dev, device_t child)
4269 {
4270 	struct pci_devinfo *dinfo;
4271 
4272 	if (pci_do_power_resume)
4273 		pci_set_power_child(dev, child, PCI_POWERSTATE_D0);
4274 
4275 	dinfo = device_get_ivars(child);
4276 	pci_cfg_restore(child, dinfo);
4277 	if (!device_is_attached(child))
4278 		pci_cfg_save(child, dinfo, 1);
4279 
4280 	bus_generic_resume_child(dev, child);
4281 
4282 	return (0);
4283 }
4284 
4285 int
4286 pci_resume(device_t dev)
4287 {
4288 	device_t child, *devlist;
4289 	int error, i, numdevs;
4290 
4291 	if ((error = device_get_children(dev, &devlist, &numdevs)) != 0)
4292 		return (error);
4293 
4294 	/*
4295 	 * Resume critical devices first, then everything else later.
4296 	 */
4297 	for (i = 0; i < numdevs; i++) {
4298 		child = devlist[i];
4299 		switch (pci_get_class(child)) {
4300 		case PCIC_DISPLAY:
4301 		case PCIC_MEMORY:
4302 		case PCIC_BRIDGE:
4303 		case PCIC_BASEPERIPH:
4304 			BUS_RESUME_CHILD(dev, child);
4305 			break;
4306 		}
4307 	}
4308 	for (i = 0; i < numdevs; i++) {
4309 		child = devlist[i];
4310 		switch (pci_get_class(child)) {
4311 		case PCIC_DISPLAY:
4312 		case PCIC_MEMORY:
4313 		case PCIC_BRIDGE:
4314 		case PCIC_BASEPERIPH:
4315 			break;
4316 		default:
4317 			BUS_RESUME_CHILD(dev, child);
4318 		}
4319 	}
4320 	free(devlist, M_TEMP);
4321 	return (0);
4322 }
4323 
4324 static void
4325 pci_load_vendor_data(void)
4326 {
4327 	caddr_t data;
4328 	void *ptr;
4329 	size_t sz;
4330 
4331 	data = preload_search_by_type("pci_vendor_data");
4332 	if (data != NULL) {
4333 		ptr = preload_fetch_addr(data);
4334 		sz = preload_fetch_size(data);
4335 		if (ptr != NULL && sz != 0) {
4336 			pci_vendordata = ptr;
4337 			pci_vendordata_size = sz;
4338 			/* terminate the database */
4339 			pci_vendordata[pci_vendordata_size] = '\n';
4340 		}
4341 	}
4342 }
4343 
4344 void
4345 pci_driver_added(device_t dev, driver_t *driver)
4346 {
4347 	int numdevs;
4348 	device_t *devlist;
4349 	device_t child;
4350 	struct pci_devinfo *dinfo;
4351 	int i;
4352 
4353 	if (bootverbose)
4354 		device_printf(dev, "driver added\n");
4355 	DEVICE_IDENTIFY(driver, dev);
4356 	if (device_get_children(dev, &devlist, &numdevs) != 0)
4357 		return;
4358 	for (i = 0; i < numdevs; i++) {
4359 		child = devlist[i];
4360 		if (device_get_state(child) != DS_NOTPRESENT)
4361 			continue;
4362 		dinfo = device_get_ivars(child);
4363 		pci_print_verbose(dinfo);
4364 		if (bootverbose)
4365 			pci_printf(&dinfo->cfg, "reprobing on driver added\n");
4366 		pci_cfg_restore(child, dinfo);
4367 		if (device_probe_and_attach(child) != 0)
4368 			pci_child_detached(dev, child);
4369 	}
4370 	free(devlist, M_TEMP);
4371 }
4372 
4373 int
4374 pci_setup_intr(device_t dev, device_t child, struct resource *irq, int flags,
4375     driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep)
4376 {
4377 	struct pci_devinfo *dinfo;
4378 	struct msix_table_entry *mte;
4379 	struct msix_vector *mv;
4380 	uint64_t addr;
4381 	uint32_t data;
4382 	void *cookie;
4383 	int error, rid;
4384 
4385 	error = bus_generic_setup_intr(dev, child, irq, flags, filter, intr,
4386 	    arg, &cookie);
4387 	if (error)
4388 		return (error);
4389 
4390 	/* If this is not a direct child, just bail out. */
4391 	if (device_get_parent(child) != dev) {
4392 		*cookiep = cookie;
4393 		return(0);
4394 	}
4395 
4396 	rid = rman_get_rid(irq);
4397 	if (rid == 0) {
4398 		/* Make sure that INTx is enabled */
4399 		pci_clear_command_bit(dev, child, PCIM_CMD_INTxDIS);
4400 	} else {
4401 		/*
4402 		 * Check to see if the interrupt is MSI or MSI-X.
4403 		 * Ask our parent to map the MSI and give
4404 		 * us the address and data register values.
4405 		 * If we fail for some reason, teardown the
4406 		 * interrupt handler.
4407 		 */
4408 		dinfo = device_get_ivars(child);
4409 		if (dinfo->cfg.msi.msi_alloc > 0) {
4410 			if (dinfo->cfg.msi.msi_addr == 0) {
4411 				KASSERT(dinfo->cfg.msi.msi_handlers == 0,
4412 			    ("MSI has handlers, but vectors not mapped"));
4413 				error = PCIB_MAP_MSI(device_get_parent(dev),
4414 				    child, rman_get_start(irq), &addr, &data);
4415 				if (error)
4416 					goto bad;
4417 				dinfo->cfg.msi.msi_addr = addr;
4418 				dinfo->cfg.msi.msi_data = data;
4419 			}
4420 			if (dinfo->cfg.msi.msi_handlers == 0)
4421 				pci_enable_msi(child, dinfo->cfg.msi.msi_addr,
4422 				    dinfo->cfg.msi.msi_data);
4423 			dinfo->cfg.msi.msi_handlers++;
4424 		} else {
4425 			KASSERT(dinfo->cfg.msix.msix_alloc > 0,
4426 			    ("No MSI or MSI-X interrupts allocated"));
4427 			KASSERT(rid <= dinfo->cfg.msix.msix_table_len,
4428 			    ("MSI-X index too high"));
4429 			mte = &dinfo->cfg.msix.msix_table[rid - 1];
4430 			KASSERT(mte->mte_vector != 0, ("no message vector"));
4431 			mv = &dinfo->cfg.msix.msix_vectors[mte->mte_vector - 1];
4432 			KASSERT(mv->mv_irq == rman_get_start(irq),
4433 			    ("IRQ mismatch"));
4434 			if (mv->mv_address == 0) {
4435 				KASSERT(mte->mte_handlers == 0,
4436 		    ("MSI-X table entry has handlers, but vector not mapped"));
4437 				error = PCIB_MAP_MSI(device_get_parent(dev),
4438 				    child, rman_get_start(irq), &addr, &data);
4439 				if (error)
4440 					goto bad;
4441 				mv->mv_address = addr;
4442 				mv->mv_data = data;
4443 			}
4444 
4445 			/*
4446 			 * The MSIX table entry must be made valid by
4447 			 * incrementing the mte_handlers before
4448 			 * calling pci_enable_msix() and
4449 			 * pci_resume_msix(). Else the MSIX rewrite
4450 			 * table quirk will not work as expected.
4451 			 */
4452 			mte->mte_handlers++;
4453 			if (mte->mte_handlers == 1) {
4454 				pci_enable_msix(child, rid - 1, mv->mv_address,
4455 				    mv->mv_data);
4456 				pci_unmask_msix(child, rid - 1);
4457 			}
4458 		}
4459 
4460 		/*
4461 		 * Make sure that INTx is disabled if we are using MSI/MSI-X,
4462 		 * unless the device is affected by PCI_QUIRK_MSI_INTX_BUG,
4463 		 * in which case we "enable" INTx so MSI/MSI-X actually works.
4464 		 */
4465 		if (!pci_has_quirk(pci_get_devid(child),
4466 		    PCI_QUIRK_MSI_INTX_BUG))
4467 			pci_set_command_bit(dev, child, PCIM_CMD_INTxDIS);
4468 		else
4469 			pci_clear_command_bit(dev, child, PCIM_CMD_INTxDIS);
4470 	bad:
4471 		if (error) {
4472 			(void)bus_generic_teardown_intr(dev, child, irq,
4473 			    cookie);
4474 			return (error);
4475 		}
4476 	}
4477 	*cookiep = cookie;
4478 	return (0);
4479 }
4480 
4481 int
4482 pci_teardown_intr(device_t dev, device_t child, struct resource *irq,
4483     void *cookie)
4484 {
4485 	struct msix_table_entry *mte;
4486 	struct resource_list_entry *rle;
4487 	struct pci_devinfo *dinfo;
4488 	int error, rid;
4489 
4490 	if (irq == NULL || !(rman_get_flags(irq) & RF_ACTIVE))
4491 		return (EINVAL);
4492 
4493 	/* If this isn't a direct child, just bail out */
4494 	if (device_get_parent(child) != dev)
4495 		return(bus_generic_teardown_intr(dev, child, irq, cookie));
4496 
4497 	rid = rman_get_rid(irq);
4498 	if (rid == 0) {
4499 		/* Mask INTx */
4500 		pci_set_command_bit(dev, child, PCIM_CMD_INTxDIS);
4501 	} else {
4502 		/*
4503 		 * Check to see if the interrupt is MSI or MSI-X.  If so,
4504 		 * decrement the appropriate handlers count and mask the
4505 		 * MSI-X message, or disable MSI messages if the count
4506 		 * drops to 0.
4507 		 */
4508 		dinfo = device_get_ivars(child);
4509 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, rid);
4510 		if (rle->res != irq)
4511 			return (EINVAL);
4512 		if (dinfo->cfg.msi.msi_alloc > 0) {
4513 			KASSERT(rid <= dinfo->cfg.msi.msi_alloc,
4514 			    ("MSI-X index too high"));
4515 			if (dinfo->cfg.msi.msi_handlers == 0)
4516 				return (EINVAL);
4517 			dinfo->cfg.msi.msi_handlers--;
4518 			if (dinfo->cfg.msi.msi_handlers == 0)
4519 				pci_disable_msi(child);
4520 		} else {
4521 			KASSERT(dinfo->cfg.msix.msix_alloc > 0,
4522 			    ("No MSI or MSI-X interrupts allocated"));
4523 			KASSERT(rid <= dinfo->cfg.msix.msix_table_len,
4524 			    ("MSI-X index too high"));
4525 			mte = &dinfo->cfg.msix.msix_table[rid - 1];
4526 			if (mte->mte_handlers == 0)
4527 				return (EINVAL);
4528 			mte->mte_handlers--;
4529 			if (mte->mte_handlers == 0)
4530 				pci_mask_msix(child, rid - 1);
4531 		}
4532 	}
4533 	error = bus_generic_teardown_intr(dev, child, irq, cookie);
4534 	if (rid > 0)
4535 		KASSERT(error == 0,
4536 		    ("%s: generic teardown failed for MSI/MSI-X", __func__));
4537 	return (error);
4538 }
4539 
4540 int
4541 pci_print_child(device_t dev, device_t child)
4542 {
4543 	struct pci_devinfo *dinfo;
4544 	struct resource_list *rl;
4545 	int retval = 0;
4546 
4547 	dinfo = device_get_ivars(child);
4548 	rl = &dinfo->resources;
4549 
4550 	retval += bus_print_child_header(dev, child);
4551 
4552 	retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#jx");
4553 	retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY, "%#jx");
4554 	retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%jd");
4555 	if (device_get_flags(dev))
4556 		retval += printf(" flags %#x", device_get_flags(dev));
4557 
4558 	retval += printf(" at device %d.%d", pci_get_slot(child),
4559 	    pci_get_function(child));
4560 
4561 	retval += bus_print_child_domain(dev, child);
4562 	retval += bus_print_child_footer(dev, child);
4563 
4564 	return (retval);
4565 }
4566 
4567 static const struct
4568 {
4569 	int		class;
4570 	int		subclass;
4571 	int		report; /* 0 = bootverbose, 1 = always */
4572 	const char	*desc;
4573 } pci_nomatch_tab[] = {
4574 	{PCIC_OLD,		-1,			1, "old"},
4575 	{PCIC_OLD,		PCIS_OLD_NONVGA,	1, "non-VGA display device"},
4576 	{PCIC_OLD,		PCIS_OLD_VGA,		1, "VGA-compatible display device"},
4577 	{PCIC_STORAGE,		-1,			1, "mass storage"},
4578 	{PCIC_STORAGE,		PCIS_STORAGE_SCSI,	1, "SCSI"},
4579 	{PCIC_STORAGE,		PCIS_STORAGE_IDE,	1, "ATA"},
4580 	{PCIC_STORAGE,		PCIS_STORAGE_FLOPPY,	1, "floppy disk"},
4581 	{PCIC_STORAGE,		PCIS_STORAGE_IPI,	1, "IPI"},
4582 	{PCIC_STORAGE,		PCIS_STORAGE_RAID,	1, "RAID"},
4583 	{PCIC_STORAGE,		PCIS_STORAGE_ATA_ADMA,	1, "ATA (ADMA)"},
4584 	{PCIC_STORAGE,		PCIS_STORAGE_SATA,	1, "SATA"},
4585 	{PCIC_STORAGE,		PCIS_STORAGE_SAS,	1, "SAS"},
4586 	{PCIC_STORAGE,		PCIS_STORAGE_NVM,	1, "NVM"},
4587 	{PCIC_NETWORK,		-1,			1, "network"},
4588 	{PCIC_NETWORK,		PCIS_NETWORK_ETHERNET,	1, "ethernet"},
4589 	{PCIC_NETWORK,		PCIS_NETWORK_TOKENRING,	1, "token ring"},
4590 	{PCIC_NETWORK,		PCIS_NETWORK_FDDI,	1, "fddi"},
4591 	{PCIC_NETWORK,		PCIS_NETWORK_ATM,	1, "ATM"},
4592 	{PCIC_NETWORK,		PCIS_NETWORK_ISDN,	1, "ISDN"},
4593 	{PCIC_DISPLAY,		-1,			1, "display"},
4594 	{PCIC_DISPLAY,		PCIS_DISPLAY_VGA,	1, "VGA"},
4595 	{PCIC_DISPLAY,		PCIS_DISPLAY_XGA,	1, "XGA"},
4596 	{PCIC_DISPLAY,		PCIS_DISPLAY_3D,	1, "3D"},
4597 	{PCIC_MULTIMEDIA,	-1,			1, "multimedia"},
4598 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_VIDEO,	1, "video"},
4599 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_AUDIO,	1, "audio"},
4600 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_TELE,	1, "telephony"},
4601 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_HDA,	1, "HDA"},
4602 	{PCIC_MEMORY,		-1,			1, "memory"},
4603 	{PCIC_MEMORY,		PCIS_MEMORY_RAM,	1, "RAM"},
4604 	{PCIC_MEMORY,		PCIS_MEMORY_FLASH,	1, "flash"},
4605 	{PCIC_BRIDGE,		-1,			1, "bridge"},
4606 	{PCIC_BRIDGE,		PCIS_BRIDGE_HOST,	1, "HOST-PCI"},
4607 	{PCIC_BRIDGE,		PCIS_BRIDGE_ISA,	1, "PCI-ISA"},
4608 	{PCIC_BRIDGE,		PCIS_BRIDGE_EISA,	1, "PCI-EISA"},
4609 	{PCIC_BRIDGE,		PCIS_BRIDGE_MCA,	1, "PCI-MCA"},
4610 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI,	1, "PCI-PCI"},
4611 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCMCIA,	1, "PCI-PCMCIA"},
4612 	{PCIC_BRIDGE,		PCIS_BRIDGE_NUBUS,	1, "PCI-NuBus"},
4613 	{PCIC_BRIDGE,		PCIS_BRIDGE_CARDBUS,	1, "PCI-CardBus"},
4614 	{PCIC_BRIDGE,		PCIS_BRIDGE_RACEWAY,	1, "PCI-RACEway"},
4615 	{PCIC_SIMPLECOMM,	-1,			1, "simple comms"},
4616 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_UART,	1, "UART"},	/* could detect 16550 */
4617 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_PAR,	1, "parallel port"},
4618 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MULSER,	1, "multiport serial"},
4619 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MODEM,	1, "generic modem"},
4620 	{PCIC_BASEPERIPH,	-1,			0, "base peripheral"},
4621 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PIC,	1, "interrupt controller"},
4622 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_DMA,	1, "DMA controller"},
4623 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_TIMER,	1, "timer"},
4624 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RTC,	1, "realtime clock"},
4625 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PCIHOT,	1, "PCI hot-plug controller"},
4626 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_SDHC,	1, "SD host controller"},
4627 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_IOMMU,	1, "IOMMU"},
4628 	{PCIC_INPUTDEV,		-1,			1, "input device"},
4629 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_KEYBOARD,	1, "keyboard"},
4630 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_DIGITIZER,1, "digitizer"},
4631 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_MOUSE,	1, "mouse"},
4632 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_SCANNER,	1, "scanner"},
4633 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_GAMEPORT,	1, "gameport"},
4634 	{PCIC_DOCKING,		-1,			1, "docking station"},
4635 	{PCIC_PROCESSOR,	-1,			1, "processor"},
4636 	{PCIC_SERIALBUS,	-1,			1, "serial bus"},
4637 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FW,	1, "FireWire"},
4638 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_ACCESS,	1, "AccessBus"},
4639 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SSA,	1, "SSA"},
4640 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_USB,	1, "USB"},
4641 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FC,	1, "Fibre Channel"},
4642 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SMBUS,	0, "SMBus"},
4643 	{PCIC_WIRELESS,		-1,			1, "wireless controller"},
4644 	{PCIC_WIRELESS,		PCIS_WIRELESS_IRDA,	1, "iRDA"},
4645 	{PCIC_WIRELESS,		PCIS_WIRELESS_IR,	1, "IR"},
4646 	{PCIC_WIRELESS,		PCIS_WIRELESS_RF,	1, "RF"},
4647 	{PCIC_INTELLIIO,	-1,			1, "intelligent I/O controller"},
4648 	{PCIC_INTELLIIO,	PCIS_INTELLIIO_I2O,	1, "I2O"},
4649 	{PCIC_SATCOM,		-1,			1, "satellite communication"},
4650 	{PCIC_SATCOM,		PCIS_SATCOM_TV,		1, "sat TV"},
4651 	{PCIC_SATCOM,		PCIS_SATCOM_AUDIO,	1, "sat audio"},
4652 	{PCIC_SATCOM,		PCIS_SATCOM_VOICE,	1, "sat voice"},
4653 	{PCIC_SATCOM,		PCIS_SATCOM_DATA,	1, "sat data"},
4654 	{PCIC_CRYPTO,		-1,			1, "encrypt/decrypt"},
4655 	{PCIC_CRYPTO,		PCIS_CRYPTO_NETCOMP,	1, "network/computer crypto"},
4656 	{PCIC_CRYPTO,		PCIS_CRYPTO_ENTERTAIN,	1, "entertainment crypto"},
4657 	{PCIC_DASP,		-1,			0, "dasp"},
4658 	{PCIC_DASP,		PCIS_DASP_DPIO,		1, "DPIO module"},
4659 	{PCIC_DASP,		PCIS_DASP_PERFCNTRS,	1, "performance counters"},
4660 	{PCIC_DASP,		PCIS_DASP_COMM_SYNC,	1, "communication synchronizer"},
4661 	{PCIC_DASP,		PCIS_DASP_MGMT_CARD,	1, "signal processing management"},
4662 	{0, 0, 0,		NULL}
4663 };
4664 
4665 void
4666 pci_probe_nomatch(device_t dev, device_t child)
4667 {
4668 	int i, report;
4669 	const char *cp, *scp;
4670 	char *device;
4671 
4672 	/*
4673 	 * Look for a listing for this device in a loaded device database.
4674 	 */
4675 	report = 1;
4676 	if ((device = pci_describe_device(child)) != NULL) {
4677 		device_printf(dev, "<%s>", device);
4678 		free(device, M_DEVBUF);
4679 	} else {
4680 		/*
4681 		 * Scan the class/subclass descriptions for a general
4682 		 * description.
4683 		 */
4684 		cp = "unknown";
4685 		scp = NULL;
4686 		for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
4687 			if (pci_nomatch_tab[i].class == pci_get_class(child)) {
4688 				if (pci_nomatch_tab[i].subclass == -1) {
4689 					cp = pci_nomatch_tab[i].desc;
4690 					report = pci_nomatch_tab[i].report;
4691 				} else if (pci_nomatch_tab[i].subclass ==
4692 				    pci_get_subclass(child)) {
4693 					scp = pci_nomatch_tab[i].desc;
4694 					report = pci_nomatch_tab[i].report;
4695 				}
4696 			}
4697 		}
4698 		if (report || bootverbose) {
4699 			device_printf(dev, "<%s%s%s>",
4700 			    cp ? cp : "",
4701 			    ((cp != NULL) && (scp != NULL)) ? ", " : "",
4702 			    scp ? scp : "");
4703 		}
4704 	}
4705 	if (report || bootverbose) {
4706 		printf(" at device %d.%d (no driver attached)\n",
4707 		    pci_get_slot(child), pci_get_function(child));
4708 	}
4709 	pci_cfg_save(child, device_get_ivars(child), 1);
4710 }
4711 
4712 void
4713 pci_child_detached(device_t dev, device_t child)
4714 {
4715 	struct pci_devinfo *dinfo;
4716 	struct resource_list *rl;
4717 
4718 	dinfo = device_get_ivars(child);
4719 	rl = &dinfo->resources;
4720 
4721 	/*
4722 	 * Have to deallocate IRQs before releasing any MSI messages and
4723 	 * have to release MSI messages before deallocating any memory
4724 	 * BARs.
4725 	 */
4726 	if (resource_list_release_active(rl, dev, child, SYS_RES_IRQ) != 0)
4727 		pci_printf(&dinfo->cfg, "Device leaked IRQ resources\n");
4728 	if (dinfo->cfg.msi.msi_alloc != 0 || dinfo->cfg.msix.msix_alloc != 0) {
4729 		pci_printf(&dinfo->cfg, "Device leaked MSI vectors\n");
4730 		(void)pci_release_msi(child);
4731 	}
4732 	if (resource_list_release_active(rl, dev, child, SYS_RES_MEMORY) != 0)
4733 		pci_printf(&dinfo->cfg, "Device leaked memory resources\n");
4734 	if (resource_list_release_active(rl, dev, child, SYS_RES_IOPORT) != 0)
4735 		pci_printf(&dinfo->cfg, "Device leaked I/O resources\n");
4736 #ifdef PCI_RES_BUS
4737 	if (resource_list_release_active(rl, dev, child, PCI_RES_BUS) != 0)
4738 		pci_printf(&dinfo->cfg, "Device leaked PCI bus numbers\n");
4739 #endif
4740 
4741 	pci_cfg_save(child, dinfo, 1);
4742 }
4743 
4744 /*
4745  * Parse the PCI device database, if loaded, and return a pointer to a
4746  * description of the device.
4747  *
4748  * The database is flat text formatted as follows:
4749  *
4750  * Any line not in a valid format is ignored.
4751  * Lines are terminated with newline '\n' characters.
4752  *
4753  * A VENDOR line consists of the 4 digit (hex) vendor code, a TAB, then
4754  * the vendor name.
4755  *
4756  * A DEVICE line is entered immediately below the corresponding VENDOR ID.
4757  * - devices cannot be listed without a corresponding VENDOR line.
4758  * A DEVICE line consists of a TAB, the 4 digit (hex) device code,
4759  * another TAB, then the device name.
4760  */
4761 
4762 /*
4763  * Assuming (ptr) points to the beginning of a line in the database,
4764  * return the vendor or device and description of the next entry.
4765  * The value of (vendor) or (device) inappropriate for the entry type
4766  * is set to -1.  Returns nonzero at the end of the database.
4767  *
4768  * Note that this is slightly unrobust in the face of corrupt data;
4769  * we attempt to safeguard against this by spamming the end of the
4770  * database with a newline when we initialise.
4771  */
4772 static int
4773 pci_describe_parse_line(char **ptr, int *vendor, int *device, char **desc)
4774 {
4775 	char	*cp = *ptr;
4776 	int	left;
4777 
4778 	*device = -1;
4779 	*vendor = -1;
4780 	**desc = '\0';
4781 	for (;;) {
4782 		left = pci_vendordata_size - (cp - pci_vendordata);
4783 		if (left <= 0) {
4784 			*ptr = cp;
4785 			return(1);
4786 		}
4787 
4788 		/* vendor entry? */
4789 		if (*cp != '\t' &&
4790 		    sscanf(cp, "%x\t%80[^\n]", vendor, *desc) == 2)
4791 			break;
4792 		/* device entry? */
4793 		if (*cp == '\t' &&
4794 		    sscanf(cp, "%x\t%80[^\n]", device, *desc) == 2)
4795 			break;
4796 
4797 		/* skip to next line */
4798 		while (*cp != '\n' && left > 0) {
4799 			cp++;
4800 			left--;
4801 		}
4802 		if (*cp == '\n') {
4803 			cp++;
4804 			left--;
4805 		}
4806 	}
4807 	/* skip to next line */
4808 	while (*cp != '\n' && left > 0) {
4809 		cp++;
4810 		left--;
4811 	}
4812 	if (*cp == '\n' && left > 0)
4813 		cp++;
4814 	*ptr = cp;
4815 	return(0);
4816 }
4817 
4818 static char *
4819 pci_describe_device(device_t dev)
4820 {
4821 	int	vendor, device;
4822 	char	*desc, *vp, *dp, *line;
4823 
4824 	desc = vp = dp = NULL;
4825 
4826 	/*
4827 	 * If we have no vendor data, we can't do anything.
4828 	 */
4829 	if (pci_vendordata == NULL)
4830 		goto out;
4831 
4832 	/*
4833 	 * Scan the vendor data looking for this device
4834 	 */
4835 	line = pci_vendordata;
4836 	if ((vp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
4837 		goto out;
4838 	for (;;) {
4839 		if (pci_describe_parse_line(&line, &vendor, &device, &vp))
4840 			goto out;
4841 		if (vendor == pci_get_vendor(dev))
4842 			break;
4843 	}
4844 	if ((dp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
4845 		goto out;
4846 	for (;;) {
4847 		if (pci_describe_parse_line(&line, &vendor, &device, &dp)) {
4848 			*dp = 0;
4849 			break;
4850 		}
4851 		if (vendor != -1) {
4852 			*dp = 0;
4853 			break;
4854 		}
4855 		if (device == pci_get_device(dev))
4856 			break;
4857 	}
4858 	if (dp[0] == '\0')
4859 		snprintf(dp, 80, "0x%x", pci_get_device(dev));
4860 	if ((desc = malloc(strlen(vp) + strlen(dp) + 3, M_DEVBUF, M_NOWAIT)) !=
4861 	    NULL)
4862 		sprintf(desc, "%s, %s", vp, dp);
4863 out:
4864 	if (vp != NULL)
4865 		free(vp, M_DEVBUF);
4866 	if (dp != NULL)
4867 		free(dp, M_DEVBUF);
4868 	return(desc);
4869 }
4870 
4871 int
4872 pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
4873 {
4874 	struct pci_devinfo *dinfo;
4875 	pcicfgregs *cfg;
4876 
4877 	dinfo = device_get_ivars(child);
4878 	cfg = &dinfo->cfg;
4879 
4880 	switch (which) {
4881 	case PCI_IVAR_ETHADDR:
4882 		/*
4883 		 * The generic accessor doesn't deal with failure, so
4884 		 * we set the return value, then return an error.
4885 		 */
4886 		*((uint8_t **) result) = NULL;
4887 		return (EINVAL);
4888 	case PCI_IVAR_SUBVENDOR:
4889 		*result = cfg->subvendor;
4890 		break;
4891 	case PCI_IVAR_SUBDEVICE:
4892 		*result = cfg->subdevice;
4893 		break;
4894 	case PCI_IVAR_VENDOR:
4895 		*result = cfg->vendor;
4896 		break;
4897 	case PCI_IVAR_DEVICE:
4898 		*result = cfg->device;
4899 		break;
4900 	case PCI_IVAR_DEVID:
4901 		*result = (cfg->device << 16) | cfg->vendor;
4902 		break;
4903 	case PCI_IVAR_CLASS:
4904 		*result = cfg->baseclass;
4905 		break;
4906 	case PCI_IVAR_SUBCLASS:
4907 		*result = cfg->subclass;
4908 		break;
4909 	case PCI_IVAR_PROGIF:
4910 		*result = cfg->progif;
4911 		break;
4912 	case PCI_IVAR_REVID:
4913 		*result = cfg->revid;
4914 		break;
4915 	case PCI_IVAR_INTPIN:
4916 		*result = cfg->intpin;
4917 		break;
4918 	case PCI_IVAR_IRQ:
4919 		*result = cfg->intline;
4920 		break;
4921 	case PCI_IVAR_DOMAIN:
4922 		*result = cfg->domain;
4923 		break;
4924 	case PCI_IVAR_BUS:
4925 		*result = cfg->bus;
4926 		break;
4927 	case PCI_IVAR_SLOT:
4928 		*result = cfg->slot;
4929 		break;
4930 	case PCI_IVAR_FUNCTION:
4931 		*result = cfg->func;
4932 		break;
4933 	case PCI_IVAR_CMDREG:
4934 		*result = cfg->cmdreg;
4935 		break;
4936 	case PCI_IVAR_CACHELNSZ:
4937 		*result = cfg->cachelnsz;
4938 		break;
4939 	case PCI_IVAR_MINGNT:
4940 		if (cfg->hdrtype != PCIM_HDRTYPE_NORMAL) {
4941 			*result = -1;
4942 			return (EINVAL);
4943 		}
4944 		*result = cfg->mingnt;
4945 		break;
4946 	case PCI_IVAR_MAXLAT:
4947 		if (cfg->hdrtype != PCIM_HDRTYPE_NORMAL) {
4948 			*result = -1;
4949 			return (EINVAL);
4950 		}
4951 		*result = cfg->maxlat;
4952 		break;
4953 	case PCI_IVAR_LATTIMER:
4954 		*result = cfg->lattimer;
4955 		break;
4956 	default:
4957 		return (ENOENT);
4958 	}
4959 	return (0);
4960 }
4961 
4962 int
4963 pci_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
4964 {
4965 	struct pci_devinfo *dinfo;
4966 
4967 	dinfo = device_get_ivars(child);
4968 
4969 	switch (which) {
4970 	case PCI_IVAR_INTPIN:
4971 		dinfo->cfg.intpin = value;
4972 		return (0);
4973 	case PCI_IVAR_ETHADDR:
4974 	case PCI_IVAR_SUBVENDOR:
4975 	case PCI_IVAR_SUBDEVICE:
4976 	case PCI_IVAR_VENDOR:
4977 	case PCI_IVAR_DEVICE:
4978 	case PCI_IVAR_DEVID:
4979 	case PCI_IVAR_CLASS:
4980 	case PCI_IVAR_SUBCLASS:
4981 	case PCI_IVAR_PROGIF:
4982 	case PCI_IVAR_REVID:
4983 	case PCI_IVAR_IRQ:
4984 	case PCI_IVAR_DOMAIN:
4985 	case PCI_IVAR_BUS:
4986 	case PCI_IVAR_SLOT:
4987 	case PCI_IVAR_FUNCTION:
4988 		return (EINVAL);	/* disallow for now */
4989 
4990 	default:
4991 		return (ENOENT);
4992 	}
4993 }
4994 
4995 #include "opt_ddb.h"
4996 #ifdef DDB
4997 #include <ddb/ddb.h>
4998 #include <sys/cons.h>
4999 
5000 /*
5001  * List resources based on pci map registers, used for within ddb
5002  */
5003 
5004 DB_SHOW_COMMAND(pciregs, db_pci_dump)
5005 {
5006 	struct pci_devinfo *dinfo;
5007 	struct devlist *devlist_head;
5008 	struct pci_conf *p;
5009 	const char *name;
5010 	int i, error, none_count;
5011 
5012 	none_count = 0;
5013 	/* get the head of the device queue */
5014 	devlist_head = &pci_devq;
5015 
5016 	/*
5017 	 * Go through the list of devices and print out devices
5018 	 */
5019 	for (error = 0, i = 0,
5020 	     dinfo = STAILQ_FIRST(devlist_head);
5021 	     (dinfo != NULL) && (error == 0) && (i < pci_numdevs) && !db_pager_quit;
5022 	     dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {
5023 
5024 		/* Populate pd_name and pd_unit */
5025 		name = NULL;
5026 		if (dinfo->cfg.dev)
5027 			name = device_get_name(dinfo->cfg.dev);
5028 
5029 		p = &dinfo->conf;
5030 		db_printf("%s%d@pci%d:%d:%d:%d:\tclass=0x%06x card=0x%08x "
5031 			"chip=0x%08x rev=0x%02x hdr=0x%02x\n",
5032 			(name && *name) ? name : "none",
5033 			(name && *name) ? (int)device_get_unit(dinfo->cfg.dev) :
5034 			none_count++,
5035 			p->pc_sel.pc_domain, p->pc_sel.pc_bus, p->pc_sel.pc_dev,
5036 			p->pc_sel.pc_func, (p->pc_class << 16) |
5037 			(p->pc_subclass << 8) | p->pc_progif,
5038 			(p->pc_subdevice << 16) | p->pc_subvendor,
5039 			(p->pc_device << 16) | p->pc_vendor,
5040 			p->pc_revid, p->pc_hdr);
5041 	}
5042 }
5043 #endif /* DDB */
5044 
5045 static struct resource *
5046 pci_reserve_map(device_t dev, device_t child, int type, int *rid,
5047     rman_res_t start, rman_res_t end, rman_res_t count, u_int num,
5048     u_int flags)
5049 {
5050 	struct pci_devinfo *dinfo = device_get_ivars(child);
5051 	struct resource_list *rl = &dinfo->resources;
5052 	struct resource *res;
5053 	struct pci_map *pm;
5054 	uint16_t cmd;
5055 	pci_addr_t map, testval;
5056 	int mapsize;
5057 
5058 	res = NULL;
5059 
5060 	/* If rid is managed by EA, ignore it */
5061 	if (pci_ea_is_enabled(child, *rid))
5062 		goto out;
5063 
5064 	pm = pci_find_bar(child, *rid);
5065 	if (pm != NULL) {
5066 		/* This is a BAR that we failed to allocate earlier. */
5067 		mapsize = pm->pm_size;
5068 		map = pm->pm_value;
5069 	} else {
5070 		/*
5071 		 * Weed out the bogons, and figure out how large the
5072 		 * BAR/map is.  BARs that read back 0 here are bogus
5073 		 * and unimplemented.  Note: atapci in legacy mode are
5074 		 * special and handled elsewhere in the code.  If you
5075 		 * have a atapci device in legacy mode and it fails
5076 		 * here, that other code is broken.
5077 		 */
5078 		pci_read_bar(child, *rid, &map, &testval, NULL);
5079 
5080 		/*
5081 		 * Determine the size of the BAR and ignore BARs with a size
5082 		 * of 0.  Device ROM BARs use a different mask value.
5083 		 */
5084 		if (PCIR_IS_BIOS(&dinfo->cfg, *rid))
5085 			mapsize = pci_romsize(testval);
5086 		else
5087 			mapsize = pci_mapsize(testval);
5088 		if (mapsize == 0)
5089 			goto out;
5090 		pm = pci_add_bar(child, *rid, map, mapsize);
5091 	}
5092 
5093 	if (PCI_BAR_MEM(map) || PCIR_IS_BIOS(&dinfo->cfg, *rid)) {
5094 		if (type != SYS_RES_MEMORY) {
5095 			if (bootverbose)
5096 				device_printf(dev,
5097 				    "child %s requested type %d for rid %#x,"
5098 				    " but the BAR says it is an memio\n",
5099 				    device_get_nameunit(child), type, *rid);
5100 			goto out;
5101 		}
5102 	} else {
5103 		if (type != SYS_RES_IOPORT) {
5104 			if (bootverbose)
5105 				device_printf(dev,
5106 				    "child %s requested type %d for rid %#x,"
5107 				    " but the BAR says it is an ioport\n",
5108 				    device_get_nameunit(child), type, *rid);
5109 			goto out;
5110 		}
5111 	}
5112 
5113 	/*
5114 	 * For real BARs, we need to override the size that
5115 	 * the driver requests, because that's what the BAR
5116 	 * actually uses and we would otherwise have a
5117 	 * situation where we might allocate the excess to
5118 	 * another driver, which won't work.
5119 	 */
5120 	count = ((pci_addr_t)1 << mapsize) * num;
5121 	if (RF_ALIGNMENT(flags) < mapsize)
5122 		flags = (flags & ~RF_ALIGNMENT_MASK) | RF_ALIGNMENT_LOG2(mapsize);
5123 	if (PCI_BAR_MEM(map) && (map & PCIM_BAR_MEM_PREFETCH))
5124 		flags |= RF_PREFETCHABLE;
5125 
5126 	/*
5127 	 * Allocate enough resource, and then write back the
5128 	 * appropriate BAR for that resource.
5129 	 */
5130 	resource_list_add(rl, type, *rid, start, end, count);
5131 	res = resource_list_reserve(rl, dev, child, type, rid, start, end,
5132 	    count, flags & ~RF_ACTIVE);
5133 	if (res == NULL) {
5134 		resource_list_delete(rl, type, *rid);
5135 		device_printf(child,
5136 		    "%#jx bytes of rid %#x res %d failed (%#jx, %#jx).\n",
5137 		    count, *rid, type, start, end);
5138 		goto out;
5139 	}
5140 	if (bootverbose)
5141 		device_printf(child,
5142 		    "Lazy allocation of %#jx bytes rid %#x type %d at %#jx\n",
5143 		    count, *rid, type, rman_get_start(res));
5144 
5145 	/* Disable decoding via the CMD register before updating the BAR */
5146 	cmd = pci_read_config(child, PCIR_COMMAND, 2);
5147 	pci_write_config(child, PCIR_COMMAND,
5148 	    cmd & ~(PCI_BAR_MEM(map) ? PCIM_CMD_MEMEN : PCIM_CMD_PORTEN), 2);
5149 
5150 	map = rman_get_start(res);
5151 	pci_write_bar(child, pm, map);
5152 
5153 	/* Restore the original value of the CMD register */
5154 	pci_write_config(child, PCIR_COMMAND, cmd, 2);
5155 out:
5156 	return (res);
5157 }
5158 
5159 struct resource *
5160 pci_alloc_multi_resource(device_t dev, device_t child, int type, int *rid,
5161     rman_res_t start, rman_res_t end, rman_res_t count, u_long num,
5162     u_int flags)
5163 {
5164 	struct pci_devinfo *dinfo;
5165 	struct resource_list *rl;
5166 	struct resource_list_entry *rle;
5167 	struct resource *res;
5168 	pcicfgregs *cfg;
5169 
5170 	/*
5171 	 * Perform lazy resource allocation
5172 	 */
5173 	dinfo = device_get_ivars(child);
5174 	rl = &dinfo->resources;
5175 	cfg = &dinfo->cfg;
5176 	switch (type) {
5177 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
5178 	case PCI_RES_BUS:
5179 		return (pci_alloc_secbus(dev, child, rid, start, end, count,
5180 		    flags));
5181 #endif
5182 	case SYS_RES_IRQ:
5183 		/*
5184 		 * Can't alloc legacy interrupt once MSI messages have
5185 		 * been allocated.
5186 		 */
5187 		if (*rid == 0 && (cfg->msi.msi_alloc > 0 ||
5188 		    cfg->msix.msix_alloc > 0))
5189 			return (NULL);
5190 
5191 		/*
5192 		 * If the child device doesn't have an interrupt
5193 		 * routed and is deserving of an interrupt, try to
5194 		 * assign it one.
5195 		 */
5196 		if (*rid == 0 && !PCI_INTERRUPT_VALID(cfg->intline) &&
5197 		    (cfg->intpin != 0))
5198 			pci_assign_interrupt(dev, child, 0);
5199 		break;
5200 	case SYS_RES_IOPORT:
5201 	case SYS_RES_MEMORY:
5202 #ifdef NEW_PCIB
5203 		/*
5204 		 * PCI-PCI bridge I/O window resources are not BARs.
5205 		 * For those allocations just pass the request up the
5206 		 * tree.
5207 		 */
5208 		if (cfg->hdrtype == PCIM_HDRTYPE_BRIDGE) {
5209 			switch (*rid) {
5210 			case PCIR_IOBASEL_1:
5211 			case PCIR_MEMBASE_1:
5212 			case PCIR_PMBASEL_1:
5213 				/*
5214 				 * XXX: Should we bother creating a resource
5215 				 * list entry?
5216 				 */
5217 				return (bus_generic_alloc_resource(dev, child,
5218 				    type, rid, start, end, count, flags));
5219 			}
5220 		}
5221 #endif
5222 		/* Reserve resources for this BAR if needed. */
5223 		rle = resource_list_find(rl, type, *rid);
5224 		if (rle == NULL) {
5225 			res = pci_reserve_map(dev, child, type, rid, start, end,
5226 			    count, num, flags);
5227 			if (res == NULL)
5228 				return (NULL);
5229 		}
5230 	}
5231 	return (resource_list_alloc(rl, dev, child, type, rid,
5232 	    start, end, count, flags));
5233 }
5234 
5235 struct resource *
5236 pci_alloc_resource(device_t dev, device_t child, int type, int *rid,
5237     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
5238 {
5239 #ifdef PCI_IOV
5240 	struct pci_devinfo *dinfo;
5241 #endif
5242 
5243 	if (device_get_parent(child) != dev)
5244 		return (BUS_ALLOC_RESOURCE(device_get_parent(dev), child,
5245 		    type, rid, start, end, count, flags));
5246 
5247 #ifdef PCI_IOV
5248 	dinfo = device_get_ivars(child);
5249 	if (dinfo->cfg.flags & PCICFG_VF) {
5250 		switch (type) {
5251 		/* VFs can't have I/O BARs. */
5252 		case SYS_RES_IOPORT:
5253 			return (NULL);
5254 		case SYS_RES_MEMORY:
5255 			return (pci_vf_alloc_mem_resource(dev, child, rid,
5256 			    start, end, count, flags));
5257 		}
5258 
5259 		/* Fall through for other types of resource allocations. */
5260 	}
5261 #endif
5262 
5263 	return (pci_alloc_multi_resource(dev, child, type, rid, start, end,
5264 	    count, 1, flags));
5265 }
5266 
5267 int
5268 pci_release_resource(device_t dev, device_t child, int type, int rid,
5269     struct resource *r)
5270 {
5271 	struct pci_devinfo *dinfo;
5272 	struct resource_list *rl;
5273 	pcicfgregs *cfg;
5274 
5275 	if (device_get_parent(child) != dev)
5276 		return (BUS_RELEASE_RESOURCE(device_get_parent(dev), child,
5277 		    type, rid, r));
5278 
5279 	dinfo = device_get_ivars(child);
5280 	cfg = &dinfo->cfg;
5281 
5282 #ifdef PCI_IOV
5283 	if (dinfo->cfg.flags & PCICFG_VF) {
5284 		switch (type) {
5285 		/* VFs can't have I/O BARs. */
5286 		case SYS_RES_IOPORT:
5287 			return (EDOOFUS);
5288 		case SYS_RES_MEMORY:
5289 			return (pci_vf_release_mem_resource(dev, child, rid,
5290 			    r));
5291 		}
5292 
5293 		/* Fall through for other types of resource allocations. */
5294 	}
5295 #endif
5296 
5297 #ifdef NEW_PCIB
5298 	/*
5299 	 * PCI-PCI bridge I/O window resources are not BARs.  For
5300 	 * those allocations just pass the request up the tree.
5301 	 */
5302 	if (cfg->hdrtype == PCIM_HDRTYPE_BRIDGE &&
5303 	    (type == SYS_RES_IOPORT || type == SYS_RES_MEMORY)) {
5304 		switch (rid) {
5305 		case PCIR_IOBASEL_1:
5306 		case PCIR_MEMBASE_1:
5307 		case PCIR_PMBASEL_1:
5308 			return (bus_generic_release_resource(dev, child, type,
5309 			    rid, r));
5310 		}
5311 	}
5312 #endif
5313 
5314 	rl = &dinfo->resources;
5315 	return (resource_list_release(rl, dev, child, type, rid, r));
5316 }
5317 
5318 int
5319 pci_activate_resource(device_t dev, device_t child, int type, int rid,
5320     struct resource *r)
5321 {
5322 	struct pci_devinfo *dinfo;
5323 	int error;
5324 
5325 	error = bus_generic_activate_resource(dev, child, type, rid, r);
5326 	if (error)
5327 		return (error);
5328 
5329 	/* Enable decoding in the command register when activating BARs. */
5330 	if (device_get_parent(child) == dev) {
5331 		/* Device ROMs need their decoding explicitly enabled. */
5332 		dinfo = device_get_ivars(child);
5333 		if (type == SYS_RES_MEMORY && PCIR_IS_BIOS(&dinfo->cfg, rid))
5334 			pci_write_bar(child, pci_find_bar(child, rid),
5335 			    rman_get_start(r) | PCIM_BIOS_ENABLE);
5336 		switch (type) {
5337 		case SYS_RES_IOPORT:
5338 		case SYS_RES_MEMORY:
5339 			error = PCI_ENABLE_IO(dev, child, type);
5340 			break;
5341 		}
5342 	}
5343 	return (error);
5344 }
5345 
5346 int
5347 pci_deactivate_resource(device_t dev, device_t child, int type,
5348     int rid, struct resource *r)
5349 {
5350 	struct pci_devinfo *dinfo;
5351 	int error;
5352 
5353 	error = bus_generic_deactivate_resource(dev, child, type, rid, r);
5354 	if (error)
5355 		return (error);
5356 
5357 	/* Disable decoding for device ROMs. */
5358 	if (device_get_parent(child) == dev) {
5359 		dinfo = device_get_ivars(child);
5360 		if (type == SYS_RES_MEMORY && PCIR_IS_BIOS(&dinfo->cfg, rid))
5361 			pci_write_bar(child, pci_find_bar(child, rid),
5362 			    rman_get_start(r));
5363 	}
5364 	return (0);
5365 }
5366 
5367 void
5368 pci_child_deleted(device_t dev, device_t child)
5369 {
5370 	struct resource_list_entry *rle;
5371 	struct resource_list *rl;
5372 	struct pci_devinfo *dinfo;
5373 
5374 	dinfo = device_get_ivars(child);
5375 	rl = &dinfo->resources;
5376 
5377 	EVENTHANDLER_INVOKE(pci_delete_device, child);
5378 
5379 	/* Turn off access to resources we're about to free */
5380 	if (bus_child_present(child) != 0) {
5381 		pci_write_config(child, PCIR_COMMAND, pci_read_config(child,
5382 		    PCIR_COMMAND, 2) & ~(PCIM_CMD_MEMEN | PCIM_CMD_PORTEN), 2);
5383 
5384 		pci_disable_busmaster(child);
5385 	}
5386 
5387 	/* Free all allocated resources */
5388 	STAILQ_FOREACH(rle, rl, link) {
5389 		if (rle->res) {
5390 			if (rman_get_flags(rle->res) & RF_ACTIVE ||
5391 			    resource_list_busy(rl, rle->type, rle->rid)) {
5392 				pci_printf(&dinfo->cfg,
5393 				    "Resource still owned, oops. "
5394 				    "(type=%d, rid=%d, addr=%lx)\n",
5395 				    rle->type, rle->rid,
5396 				    rman_get_start(rle->res));
5397 				bus_release_resource(child, rle->type, rle->rid,
5398 				    rle->res);
5399 			}
5400 			resource_list_unreserve(rl, dev, child, rle->type,
5401 			    rle->rid);
5402 		}
5403 	}
5404 	resource_list_free(rl);
5405 
5406 	pci_freecfg(dinfo);
5407 }
5408 
5409 void
5410 pci_delete_resource(device_t dev, device_t child, int type, int rid)
5411 {
5412 	struct pci_devinfo *dinfo;
5413 	struct resource_list *rl;
5414 	struct resource_list_entry *rle;
5415 
5416 	if (device_get_parent(child) != dev)
5417 		return;
5418 
5419 	dinfo = device_get_ivars(child);
5420 	rl = &dinfo->resources;
5421 	rle = resource_list_find(rl, type, rid);
5422 	if (rle == NULL)
5423 		return;
5424 
5425 	if (rle->res) {
5426 		if (rman_get_flags(rle->res) & RF_ACTIVE ||
5427 		    resource_list_busy(rl, type, rid)) {
5428 			device_printf(dev, "delete_resource: "
5429 			    "Resource still owned by child, oops. "
5430 			    "(type=%d, rid=%d, addr=%jx)\n",
5431 			    type, rid, rman_get_start(rle->res));
5432 			return;
5433 		}
5434 		resource_list_unreserve(rl, dev, child, type, rid);
5435 	}
5436 	resource_list_delete(rl, type, rid);
5437 }
5438 
5439 struct resource_list *
5440 pci_get_resource_list (device_t dev, device_t child)
5441 {
5442 	struct pci_devinfo *dinfo = device_get_ivars(child);
5443 
5444 	return (&dinfo->resources);
5445 }
5446 
5447 bus_dma_tag_t
5448 pci_get_dma_tag(device_t bus, device_t dev)
5449 {
5450 	struct pci_softc *sc = device_get_softc(bus);
5451 
5452 	return (sc->sc_dma_tag);
5453 }
5454 
5455 uint32_t
5456 pci_read_config_method(device_t dev, device_t child, int reg, int width)
5457 {
5458 	struct pci_devinfo *dinfo = device_get_ivars(child);
5459 	pcicfgregs *cfg = &dinfo->cfg;
5460 
5461 #ifdef PCI_IOV
5462 	/*
5463 	 * SR-IOV VFs don't implement the VID or DID registers, so we have to
5464 	 * emulate them here.
5465 	 */
5466 	if (cfg->flags & PCICFG_VF) {
5467 		if (reg == PCIR_VENDOR) {
5468 			switch (width) {
5469 			case 4:
5470 				return (cfg->device << 16 | cfg->vendor);
5471 			case 2:
5472 				return (cfg->vendor);
5473 			case 1:
5474 				return (cfg->vendor & 0xff);
5475 			default:
5476 				return (0xffffffff);
5477 			}
5478 		} else if (reg == PCIR_DEVICE) {
5479 			switch (width) {
5480 			/* Note that an unaligned 4-byte read is an error. */
5481 			case 2:
5482 				return (cfg->device);
5483 			case 1:
5484 				return (cfg->device & 0xff);
5485 			default:
5486 				return (0xffffffff);
5487 			}
5488 		}
5489 	}
5490 #endif
5491 
5492 	return (PCIB_READ_CONFIG(device_get_parent(dev),
5493 	    cfg->bus, cfg->slot, cfg->func, reg, width));
5494 }
5495 
5496 void
5497 pci_write_config_method(device_t dev, device_t child, int reg,
5498     uint32_t val, int width)
5499 {
5500 	struct pci_devinfo *dinfo = device_get_ivars(child);
5501 	pcicfgregs *cfg = &dinfo->cfg;
5502 
5503 	PCIB_WRITE_CONFIG(device_get_parent(dev),
5504 	    cfg->bus, cfg->slot, cfg->func, reg, val, width);
5505 }
5506 
5507 int
5508 pci_child_location_str_method(device_t dev, device_t child, char *buf,
5509     size_t buflen)
5510 {
5511 
5512 	snprintf(buf, buflen, "slot=%d function=%d dbsf=pci%d:%d:%d:%d",
5513 	    pci_get_slot(child), pci_get_function(child), pci_get_domain(child),
5514 	    pci_get_bus(child), pci_get_slot(child), pci_get_function(child));
5515 	return (0);
5516 }
5517 
5518 int
5519 pci_child_pnpinfo_str_method(device_t dev, device_t child, char *buf,
5520     size_t buflen)
5521 {
5522 	struct pci_devinfo *dinfo;
5523 	pcicfgregs *cfg;
5524 
5525 	dinfo = device_get_ivars(child);
5526 	cfg = &dinfo->cfg;
5527 	snprintf(buf, buflen, "vendor=0x%04x device=0x%04x subvendor=0x%04x "
5528 	    "subdevice=0x%04x class=0x%02x%02x%02x", cfg->vendor, cfg->device,
5529 	    cfg->subvendor, cfg->subdevice, cfg->baseclass, cfg->subclass,
5530 	    cfg->progif);
5531 	return (0);
5532 }
5533 
5534 int
5535 pci_assign_interrupt_method(device_t dev, device_t child)
5536 {
5537 	struct pci_devinfo *dinfo = device_get_ivars(child);
5538 	pcicfgregs *cfg = &dinfo->cfg;
5539 
5540 	return (PCIB_ROUTE_INTERRUPT(device_get_parent(dev), child,
5541 	    cfg->intpin));
5542 }
5543 
5544 static void
5545 pci_lookup(void *arg, const char *name, device_t *dev)
5546 {
5547 	long val;
5548 	char *end;
5549 	int domain, bus, slot, func;
5550 
5551 	if (*dev != NULL)
5552 		return;
5553 
5554 	/*
5555 	 * Accept pciconf-style selectors of either pciD:B:S:F or
5556 	 * pciB:S:F.  In the latter case, the domain is assumed to
5557 	 * be zero.
5558 	 */
5559 	if (strncmp(name, "pci", 3) != 0)
5560 		return;
5561 	val = strtol(name + 3, &end, 10);
5562 	if (val < 0 || val > INT_MAX || *end != ':')
5563 		return;
5564 	domain = val;
5565 	val = strtol(end + 1, &end, 10);
5566 	if (val < 0 || val > INT_MAX || *end != ':')
5567 		return;
5568 	bus = val;
5569 	val = strtol(end + 1, &end, 10);
5570 	if (val < 0 || val > INT_MAX)
5571 		return;
5572 	slot = val;
5573 	if (*end == ':') {
5574 		val = strtol(end + 1, &end, 10);
5575 		if (val < 0 || val > INT_MAX || *end != '\0')
5576 			return;
5577 		func = val;
5578 	} else if (*end == '\0') {
5579 		func = slot;
5580 		slot = bus;
5581 		bus = domain;
5582 		domain = 0;
5583 	} else
5584 		return;
5585 
5586 	if (domain > PCI_DOMAINMAX || bus > PCI_BUSMAX || slot > PCI_SLOTMAX ||
5587 	    func > PCIE_ARI_FUNCMAX || (slot != 0 && func > PCI_FUNCMAX))
5588 		return;
5589 
5590 	*dev = pci_find_dbsf(domain, bus, slot, func);
5591 }
5592 
5593 static int
5594 pci_modevent(module_t mod, int what, void *arg)
5595 {
5596 	static struct cdev *pci_cdev;
5597 	static eventhandler_tag tag;
5598 
5599 	switch (what) {
5600 	case MOD_LOAD:
5601 		STAILQ_INIT(&pci_devq);
5602 		pci_generation = 0;
5603 		pci_cdev = make_dev(&pcicdev, 0, UID_ROOT, GID_WHEEL, 0644,
5604 		    "pci");
5605 		pci_load_vendor_data();
5606 		tag = EVENTHANDLER_REGISTER(dev_lookup, pci_lookup, NULL,
5607 		    1000);
5608 		break;
5609 
5610 	case MOD_UNLOAD:
5611 		if (tag != NULL)
5612 			EVENTHANDLER_DEREGISTER(dev_lookup, tag);
5613 		destroy_dev(pci_cdev);
5614 		break;
5615 	}
5616 
5617 	return (0);
5618 }
5619 
5620 static void
5621 pci_cfg_restore_pcie(device_t dev, struct pci_devinfo *dinfo)
5622 {
5623 #define	WREG(n, v)	pci_write_config(dev, pos + (n), (v), 2)
5624 	struct pcicfg_pcie *cfg;
5625 	int version, pos;
5626 
5627 	cfg = &dinfo->cfg.pcie;
5628 	pos = cfg->pcie_location;
5629 
5630 	version = cfg->pcie_flags & PCIEM_FLAGS_VERSION;
5631 
5632 	WREG(PCIER_DEVICE_CTL, cfg->pcie_device_ctl);
5633 
5634 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
5635 	    cfg->pcie_type == PCIEM_TYPE_ENDPOINT ||
5636 	    cfg->pcie_type == PCIEM_TYPE_LEGACY_ENDPOINT)
5637 		WREG(PCIER_LINK_CTL, cfg->pcie_link_ctl);
5638 
5639 	if (version > 1 || (cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
5640 	    (cfg->pcie_type == PCIEM_TYPE_DOWNSTREAM_PORT &&
5641 	     (cfg->pcie_flags & PCIEM_FLAGS_SLOT))))
5642 		WREG(PCIER_SLOT_CTL, cfg->pcie_slot_ctl);
5643 
5644 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
5645 	    cfg->pcie_type == PCIEM_TYPE_ROOT_EC)
5646 		WREG(PCIER_ROOT_CTL, cfg->pcie_root_ctl);
5647 
5648 	if (version > 1) {
5649 		WREG(PCIER_DEVICE_CTL2, cfg->pcie_device_ctl2);
5650 		WREG(PCIER_LINK_CTL2, cfg->pcie_link_ctl2);
5651 		WREG(PCIER_SLOT_CTL2, cfg->pcie_slot_ctl2);
5652 	}
5653 #undef WREG
5654 }
5655 
5656 static void
5657 pci_cfg_restore_pcix(device_t dev, struct pci_devinfo *dinfo)
5658 {
5659 	pci_write_config(dev, dinfo->cfg.pcix.pcix_location + PCIXR_COMMAND,
5660 	    dinfo->cfg.pcix.pcix_command,  2);
5661 }
5662 
5663 void
5664 pci_cfg_restore(device_t dev, struct pci_devinfo *dinfo)
5665 {
5666 
5667 	/*
5668 	 * Restore the device to full power mode.  We must do this
5669 	 * before we restore the registers because moving from D3 to
5670 	 * D0 will cause the chip's BARs and some other registers to
5671 	 * be reset to some unknown power on reset values.  Cut down
5672 	 * the noise on boot by doing nothing if we are already in
5673 	 * state D0.
5674 	 */
5675 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0)
5676 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
5677 	pci_write_config(dev, PCIR_COMMAND, dinfo->cfg.cmdreg, 2);
5678 	pci_write_config(dev, PCIR_INTLINE, dinfo->cfg.intline, 1);
5679 	pci_write_config(dev, PCIR_INTPIN, dinfo->cfg.intpin, 1);
5680 	pci_write_config(dev, PCIR_CACHELNSZ, dinfo->cfg.cachelnsz, 1);
5681 	pci_write_config(dev, PCIR_LATTIMER, dinfo->cfg.lattimer, 1);
5682 	pci_write_config(dev, PCIR_PROGIF, dinfo->cfg.progif, 1);
5683 	pci_write_config(dev, PCIR_REVID, dinfo->cfg.revid, 1);
5684 	switch (dinfo->cfg.hdrtype & PCIM_HDRTYPE) {
5685 	case PCIM_HDRTYPE_NORMAL:
5686 		pci_write_config(dev, PCIR_MINGNT, dinfo->cfg.mingnt, 1);
5687 		pci_write_config(dev, PCIR_MAXLAT, dinfo->cfg.maxlat, 1);
5688 		break;
5689 	case PCIM_HDRTYPE_BRIDGE:
5690 		pci_write_config(dev, PCIR_SECLAT_1,
5691 		    dinfo->cfg.bridge.br_seclat, 1);
5692 		pci_write_config(dev, PCIR_SUBBUS_1,
5693 		    dinfo->cfg.bridge.br_subbus, 1);
5694 		pci_write_config(dev, PCIR_SECBUS_1,
5695 		    dinfo->cfg.bridge.br_secbus, 1);
5696 		pci_write_config(dev, PCIR_PRIBUS_1,
5697 		    dinfo->cfg.bridge.br_pribus, 1);
5698 		pci_write_config(dev, PCIR_BRIDGECTL_1,
5699 		    dinfo->cfg.bridge.br_control, 2);
5700 		break;
5701 	case PCIM_HDRTYPE_CARDBUS:
5702 		pci_write_config(dev, PCIR_SECLAT_2,
5703 		    dinfo->cfg.bridge.br_seclat, 1);
5704 		pci_write_config(dev, PCIR_SUBBUS_2,
5705 		    dinfo->cfg.bridge.br_subbus, 1);
5706 		pci_write_config(dev, PCIR_SECBUS_2,
5707 		    dinfo->cfg.bridge.br_secbus, 1);
5708 		pci_write_config(dev, PCIR_PRIBUS_2,
5709 		    dinfo->cfg.bridge.br_pribus, 1);
5710 		pci_write_config(dev, PCIR_BRIDGECTL_2,
5711 		    dinfo->cfg.bridge.br_control, 2);
5712 		break;
5713 	}
5714 	pci_restore_bars(dev);
5715 
5716 	/*
5717 	 * Restore extended capabilities for PCI-Express and PCI-X
5718 	 */
5719 	if (dinfo->cfg.pcie.pcie_location != 0)
5720 		pci_cfg_restore_pcie(dev, dinfo);
5721 	if (dinfo->cfg.pcix.pcix_location != 0)
5722 		pci_cfg_restore_pcix(dev, dinfo);
5723 
5724 	/* Restore MSI and MSI-X configurations if they are present. */
5725 	if (dinfo->cfg.msi.msi_location != 0)
5726 		pci_resume_msi(dev);
5727 	if (dinfo->cfg.msix.msix_location != 0)
5728 		pci_resume_msix(dev);
5729 
5730 #ifdef PCI_IOV
5731 	if (dinfo->cfg.iov != NULL)
5732 		pci_iov_cfg_restore(dev, dinfo);
5733 #endif
5734 }
5735 
5736 static void
5737 pci_cfg_save_pcie(device_t dev, struct pci_devinfo *dinfo)
5738 {
5739 #define	RREG(n)	pci_read_config(dev, pos + (n), 2)
5740 	struct pcicfg_pcie *cfg;
5741 	int version, pos;
5742 
5743 	cfg = &dinfo->cfg.pcie;
5744 	pos = cfg->pcie_location;
5745 
5746 	cfg->pcie_flags = RREG(PCIER_FLAGS);
5747 
5748 	version = cfg->pcie_flags & PCIEM_FLAGS_VERSION;
5749 
5750 	cfg->pcie_device_ctl = RREG(PCIER_DEVICE_CTL);
5751 
5752 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
5753 	    cfg->pcie_type == PCIEM_TYPE_ENDPOINT ||
5754 	    cfg->pcie_type == PCIEM_TYPE_LEGACY_ENDPOINT)
5755 		cfg->pcie_link_ctl = RREG(PCIER_LINK_CTL);
5756 
5757 	if (version > 1 || (cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
5758 	    (cfg->pcie_type == PCIEM_TYPE_DOWNSTREAM_PORT &&
5759 	     (cfg->pcie_flags & PCIEM_FLAGS_SLOT))))
5760 		cfg->pcie_slot_ctl = RREG(PCIER_SLOT_CTL);
5761 
5762 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
5763 	    cfg->pcie_type == PCIEM_TYPE_ROOT_EC)
5764 		cfg->pcie_root_ctl = RREG(PCIER_ROOT_CTL);
5765 
5766 	if (version > 1) {
5767 		cfg->pcie_device_ctl2 = RREG(PCIER_DEVICE_CTL2);
5768 		cfg->pcie_link_ctl2 = RREG(PCIER_LINK_CTL2);
5769 		cfg->pcie_slot_ctl2 = RREG(PCIER_SLOT_CTL2);
5770 	}
5771 #undef RREG
5772 }
5773 
5774 static void
5775 pci_cfg_save_pcix(device_t dev, struct pci_devinfo *dinfo)
5776 {
5777 	dinfo->cfg.pcix.pcix_command = pci_read_config(dev,
5778 	    dinfo->cfg.pcix.pcix_location + PCIXR_COMMAND, 2);
5779 }
5780 
5781 void
5782 pci_cfg_save(device_t dev, struct pci_devinfo *dinfo, int setstate)
5783 {
5784 	uint32_t cls;
5785 	int ps;
5786 
5787 	/*
5788 	 * Some drivers apparently write to these registers w/o updating our
5789 	 * cached copy.  No harm happens if we update the copy, so do so here
5790 	 * so we can restore them.  The COMMAND register is modified by the
5791 	 * bus w/o updating the cache.  This should represent the normally
5792 	 * writable portion of the 'defined' part of type 0/1/2 headers.
5793 	 */
5794 	dinfo->cfg.vendor = pci_read_config(dev, PCIR_VENDOR, 2);
5795 	dinfo->cfg.device = pci_read_config(dev, PCIR_DEVICE, 2);
5796 	dinfo->cfg.cmdreg = pci_read_config(dev, PCIR_COMMAND, 2);
5797 	dinfo->cfg.intline = pci_read_config(dev, PCIR_INTLINE, 1);
5798 	dinfo->cfg.intpin = pci_read_config(dev, PCIR_INTPIN, 1);
5799 	dinfo->cfg.cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
5800 	dinfo->cfg.lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
5801 	dinfo->cfg.baseclass = pci_read_config(dev, PCIR_CLASS, 1);
5802 	dinfo->cfg.subclass = pci_read_config(dev, PCIR_SUBCLASS, 1);
5803 	dinfo->cfg.progif = pci_read_config(dev, PCIR_PROGIF, 1);
5804 	dinfo->cfg.revid = pci_read_config(dev, PCIR_REVID, 1);
5805 	switch (dinfo->cfg.hdrtype & PCIM_HDRTYPE) {
5806 	case PCIM_HDRTYPE_NORMAL:
5807 		dinfo->cfg.subvendor = pci_read_config(dev, PCIR_SUBVEND_0, 2);
5808 		dinfo->cfg.subdevice = pci_read_config(dev, PCIR_SUBDEV_0, 2);
5809 		dinfo->cfg.mingnt = pci_read_config(dev, PCIR_MINGNT, 1);
5810 		dinfo->cfg.maxlat = pci_read_config(dev, PCIR_MAXLAT, 1);
5811 		break;
5812 	case PCIM_HDRTYPE_BRIDGE:
5813 		dinfo->cfg.bridge.br_seclat = pci_read_config(dev,
5814 		    PCIR_SECLAT_1, 1);
5815 		dinfo->cfg.bridge.br_subbus = pci_read_config(dev,
5816 		    PCIR_SUBBUS_1, 1);
5817 		dinfo->cfg.bridge.br_secbus = pci_read_config(dev,
5818 		    PCIR_SECBUS_1, 1);
5819 		dinfo->cfg.bridge.br_pribus = pci_read_config(dev,
5820 		    PCIR_PRIBUS_1, 1);
5821 		dinfo->cfg.bridge.br_control = pci_read_config(dev,
5822 		    PCIR_BRIDGECTL_1, 2);
5823 		break;
5824 	case PCIM_HDRTYPE_CARDBUS:
5825 		dinfo->cfg.bridge.br_seclat = pci_read_config(dev,
5826 		    PCIR_SECLAT_2, 1);
5827 		dinfo->cfg.bridge.br_subbus = pci_read_config(dev,
5828 		    PCIR_SUBBUS_2, 1);
5829 		dinfo->cfg.bridge.br_secbus = pci_read_config(dev,
5830 		    PCIR_SECBUS_2, 1);
5831 		dinfo->cfg.bridge.br_pribus = pci_read_config(dev,
5832 		    PCIR_PRIBUS_2, 1);
5833 		dinfo->cfg.bridge.br_control = pci_read_config(dev,
5834 		    PCIR_BRIDGECTL_2, 2);
5835 		dinfo->cfg.subvendor = pci_read_config(dev, PCIR_SUBVEND_2, 2);
5836 		dinfo->cfg.subdevice = pci_read_config(dev, PCIR_SUBDEV_2, 2);
5837 		break;
5838 	}
5839 
5840 	if (dinfo->cfg.pcie.pcie_location != 0)
5841 		pci_cfg_save_pcie(dev, dinfo);
5842 
5843 	if (dinfo->cfg.pcix.pcix_location != 0)
5844 		pci_cfg_save_pcix(dev, dinfo);
5845 
5846 #ifdef PCI_IOV
5847 	if (dinfo->cfg.iov != NULL)
5848 		pci_iov_cfg_save(dev, dinfo);
5849 #endif
5850 
5851 	/*
5852 	 * don't set the state for display devices, base peripherals and
5853 	 * memory devices since bad things happen when they are powered down.
5854 	 * We should (a) have drivers that can easily detach and (b) use
5855 	 * generic drivers for these devices so that some device actually
5856 	 * attaches.  We need to make sure that when we implement (a) we don't
5857 	 * power the device down on a reattach.
5858 	 */
5859 	cls = pci_get_class(dev);
5860 	if (!setstate)
5861 		return;
5862 	switch (pci_do_power_nodriver)
5863 	{
5864 		case 0:		/* NO powerdown at all */
5865 			return;
5866 		case 1:		/* Conservative about what to power down */
5867 			if (cls == PCIC_STORAGE)
5868 				return;
5869 			/*FALLTHROUGH*/
5870 		case 2:		/* Aggressive about what to power down */
5871 			if (cls == PCIC_DISPLAY || cls == PCIC_MEMORY ||
5872 			    cls == PCIC_BASEPERIPH)
5873 				return;
5874 			/*FALLTHROUGH*/
5875 		case 3:		/* Power down everything */
5876 			break;
5877 	}
5878 	/*
5879 	 * PCI spec says we can only go into D3 state from D0 state.
5880 	 * Transition from D[12] into D0 before going to D3 state.
5881 	 */
5882 	ps = pci_get_powerstate(dev);
5883 	if (ps != PCI_POWERSTATE_D0 && ps != PCI_POWERSTATE_D3)
5884 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
5885 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D3)
5886 		pci_set_powerstate(dev, PCI_POWERSTATE_D3);
5887 }
5888 
5889 /* Wrapper APIs suitable for device driver use. */
5890 void
5891 pci_save_state(device_t dev)
5892 {
5893 	struct pci_devinfo *dinfo;
5894 
5895 	dinfo = device_get_ivars(dev);
5896 	pci_cfg_save(dev, dinfo, 0);
5897 }
5898 
5899 void
5900 pci_restore_state(device_t dev)
5901 {
5902 	struct pci_devinfo *dinfo;
5903 
5904 	dinfo = device_get_ivars(dev);
5905 	pci_cfg_restore(dev, dinfo);
5906 }
5907 
5908 static int
5909 pci_get_id_method(device_t dev, device_t child, enum pci_id_type type,
5910     uintptr_t *id)
5911 {
5912 
5913 	return (PCIB_GET_ID(device_get_parent(dev), child, type, id));
5914 }
5915 
5916 /* Find the upstream port of a given PCI device in a root complex. */
5917 device_t
5918 pci_find_pcie_root_port(device_t dev)
5919 {
5920 	struct pci_devinfo *dinfo;
5921 	devclass_t pci_class;
5922 	device_t pcib, bus;
5923 
5924 	pci_class = devclass_find("pci");
5925 	KASSERT(device_get_devclass(device_get_parent(dev)) == pci_class,
5926 	    ("%s: non-pci device %s", __func__, device_get_nameunit(dev)));
5927 
5928 	/*
5929 	 * Walk the bridge hierarchy until we find a PCI-e root
5930 	 * port or a non-PCI device.
5931 	 */
5932 	for (;;) {
5933 		bus = device_get_parent(dev);
5934 		KASSERT(bus != NULL, ("%s: null parent of %s", __func__,
5935 		    device_get_nameunit(dev)));
5936 
5937 		pcib = device_get_parent(bus);
5938 		KASSERT(pcib != NULL, ("%s: null bridge of %s", __func__,
5939 		    device_get_nameunit(bus)));
5940 
5941 		/*
5942 		 * pcib's parent must be a PCI bus for this to be a
5943 		 * PCI-PCI bridge.
5944 		 */
5945 		if (device_get_devclass(device_get_parent(pcib)) != pci_class)
5946 			return (NULL);
5947 
5948 		dinfo = device_get_ivars(pcib);
5949 		if (dinfo->cfg.pcie.pcie_location != 0 &&
5950 		    dinfo->cfg.pcie.pcie_type == PCIEM_TYPE_ROOT_PORT)
5951 			return (pcib);
5952 
5953 		dev = pcib;
5954 	}
5955 }
5956 
5957 /*
5958  * Wait for pending transactions to complete on a PCI-express function.
5959  *
5960  * The maximum delay is specified in milliseconds in max_delay.  Note
5961  * that this function may sleep.
5962  *
5963  * Returns true if the function is idle and false if the timeout is
5964  * exceeded.  If dev is not a PCI-express function, this returns true.
5965  */
5966 bool
5967 pcie_wait_for_pending_transactions(device_t dev, u_int max_delay)
5968 {
5969 	struct pci_devinfo *dinfo = device_get_ivars(dev);
5970 	uint16_t sta;
5971 	int cap;
5972 
5973 	cap = dinfo->cfg.pcie.pcie_location;
5974 	if (cap == 0)
5975 		return (true);
5976 
5977 	sta = pci_read_config(dev, cap + PCIER_DEVICE_STA, 2);
5978 	while (sta & PCIEM_STA_TRANSACTION_PND) {
5979 		if (max_delay == 0)
5980 			return (false);
5981 
5982 		/* Poll once every 100 milliseconds up to the timeout. */
5983 		if (max_delay > 100) {
5984 			pause_sbt("pcietp", 100 * SBT_1MS, 0, C_HARDCLOCK);
5985 			max_delay -= 100;
5986 		} else {
5987 			pause_sbt("pcietp", max_delay * SBT_1MS, 0,
5988 			    C_HARDCLOCK);
5989 			max_delay = 0;
5990 		}
5991 		sta = pci_read_config(dev, cap + PCIER_DEVICE_STA, 2);
5992 	}
5993 
5994 	return (true);
5995 }
5996 
5997 /*
5998  * Determine the maximum Completion Timeout in microseconds.
5999  *
6000  * For non-PCI-express functions this returns 0.
6001  */
6002 int
6003 pcie_get_max_completion_timeout(device_t dev)
6004 {
6005 	struct pci_devinfo *dinfo = device_get_ivars(dev);
6006 	int cap;
6007 
6008 	cap = dinfo->cfg.pcie.pcie_location;
6009 	if (cap == 0)
6010 		return (0);
6011 
6012 	/*
6013 	 * Functions using the 1.x spec use the default timeout range of
6014 	 * 50 microseconds to 50 milliseconds.  Functions that do not
6015 	 * support programmable timeouts also use this range.
6016 	 */
6017 	if ((dinfo->cfg.pcie.pcie_flags & PCIEM_FLAGS_VERSION) < 2 ||
6018 	    (pci_read_config(dev, cap + PCIER_DEVICE_CAP2, 4) &
6019 	    PCIEM_CAP2_COMP_TIMO_RANGES) == 0)
6020 		return (50 * 1000);
6021 
6022 	switch (pci_read_config(dev, cap + PCIER_DEVICE_CTL2, 2) &
6023 	    PCIEM_CTL2_COMP_TIMO_VAL) {
6024 	case PCIEM_CTL2_COMP_TIMO_100US:
6025 		return (100);
6026 	case PCIEM_CTL2_COMP_TIMO_10MS:
6027 		return (10 * 1000);
6028 	case PCIEM_CTL2_COMP_TIMO_55MS:
6029 		return (55 * 1000);
6030 	case PCIEM_CTL2_COMP_TIMO_210MS:
6031 		return (210 * 1000);
6032 	case PCIEM_CTL2_COMP_TIMO_900MS:
6033 		return (900 * 1000);
6034 	case PCIEM_CTL2_COMP_TIMO_3500MS:
6035 		return (3500 * 1000);
6036 	case PCIEM_CTL2_COMP_TIMO_13S:
6037 		return (13 * 1000 * 1000);
6038 	case PCIEM_CTL2_COMP_TIMO_64S:
6039 		return (64 * 1000 * 1000);
6040 	default:
6041 		return (50 * 1000);
6042 	}
6043 }
6044 
6045 /*
6046  * Perform a Function Level Reset (FLR) on a device.
6047  *
6048  * This function first waits for any pending transactions to complete
6049  * within the timeout specified by max_delay.  If transactions are
6050  * still pending, the function will return false without attempting a
6051  * reset.
6052  *
6053  * If dev is not a PCI-express function or does not support FLR, this
6054  * function returns false.
6055  *
6056  * Note that no registers are saved or restored.  The caller is
6057  * responsible for saving and restoring any registers including
6058  * PCI-standard registers via pci_save_state() and
6059  * pci_restore_state().
6060  */
6061 bool
6062 pcie_flr(device_t dev, u_int max_delay, bool force)
6063 {
6064 	struct pci_devinfo *dinfo = device_get_ivars(dev);
6065 	uint16_t cmd, ctl;
6066 	int compl_delay;
6067 	int cap;
6068 
6069 	cap = dinfo->cfg.pcie.pcie_location;
6070 	if (cap == 0)
6071 		return (false);
6072 
6073 	if (!(pci_read_config(dev, cap + PCIER_DEVICE_CAP, 4) & PCIEM_CAP_FLR))
6074 		return (false);
6075 
6076 	/*
6077 	 * Disable busmastering to prevent generation of new
6078 	 * transactions while waiting for the device to go idle.  If
6079 	 * the idle timeout fails, the command register is restored
6080 	 * which will re-enable busmastering.
6081 	 */
6082 	cmd = pci_read_config(dev, PCIR_COMMAND, 2);
6083 	pci_write_config(dev, PCIR_COMMAND, cmd & ~(PCIM_CMD_BUSMASTEREN), 2);
6084 	if (!pcie_wait_for_pending_transactions(dev, max_delay)) {
6085 		if (!force) {
6086 			pci_write_config(dev, PCIR_COMMAND, cmd, 2);
6087 			return (false);
6088 		}
6089 		pci_printf(&dinfo->cfg,
6090 		    "Resetting with transactions pending after %d ms\n",
6091 		    max_delay);
6092 
6093 		/*
6094 		 * Extend the post-FLR delay to cover the maximum
6095 		 * Completion Timeout delay of anything in flight
6096 		 * during the FLR delay.  Enforce a minimum delay of
6097 		 * at least 10ms.
6098 		 */
6099 		compl_delay = pcie_get_max_completion_timeout(dev) / 1000;
6100 		if (compl_delay < 10)
6101 			compl_delay = 10;
6102 	} else
6103 		compl_delay = 0;
6104 
6105 	/* Initiate the reset. */
6106 	ctl = pci_read_config(dev, cap + PCIER_DEVICE_CTL, 2);
6107 	pci_write_config(dev, cap + PCIER_DEVICE_CTL, ctl |
6108 	    PCIEM_CTL_INITIATE_FLR, 2);
6109 
6110 	/* Wait for 100ms. */
6111 	pause_sbt("pcieflr", (100 + compl_delay) * SBT_1MS, 0, C_HARDCLOCK);
6112 
6113 	if (pci_read_config(dev, cap + PCIER_DEVICE_STA, 2) &
6114 	    PCIEM_STA_TRANSACTION_PND)
6115 		pci_printf(&dinfo->cfg, "Transactions pending after FLR!\n");
6116 	return (true);
6117 }
6118