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