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