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