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