xref: /freebsd/sys/dev/pci/pci.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
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 		for (i = 0; i < cfg->msix.msix_alloc; i++) {
2451 			mv = &cfg->msix.msix_vectors[i];
2452 			if (mv->mv_irq == irq) {
2453 				error = PCIB_MAP_MSI(device_get_parent(bus),
2454 				    dev, irq, &addr, &data);
2455 				if (error)
2456 					return (error);
2457 				mv->mv_address = addr;
2458 				mv->mv_data = data;
2459 				for (j = 0; j < cfg->msix.msix_table_len; j++) {
2460 					mte = &cfg->msix.msix_table[j];
2461 					if (mte->mte_vector != i + 1)
2462 						continue;
2463 					if (mte->mte_handlers == 0)
2464 						continue;
2465 					pci_mask_msix(dev, j);
2466 					pci_enable_msix(dev, j, addr, data);
2467 					pci_unmask_msix(dev, j);
2468 				}
2469 			}
2470 		}
2471 		return (ENOENT);
2472 	}
2473 
2474 	return (ENOENT);
2475 }
2476 
2477 /*
2478  * Returns true if the specified device is blacklisted because MSI
2479  * doesn't work.
2480  */
2481 int
2482 pci_msi_device_blacklisted(device_t dev)
2483 {
2484 
2485 	if (!pci_honor_msi_blacklist)
2486 		return (0);
2487 
2488 	return (pci_has_quirk(pci_get_devid(dev), PCI_QUIRK_DISABLE_MSI));
2489 }
2490 
2491 /*
2492  * Determine if MSI is blacklisted globally on this system.  Currently,
2493  * we just check for blacklisted chipsets as represented by the
2494  * host-PCI bridge at device 0:0:0.  In the future, it may become
2495  * necessary to check other system attributes, such as the kenv values
2496  * that give the motherboard manufacturer and model number.
2497  */
2498 static int
2499 pci_msi_blacklisted(void)
2500 {
2501 	device_t dev;
2502 
2503 	if (!pci_honor_msi_blacklist)
2504 		return (0);
2505 
2506 	/* Blacklist all non-PCI-express and non-PCI-X chipsets. */
2507 	if (!(pcie_chipset || pcix_chipset)) {
2508 		if (vm_guest != VM_GUEST_NO) {
2509 			/*
2510 			 * Whitelist older chipsets in virtual
2511 			 * machines known to support MSI.
2512 			 */
2513 			dev = pci_find_bsf(0, 0, 0);
2514 			if (dev != NULL)
2515 				return (!pci_has_quirk(pci_get_devid(dev),
2516 					PCI_QUIRK_ENABLE_MSI_VM));
2517 		}
2518 		return (1);
2519 	}
2520 
2521 	dev = pci_find_bsf(0, 0, 0);
2522 	if (dev != NULL)
2523 		return (pci_msi_device_blacklisted(dev));
2524 	return (0);
2525 }
2526 
2527 /*
2528  * Returns true if the specified device is blacklisted because MSI-X
2529  * doesn't work.  Note that this assumes that if MSI doesn't work,
2530  * MSI-X doesn't either.
2531  */
2532 int
2533 pci_msix_device_blacklisted(device_t dev)
2534 {
2535 
2536 	if (!pci_honor_msi_blacklist)
2537 		return (0);
2538 
2539 	if (pci_has_quirk(pci_get_devid(dev), PCI_QUIRK_DISABLE_MSIX))
2540 		return (1);
2541 
2542 	return (pci_msi_device_blacklisted(dev));
2543 }
2544 
2545 /*
2546  * Determine if MSI-X is blacklisted globally on this system.  If MSI
2547  * is blacklisted, assume that MSI-X is as well.  Check for additional
2548  * chipsets where MSI works but MSI-X does not.
2549  */
2550 static int
2551 pci_msix_blacklisted(void)
2552 {
2553 	device_t dev;
2554 
2555 	if (!pci_honor_msi_blacklist)
2556 		return (0);
2557 
2558 	dev = pci_find_bsf(0, 0, 0);
2559 	if (dev != NULL && pci_has_quirk(pci_get_devid(dev),
2560 	    PCI_QUIRK_DISABLE_MSIX))
2561 		return (1);
2562 
2563 	return (pci_msi_blacklisted());
2564 }
2565 
2566 /*
2567  * Attempt to allocate *count MSI messages.  The actual number allocated is
2568  * returned in *count.  After this function returns, each message will be
2569  * available to the driver as SYS_RES_IRQ resources starting at a rid 1.
2570  */
2571 int
2572 pci_alloc_msi_method(device_t dev, device_t child, int *count)
2573 {
2574 	struct pci_devinfo *dinfo = device_get_ivars(child);
2575 	pcicfgregs *cfg = &dinfo->cfg;
2576 	struct resource_list_entry *rle;
2577 	int actual, error, i, irqs[32];
2578 	uint16_t ctrl;
2579 
2580 	/* Don't let count == 0 get us into trouble. */
2581 	if (*count == 0)
2582 		return (EINVAL);
2583 
2584 	/* If rid 0 is allocated, then fail. */
2585 	rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, 0);
2586 	if (rle != NULL && rle->res != NULL)
2587 		return (ENXIO);
2588 
2589 	/* Already have allocated messages? */
2590 	if (cfg->msi.msi_alloc != 0 || cfg->msix.msix_alloc != 0)
2591 		return (ENXIO);
2592 
2593 	/* If MSI is blacklisted for this system, fail. */
2594 	if (pci_msi_blacklisted())
2595 		return (ENXIO);
2596 
2597 	/* MSI capability present? */
2598 	if (cfg->msi.msi_location == 0 || !pci_do_msi)
2599 		return (ENODEV);
2600 
2601 	if (bootverbose)
2602 		device_printf(child,
2603 		    "attempting to allocate %d MSI vectors (%d supported)\n",
2604 		    *count, cfg->msi.msi_msgnum);
2605 
2606 	/* Don't ask for more than the device supports. */
2607 	actual = min(*count, cfg->msi.msi_msgnum);
2608 
2609 	/* Don't ask for more than 32 messages. */
2610 	actual = min(actual, 32);
2611 
2612 	/* MSI requires power of 2 number of messages. */
2613 	if (!powerof2(actual))
2614 		return (EINVAL);
2615 
2616 	for (;;) {
2617 		/* Try to allocate N messages. */
2618 		error = PCIB_ALLOC_MSI(device_get_parent(dev), child, actual,
2619 		    actual, irqs);
2620 		if (error == 0)
2621 			break;
2622 		if (actual == 1)
2623 			return (error);
2624 
2625 		/* Try N / 2. */
2626 		actual >>= 1;
2627 	}
2628 
2629 	/*
2630 	 * We now have N actual messages mapped onto SYS_RES_IRQ
2631 	 * resources in the irqs[] array, so add new resources
2632 	 * starting at rid 1.
2633 	 */
2634 	for (i = 0; i < actual; i++)
2635 		resource_list_add(&dinfo->resources, SYS_RES_IRQ, i + 1,
2636 		    irqs[i], irqs[i], 1);
2637 
2638 	if (bootverbose) {
2639 		if (actual == 1)
2640 			device_printf(child, "using IRQ %d for MSI\n", irqs[0]);
2641 		else {
2642 			int run;
2643 
2644 			/*
2645 			 * Be fancy and try to print contiguous runs
2646 			 * of IRQ values as ranges.  'run' is true if
2647 			 * we are in a range.
2648 			 */
2649 			device_printf(child, "using IRQs %d", irqs[0]);
2650 			run = 0;
2651 			for (i = 1; i < actual; i++) {
2652 				/* Still in a run? */
2653 				if (irqs[i] == irqs[i - 1] + 1) {
2654 					run = 1;
2655 					continue;
2656 				}
2657 
2658 				/* Finish previous range. */
2659 				if (run) {
2660 					printf("-%d", irqs[i - 1]);
2661 					run = 0;
2662 				}
2663 
2664 				/* Start new range. */
2665 				printf(",%d", irqs[i]);
2666 			}
2667 
2668 			/* Unfinished range? */
2669 			if (run)
2670 				printf("-%d", irqs[actual - 1]);
2671 			printf(" for MSI\n");
2672 		}
2673 	}
2674 
2675 	/* Update control register with actual count. */
2676 	ctrl = cfg->msi.msi_ctrl;
2677 	ctrl &= ~PCIM_MSICTRL_MME_MASK;
2678 	ctrl |= (ffs(actual) - 1) << 4;
2679 	cfg->msi.msi_ctrl = ctrl;
2680 	pci_write_config(child, cfg->msi.msi_location + PCIR_MSI_CTRL, ctrl, 2);
2681 
2682 	/* Update counts of alloc'd messages. */
2683 	cfg->msi.msi_alloc = actual;
2684 	cfg->msi.msi_handlers = 0;
2685 	*count = actual;
2686 	return (0);
2687 }
2688 
2689 /* Release the MSI messages associated with this device. */
2690 int
2691 pci_release_msi_method(device_t dev, device_t child)
2692 {
2693 	struct pci_devinfo *dinfo = device_get_ivars(child);
2694 	struct pcicfg_msi *msi = &dinfo->cfg.msi;
2695 	struct resource_list_entry *rle;
2696 	int error, i, irqs[32];
2697 
2698 	/* Try MSI-X first. */
2699 	error = pci_release_msix(dev, child);
2700 	if (error != ENODEV)
2701 		return (error);
2702 
2703 	/* Do we have any messages to release? */
2704 	if (msi->msi_alloc == 0)
2705 		return (ENODEV);
2706 	KASSERT(msi->msi_alloc <= 32, ("more than 32 alloc'd messages"));
2707 
2708 	/* Make sure none of the resources are allocated. */
2709 	if (msi->msi_handlers > 0)
2710 		return (EBUSY);
2711 	for (i = 0; i < msi->msi_alloc; i++) {
2712 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, i + 1);
2713 		KASSERT(rle != NULL, ("missing MSI resource"));
2714 		if (rle->res != NULL)
2715 			return (EBUSY);
2716 		irqs[i] = rle->start;
2717 	}
2718 
2719 	/* Update control register with 0 count. */
2720 	KASSERT(!(msi->msi_ctrl & PCIM_MSICTRL_MSI_ENABLE),
2721 	    ("%s: MSI still enabled", __func__));
2722 	msi->msi_ctrl &= ~PCIM_MSICTRL_MME_MASK;
2723 	pci_write_config(child, msi->msi_location + PCIR_MSI_CTRL,
2724 	    msi->msi_ctrl, 2);
2725 
2726 	/* Release the messages. */
2727 	PCIB_RELEASE_MSI(device_get_parent(dev), child, msi->msi_alloc, irqs);
2728 	for (i = 0; i < msi->msi_alloc; i++)
2729 		resource_list_delete(&dinfo->resources, SYS_RES_IRQ, i + 1);
2730 
2731 	/* Update alloc count. */
2732 	msi->msi_alloc = 0;
2733 	msi->msi_addr = 0;
2734 	msi->msi_data = 0;
2735 	return (0);
2736 }
2737 
2738 /*
2739  * Return the max supported MSI messages this device supports.
2740  * Basically, assuming the MD code can alloc messages, this function
2741  * should return the maximum value that pci_alloc_msi() can return.
2742  * Thus, it is subject to the tunables, etc.
2743  */
2744 int
2745 pci_msi_count_method(device_t dev, device_t child)
2746 {
2747 	struct pci_devinfo *dinfo = device_get_ivars(child);
2748 	struct pcicfg_msi *msi = &dinfo->cfg.msi;
2749 
2750 	if (pci_do_msi && msi->msi_location != 0)
2751 		return (msi->msi_msgnum);
2752 	return (0);
2753 }
2754 
2755 /* free pcicfgregs structure and all depending data structures */
2756 
2757 int
2758 pci_freecfg(struct pci_devinfo *dinfo)
2759 {
2760 	struct devlist *devlist_head;
2761 	struct pci_map *pm, *next;
2762 
2763 	devlist_head = &pci_devq;
2764 
2765 	if (dinfo->cfg.vpd.vpd_reg)
2766 		vpd_free(&dinfo->cfg.vpd);
2767 
2768 	STAILQ_FOREACH_SAFE(pm, &dinfo->cfg.maps, pm_link, next) {
2769 		free(pm, M_DEVBUF);
2770 	}
2771 	STAILQ_REMOVE(devlist_head, dinfo, pci_devinfo, pci_links);
2772 	free(dinfo, M_DEVBUF);
2773 
2774 	/* increment the generation count */
2775 	pci_generation++;
2776 
2777 	/* we're losing one device */
2778 	pci_numdevs--;
2779 	return (0);
2780 }
2781 
2782 /*
2783  * PCI power manangement
2784  */
2785 int
2786 pci_set_powerstate_method(device_t dev, device_t child, int state)
2787 {
2788 	struct pci_devinfo *dinfo = device_get_ivars(child);
2789 	pcicfgregs *cfg = &dinfo->cfg;
2790 	uint16_t status;
2791 	int oldstate, highest, delay;
2792 
2793 	if (cfg->pp.pp_cap == 0)
2794 		return (EOPNOTSUPP);
2795 
2796 	/*
2797 	 * Optimize a no state change request away.  While it would be OK to
2798 	 * write to the hardware in theory, some devices have shown odd
2799 	 * behavior when going from D3 -> D3.
2800 	 */
2801 	oldstate = pci_get_powerstate(child);
2802 	if (oldstate == state)
2803 		return (0);
2804 
2805 	/*
2806 	 * The PCI power management specification states that after a state
2807 	 * transition between PCI power states, system software must
2808 	 * guarantee a minimal delay before the function accesses the device.
2809 	 * Compute the worst case delay that we need to guarantee before we
2810 	 * access the device.  Many devices will be responsive much more
2811 	 * quickly than this delay, but there are some that don't respond
2812 	 * instantly to state changes.  Transitions to/from D3 state require
2813 	 * 10ms, while D2 requires 200us, and D0/1 require none.  The delay
2814 	 * is done below with DELAY rather than a sleeper function because
2815 	 * this function can be called from contexts where we cannot sleep.
2816 	 */
2817 	highest = (oldstate > state) ? oldstate : state;
2818 	if (highest == PCI_POWERSTATE_D3)
2819 	    delay = 10000;
2820 	else if (highest == PCI_POWERSTATE_D2)
2821 	    delay = 200;
2822 	else
2823 	    delay = 0;
2824 	status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2)
2825 	    & ~PCIM_PSTAT_DMASK;
2826 	switch (state) {
2827 	case PCI_POWERSTATE_D0:
2828 		status |= PCIM_PSTAT_D0;
2829 		break;
2830 	case PCI_POWERSTATE_D1:
2831 		if ((cfg->pp.pp_cap & PCIM_PCAP_D1SUPP) == 0)
2832 			return (EOPNOTSUPP);
2833 		status |= PCIM_PSTAT_D1;
2834 		break;
2835 	case PCI_POWERSTATE_D2:
2836 		if ((cfg->pp.pp_cap & PCIM_PCAP_D2SUPP) == 0)
2837 			return (EOPNOTSUPP);
2838 		status |= PCIM_PSTAT_D2;
2839 		break;
2840 	case PCI_POWERSTATE_D3:
2841 		status |= PCIM_PSTAT_D3;
2842 		break;
2843 	default:
2844 		return (EINVAL);
2845 	}
2846 
2847 	if (bootverbose)
2848 		pci_printf(cfg, "Transition from D%d to D%d\n", oldstate,
2849 		    state);
2850 
2851 	PCI_WRITE_CONFIG(dev, child, cfg->pp.pp_status, status, 2);
2852 	if (delay)
2853 		DELAY(delay);
2854 	return (0);
2855 }
2856 
2857 int
2858 pci_get_powerstate_method(device_t dev, device_t child)
2859 {
2860 	struct pci_devinfo *dinfo = device_get_ivars(child);
2861 	pcicfgregs *cfg = &dinfo->cfg;
2862 	uint16_t status;
2863 	int result;
2864 
2865 	if (cfg->pp.pp_cap != 0) {
2866 		status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2);
2867 		switch (status & PCIM_PSTAT_DMASK) {
2868 		case PCIM_PSTAT_D0:
2869 			result = PCI_POWERSTATE_D0;
2870 			break;
2871 		case PCIM_PSTAT_D1:
2872 			result = PCI_POWERSTATE_D1;
2873 			break;
2874 		case PCIM_PSTAT_D2:
2875 			result = PCI_POWERSTATE_D2;
2876 			break;
2877 		case PCIM_PSTAT_D3:
2878 			result = PCI_POWERSTATE_D3;
2879 			break;
2880 		default:
2881 			result = PCI_POWERSTATE_UNKNOWN;
2882 			break;
2883 		}
2884 	} else {
2885 		/* No support, device is always at D0 */
2886 		result = PCI_POWERSTATE_D0;
2887 	}
2888 	return (result);
2889 }
2890 
2891 /*
2892  * Some convenience functions for PCI device drivers.
2893  */
2894 
2895 static __inline void
2896 pci_set_command_bit(device_t dev, device_t child, uint16_t bit)
2897 {
2898 	uint16_t	command;
2899 
2900 	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
2901 	command |= bit;
2902 	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
2903 }
2904 
2905 static __inline void
2906 pci_clear_command_bit(device_t dev, device_t child, uint16_t bit)
2907 {
2908 	uint16_t	command;
2909 
2910 	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
2911 	command &= ~bit;
2912 	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
2913 }
2914 
2915 int
2916 pci_enable_busmaster_method(device_t dev, device_t child)
2917 {
2918 	pci_set_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
2919 	return (0);
2920 }
2921 
2922 int
2923 pci_disable_busmaster_method(device_t dev, device_t child)
2924 {
2925 	pci_clear_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
2926 	return (0);
2927 }
2928 
2929 int
2930 pci_enable_io_method(device_t dev, device_t child, int space)
2931 {
2932 	uint16_t bit;
2933 
2934 	switch(space) {
2935 	case SYS_RES_IOPORT:
2936 		bit = PCIM_CMD_PORTEN;
2937 		break;
2938 	case SYS_RES_MEMORY:
2939 		bit = PCIM_CMD_MEMEN;
2940 		break;
2941 	default:
2942 		return (EINVAL);
2943 	}
2944 	pci_set_command_bit(dev, child, bit);
2945 	return (0);
2946 }
2947 
2948 int
2949 pci_disable_io_method(device_t dev, device_t child, int space)
2950 {
2951 	uint16_t bit;
2952 
2953 	switch(space) {
2954 	case SYS_RES_IOPORT:
2955 		bit = PCIM_CMD_PORTEN;
2956 		break;
2957 	case SYS_RES_MEMORY:
2958 		bit = PCIM_CMD_MEMEN;
2959 		break;
2960 	default:
2961 		return (EINVAL);
2962 	}
2963 	pci_clear_command_bit(dev, child, bit);
2964 	return (0);
2965 }
2966 
2967 /*
2968  * New style pci driver.  Parent device is either a pci-host-bridge or a
2969  * pci-pci-bridge.  Both kinds are represented by instances of pcib.
2970  */
2971 
2972 void
2973 pci_print_verbose(struct pci_devinfo *dinfo)
2974 {
2975 
2976 	if (bootverbose) {
2977 		pcicfgregs *cfg = &dinfo->cfg;
2978 
2979 		printf("found->\tvendor=0x%04x, dev=0x%04x, revid=0x%02x\n",
2980 		    cfg->vendor, cfg->device, cfg->revid);
2981 		printf("\tdomain=%d, bus=%d, slot=%d, func=%d\n",
2982 		    cfg->domain, cfg->bus, cfg->slot, cfg->func);
2983 		printf("\tclass=%02x-%02x-%02x, hdrtype=0x%02x, mfdev=%d\n",
2984 		    cfg->baseclass, cfg->subclass, cfg->progif, cfg->hdrtype,
2985 		    cfg->mfdev);
2986 		printf("\tcmdreg=0x%04x, statreg=0x%04x, cachelnsz=%d (dwords)\n",
2987 		    cfg->cmdreg, cfg->statreg, cfg->cachelnsz);
2988 		printf("\tlattimer=0x%02x (%d ns), mingnt=0x%02x (%d ns), maxlat=0x%02x (%d ns)\n",
2989 		    cfg->lattimer, cfg->lattimer * 30, cfg->mingnt,
2990 		    cfg->mingnt * 250, cfg->maxlat, cfg->maxlat * 250);
2991 		if (cfg->intpin > 0)
2992 			printf("\tintpin=%c, irq=%d\n",
2993 			    cfg->intpin +'a' -1, cfg->intline);
2994 		if (cfg->pp.pp_cap) {
2995 			uint16_t status;
2996 
2997 			status = pci_read_config(cfg->dev, cfg->pp.pp_status, 2);
2998 			printf("\tpowerspec %d  supports D0%s%s D3  current D%d\n",
2999 			    cfg->pp.pp_cap & PCIM_PCAP_SPEC,
3000 			    cfg->pp.pp_cap & PCIM_PCAP_D1SUPP ? " D1" : "",
3001 			    cfg->pp.pp_cap & PCIM_PCAP_D2SUPP ? " D2" : "",
3002 			    status & PCIM_PSTAT_DMASK);
3003 		}
3004 		if (cfg->msi.msi_location) {
3005 			int ctrl;
3006 
3007 			ctrl = cfg->msi.msi_ctrl;
3008 			printf("\tMSI supports %d message%s%s%s\n",
3009 			    cfg->msi.msi_msgnum,
3010 			    (cfg->msi.msi_msgnum == 1) ? "" : "s",
3011 			    (ctrl & PCIM_MSICTRL_64BIT) ? ", 64 bit" : "",
3012 			    (ctrl & PCIM_MSICTRL_VECTOR) ? ", vector masks":"");
3013 		}
3014 		if (cfg->msix.msix_location) {
3015 			printf("\tMSI-X supports %d message%s ",
3016 			    cfg->msix.msix_msgnum,
3017 			    (cfg->msix.msix_msgnum == 1) ? "" : "s");
3018 			if (cfg->msix.msix_table_bar == cfg->msix.msix_pba_bar)
3019 				printf("in map 0x%x\n",
3020 				    cfg->msix.msix_table_bar);
3021 			else
3022 				printf("in maps 0x%x and 0x%x\n",
3023 				    cfg->msix.msix_table_bar,
3024 				    cfg->msix.msix_pba_bar);
3025 		}
3026 	}
3027 }
3028 
3029 static int
3030 pci_porten(device_t dev)
3031 {
3032 	return (pci_read_config(dev, PCIR_COMMAND, 2) & PCIM_CMD_PORTEN) != 0;
3033 }
3034 
3035 static int
3036 pci_memen(device_t dev)
3037 {
3038 	return (pci_read_config(dev, PCIR_COMMAND, 2) & PCIM_CMD_MEMEN) != 0;
3039 }
3040 
3041 void
3042 pci_read_bar(device_t dev, int reg, pci_addr_t *mapp, pci_addr_t *testvalp,
3043     int *bar64)
3044 {
3045 	struct pci_devinfo *dinfo;
3046 	pci_addr_t map, testval;
3047 	int ln2range;
3048 	uint16_t cmd;
3049 
3050 	/*
3051 	 * The device ROM BAR is special.  It is always a 32-bit
3052 	 * memory BAR.  Bit 0 is special and should not be set when
3053 	 * sizing the BAR.
3054 	 */
3055 	dinfo = device_get_ivars(dev);
3056 	if (PCIR_IS_BIOS(&dinfo->cfg, reg)) {
3057 		map = pci_read_config(dev, reg, 4);
3058 		pci_write_config(dev, reg, 0xfffffffe, 4);
3059 		testval = pci_read_config(dev, reg, 4);
3060 		pci_write_config(dev, reg, map, 4);
3061 		*mapp = map;
3062 		*testvalp = testval;
3063 		if (bar64 != NULL)
3064 			*bar64 = 0;
3065 		return;
3066 	}
3067 
3068 	map = pci_read_config(dev, reg, 4);
3069 	ln2range = pci_maprange(map);
3070 	if (ln2range == 64)
3071 		map |= (pci_addr_t)pci_read_config(dev, reg + 4, 4) << 32;
3072 
3073 	/*
3074 	 * Disable decoding via the command register before
3075 	 * determining the BAR's length since we will be placing it in
3076 	 * a weird state.
3077 	 */
3078 	cmd = pci_read_config(dev, PCIR_COMMAND, 2);
3079 	pci_write_config(dev, PCIR_COMMAND,
3080 	    cmd & ~(PCI_BAR_MEM(map) ? PCIM_CMD_MEMEN : PCIM_CMD_PORTEN), 2);
3081 
3082 	/*
3083 	 * Determine the BAR's length by writing all 1's.  The bottom
3084 	 * log_2(size) bits of the BAR will stick as 0 when we read
3085 	 * the value back.
3086 	 *
3087 	 * NB: according to the PCI Local Bus Specification, rev. 3.0:
3088 	 * "Software writes 0FFFFFFFFh to both registers, reads them back,
3089 	 * and combines the result into a 64-bit value." (section 6.2.5.1)
3090 	 *
3091 	 * Writes to both registers must be performed before attempting to
3092 	 * read back the size value.
3093 	 */
3094 	testval = 0;
3095 	pci_write_config(dev, reg, 0xffffffff, 4);
3096 	if (ln2range == 64) {
3097 		pci_write_config(dev, reg + 4, 0xffffffff, 4);
3098 		testval |= (pci_addr_t)pci_read_config(dev, reg + 4, 4) << 32;
3099 	}
3100 	testval |= pci_read_config(dev, reg, 4);
3101 
3102 	/*
3103 	 * Restore the original value of the BAR.  We may have reprogrammed
3104 	 * the BAR of the low-level console device and when booting verbose,
3105 	 * we need the console device addressable.
3106 	 */
3107 	pci_write_config(dev, reg, map, 4);
3108 	if (ln2range == 64)
3109 		pci_write_config(dev, reg + 4, map >> 32, 4);
3110 	pci_write_config(dev, PCIR_COMMAND, cmd, 2);
3111 
3112 	*mapp = map;
3113 	*testvalp = testval;
3114 	if (bar64 != NULL)
3115 		*bar64 = (ln2range == 64);
3116 }
3117 
3118 static void
3119 pci_write_bar(device_t dev, struct pci_map *pm, pci_addr_t base)
3120 {
3121 	struct pci_devinfo *dinfo;
3122 	int ln2range;
3123 
3124 	/* The device ROM BAR is always a 32-bit memory BAR. */
3125 	dinfo = device_get_ivars(dev);
3126 	if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg))
3127 		ln2range = 32;
3128 	else
3129 		ln2range = pci_maprange(pm->pm_value);
3130 	pci_write_config(dev, pm->pm_reg, base, 4);
3131 	if (ln2range == 64)
3132 		pci_write_config(dev, pm->pm_reg + 4, base >> 32, 4);
3133 	pm->pm_value = pci_read_config(dev, pm->pm_reg, 4);
3134 	if (ln2range == 64)
3135 		pm->pm_value |= (pci_addr_t)pci_read_config(dev,
3136 		    pm->pm_reg + 4, 4) << 32;
3137 }
3138 
3139 struct pci_map *
3140 pci_find_bar(device_t dev, int reg)
3141 {
3142 	struct pci_devinfo *dinfo;
3143 	struct pci_map *pm;
3144 
3145 	dinfo = device_get_ivars(dev);
3146 	STAILQ_FOREACH(pm, &dinfo->cfg.maps, pm_link) {
3147 		if (pm->pm_reg == reg)
3148 			return (pm);
3149 	}
3150 	return (NULL);
3151 }
3152 
3153 struct pci_map *
3154 pci_first_bar(device_t dev)
3155 {
3156 	struct pci_devinfo *dinfo;
3157 
3158 	dinfo = device_get_ivars(dev);
3159 	return (STAILQ_FIRST(&dinfo->cfg.maps));
3160 }
3161 
3162 struct pci_map *
3163 pci_next_bar(struct pci_map *pm)
3164 {
3165 	return (STAILQ_NEXT(pm, pm_link));
3166 }
3167 
3168 int
3169 pci_bar_enabled(device_t dev, struct pci_map *pm)
3170 {
3171 	struct pci_devinfo *dinfo;
3172 	uint16_t cmd;
3173 
3174 	dinfo = device_get_ivars(dev);
3175 	if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg) &&
3176 	    !(pm->pm_value & PCIM_BIOS_ENABLE))
3177 		return (0);
3178 #ifdef PCI_IOV
3179 	if ((dinfo->cfg.flags & PCICFG_VF) != 0) {
3180 		struct pcicfg_iov *iov;
3181 
3182 		iov = dinfo->cfg.iov;
3183 		cmd = pci_read_config(iov->iov_pf,
3184 		    iov->iov_pos + PCIR_SRIOV_CTL, 2);
3185 		return ((cmd & PCIM_SRIOV_VF_MSE) != 0);
3186 	}
3187 #endif
3188 	cmd = pci_read_config(dev, PCIR_COMMAND, 2);
3189 	if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg) || PCI_BAR_MEM(pm->pm_value))
3190 		return ((cmd & PCIM_CMD_MEMEN) != 0);
3191 	else
3192 		return ((cmd & PCIM_CMD_PORTEN) != 0);
3193 }
3194 
3195 struct pci_map *
3196 pci_add_bar(device_t dev, int reg, pci_addr_t value, pci_addr_t size)
3197 {
3198 	struct pci_devinfo *dinfo;
3199 	struct pci_map *pm, *prev;
3200 
3201 	dinfo = device_get_ivars(dev);
3202 	pm = malloc(sizeof(*pm), M_DEVBUF, M_WAITOK | M_ZERO);
3203 	pm->pm_reg = reg;
3204 	pm->pm_value = value;
3205 	pm->pm_size = size;
3206 	STAILQ_FOREACH(prev, &dinfo->cfg.maps, pm_link) {
3207 		KASSERT(prev->pm_reg != pm->pm_reg, ("duplicate map %02x",
3208 		    reg));
3209 		if (STAILQ_NEXT(prev, pm_link) == NULL ||
3210 		    STAILQ_NEXT(prev, pm_link)->pm_reg > pm->pm_reg)
3211 			break;
3212 	}
3213 	if (prev != NULL)
3214 		STAILQ_INSERT_AFTER(&dinfo->cfg.maps, prev, pm, pm_link);
3215 	else
3216 		STAILQ_INSERT_TAIL(&dinfo->cfg.maps, pm, pm_link);
3217 	return (pm);
3218 }
3219 
3220 static void
3221 pci_restore_bars(device_t dev)
3222 {
3223 	struct pci_devinfo *dinfo;
3224 	struct pci_map *pm;
3225 	int ln2range;
3226 
3227 	dinfo = device_get_ivars(dev);
3228 	STAILQ_FOREACH(pm, &dinfo->cfg.maps, pm_link) {
3229 		if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg))
3230 			ln2range = 32;
3231 		else
3232 			ln2range = pci_maprange(pm->pm_value);
3233 		pci_write_config(dev, pm->pm_reg, pm->pm_value, 4);
3234 		if (ln2range == 64)
3235 			pci_write_config(dev, pm->pm_reg + 4,
3236 			    pm->pm_value >> 32, 4);
3237 	}
3238 }
3239 
3240 /*
3241  * Add a resource based on a pci map register. Return 1 if the map
3242  * register is a 32bit map register or 2 if it is a 64bit register.
3243  */
3244 static int
3245 pci_add_map(device_t bus, device_t dev, int reg, struct resource_list *rl,
3246     int force, int prefetch)
3247 {
3248 	struct pci_map *pm;
3249 	pci_addr_t base, map, testval;
3250 	pci_addr_t start, end, count;
3251 	int barlen, basezero, flags, maprange, mapsize, type;
3252 	uint16_t cmd;
3253 	struct resource *res;
3254 
3255 	/*
3256 	 * The BAR may already exist if the device is a CardBus card
3257 	 * whose CIS is stored in this BAR.
3258 	 */
3259 	pm = pci_find_bar(dev, reg);
3260 	if (pm != NULL) {
3261 		maprange = pci_maprange(pm->pm_value);
3262 		barlen = maprange == 64 ? 2 : 1;
3263 		return (barlen);
3264 	}
3265 
3266 	pci_read_bar(dev, reg, &map, &testval, NULL);
3267 	if (PCI_BAR_MEM(map)) {
3268 		type = SYS_RES_MEMORY;
3269 		if (map & PCIM_BAR_MEM_PREFETCH)
3270 			prefetch = 1;
3271 	} else
3272 		type = SYS_RES_IOPORT;
3273 	mapsize = pci_mapsize(testval);
3274 	base = pci_mapbase(map);
3275 #ifdef __PCI_BAR_ZERO_VALID
3276 	basezero = 0;
3277 #else
3278 	basezero = base == 0;
3279 #endif
3280 	maprange = pci_maprange(map);
3281 	barlen = maprange == 64 ? 2 : 1;
3282 
3283 	/*
3284 	 * For I/O registers, if bottom bit is set, and the next bit up
3285 	 * isn't clear, we know we have a BAR that doesn't conform to the
3286 	 * spec, so ignore it.  Also, sanity check the size of the data
3287 	 * areas to the type of memory involved.  Memory must be at least
3288 	 * 16 bytes in size, while I/O ranges must be at least 4.
3289 	 */
3290 	if (PCI_BAR_IO(testval) && (testval & PCIM_BAR_IO_RESERVED) != 0)
3291 		return (barlen);
3292 	if ((type == SYS_RES_MEMORY && mapsize < 4) ||
3293 	    (type == SYS_RES_IOPORT && mapsize < 2))
3294 		return (barlen);
3295 
3296 	/* Save a record of this BAR. */
3297 	pm = pci_add_bar(dev, reg, map, mapsize);
3298 	if (bootverbose) {
3299 		printf("\tmap[%02x]: type %s, range %2d, base %#jx, size %2d",
3300 		    reg, pci_maptype(map), maprange, (uintmax_t)base, mapsize);
3301 		if (type == SYS_RES_IOPORT && !pci_porten(dev))
3302 			printf(", port disabled\n");
3303 		else if (type == SYS_RES_MEMORY && !pci_memen(dev))
3304 			printf(", memory disabled\n");
3305 		else
3306 			printf(", enabled\n");
3307 	}
3308 
3309 	/*
3310 	 * If base is 0, then we have problems if this architecture does
3311 	 * not allow that.  It is best to ignore such entries for the
3312 	 * moment.  These will be allocated later if the driver specifically
3313 	 * requests them.  However, some removable buses look better when
3314 	 * all resources are allocated, so allow '0' to be overridden.
3315 	 *
3316 	 * Similarly treat maps whose values is the same as the test value
3317 	 * read back.  These maps have had all f's written to them by the
3318 	 * BIOS in an attempt to disable the resources.
3319 	 */
3320 	if (!force && (basezero || map == testval))
3321 		return (barlen);
3322 	if ((u_long)base != base) {
3323 		device_printf(bus,
3324 		    "pci%d:%d:%d:%d bar %#x too many address bits",
3325 		    pci_get_domain(dev), pci_get_bus(dev), pci_get_slot(dev),
3326 		    pci_get_function(dev), reg);
3327 		return (barlen);
3328 	}
3329 
3330 	/*
3331 	 * This code theoretically does the right thing, but has
3332 	 * undesirable side effects in some cases where peripherals
3333 	 * respond oddly to having these bits enabled.  Let the user
3334 	 * be able to turn them off (since pci_enable_io_modes is 1 by
3335 	 * default).
3336 	 */
3337 	if (pci_enable_io_modes) {
3338 		/* Turn on resources that have been left off by a lazy BIOS */
3339 		if (type == SYS_RES_IOPORT && !pci_porten(dev)) {
3340 			cmd = pci_read_config(dev, PCIR_COMMAND, 2);
3341 			cmd |= PCIM_CMD_PORTEN;
3342 			pci_write_config(dev, PCIR_COMMAND, cmd, 2);
3343 		}
3344 		if (type == SYS_RES_MEMORY && !pci_memen(dev)) {
3345 			cmd = pci_read_config(dev, PCIR_COMMAND, 2);
3346 			cmd |= PCIM_CMD_MEMEN;
3347 			pci_write_config(dev, PCIR_COMMAND, cmd, 2);
3348 		}
3349 	} else {
3350 		if (type == SYS_RES_IOPORT && !pci_porten(dev))
3351 			return (barlen);
3352 		if (type == SYS_RES_MEMORY && !pci_memen(dev))
3353 			return (barlen);
3354 	}
3355 
3356 	count = (pci_addr_t)1 << mapsize;
3357 	flags = RF_ALIGNMENT_LOG2(mapsize);
3358 	if (prefetch)
3359 		flags |= RF_PREFETCHABLE;
3360 	if (basezero || base == pci_mapbase(testval) || pci_clear_bars) {
3361 		start = 0;	/* Let the parent decide. */
3362 		end = ~0;
3363 	} else {
3364 		start = base;
3365 		end = base + count - 1;
3366 	}
3367 	resource_list_add(rl, type, reg, start, end, count);
3368 
3369 	/*
3370 	 * Try to allocate the resource for this BAR from our parent
3371 	 * so that this resource range is already reserved.  The
3372 	 * driver for this device will later inherit this resource in
3373 	 * pci_alloc_resource().
3374 	 */
3375 	res = resource_list_reserve(rl, bus, dev, type, &reg, start, end, count,
3376 	    flags);
3377 	if ((pci_do_realloc_bars
3378 		|| pci_has_quirk(pci_get_devid(dev), PCI_QUIRK_REALLOC_BAR))
3379 	    && res == NULL && (start != 0 || end != ~0)) {
3380 		/*
3381 		 * If the allocation fails, try to allocate a resource for
3382 		 * this BAR using any available range.  The firmware felt
3383 		 * it was important enough to assign a resource, so don't
3384 		 * disable decoding if we can help it.
3385 		 */
3386 		resource_list_delete(rl, type, reg);
3387 		resource_list_add(rl, type, reg, 0, ~0, count);
3388 		res = resource_list_reserve(rl, bus, dev, type, &reg, 0, ~0,
3389 		    count, flags);
3390 	}
3391 	if (res == NULL) {
3392 		/*
3393 		 * If the allocation fails, delete the resource list entry
3394 		 * and disable decoding for this device.
3395 		 *
3396 		 * If the driver requests this resource in the future,
3397 		 * pci_reserve_map() will try to allocate a fresh
3398 		 * resource range.
3399 		 */
3400 		resource_list_delete(rl, type, reg);
3401 		pci_disable_io(dev, type);
3402 		if (bootverbose)
3403 			device_printf(bus,
3404 			    "pci%d:%d:%d:%d bar %#x failed to allocate\n",
3405 			    pci_get_domain(dev), pci_get_bus(dev),
3406 			    pci_get_slot(dev), pci_get_function(dev), reg);
3407 	} else {
3408 		start = rman_get_start(res);
3409 		pci_write_bar(dev, pm, start);
3410 	}
3411 	return (barlen);
3412 }
3413 
3414 /*
3415  * For ATA devices we need to decide early what addressing mode to use.
3416  * Legacy demands that the primary and secondary ATA ports sits on the
3417  * same addresses that old ISA hardware did. This dictates that we use
3418  * those addresses and ignore the BAR's if we cannot set PCI native
3419  * addressing mode.
3420  */
3421 static void
3422 pci_ata_maps(device_t bus, device_t dev, struct resource_list *rl, int force,
3423     uint32_t prefetchmask)
3424 {
3425 	int rid, type, progif;
3426 #if 0
3427 	/* if this device supports PCI native addressing use it */
3428 	progif = pci_read_config(dev, PCIR_PROGIF, 1);
3429 	if ((progif & 0x8a) == 0x8a) {
3430 		if (pci_mapbase(pci_read_config(dev, PCIR_BAR(0), 4)) &&
3431 		    pci_mapbase(pci_read_config(dev, PCIR_BAR(2), 4))) {
3432 			printf("Trying ATA native PCI addressing mode\n");
3433 			pci_write_config(dev, PCIR_PROGIF, progif | 0x05, 1);
3434 		}
3435 	}
3436 #endif
3437 	progif = pci_read_config(dev, PCIR_PROGIF, 1);
3438 	type = SYS_RES_IOPORT;
3439 	if (progif & PCIP_STORAGE_IDE_MODEPRIM) {
3440 		pci_add_map(bus, dev, PCIR_BAR(0), rl, force,
3441 		    prefetchmask & (1 << 0));
3442 		pci_add_map(bus, dev, PCIR_BAR(1), rl, force,
3443 		    prefetchmask & (1 << 1));
3444 	} else {
3445 		rid = PCIR_BAR(0);
3446 		resource_list_add(rl, type, rid, 0x1f0, 0x1f7, 8);
3447 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x1f0,
3448 		    0x1f7, 8, 0);
3449 		rid = PCIR_BAR(1);
3450 		resource_list_add(rl, type, rid, 0x3f6, 0x3f6, 1);
3451 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x3f6,
3452 		    0x3f6, 1, 0);
3453 	}
3454 	if (progif & PCIP_STORAGE_IDE_MODESEC) {
3455 		pci_add_map(bus, dev, PCIR_BAR(2), rl, force,
3456 		    prefetchmask & (1 << 2));
3457 		pci_add_map(bus, dev, PCIR_BAR(3), rl, force,
3458 		    prefetchmask & (1 << 3));
3459 	} else {
3460 		rid = PCIR_BAR(2);
3461 		resource_list_add(rl, type, rid, 0x170, 0x177, 8);
3462 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x170,
3463 		    0x177, 8, 0);
3464 		rid = PCIR_BAR(3);
3465 		resource_list_add(rl, type, rid, 0x376, 0x376, 1);
3466 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x376,
3467 		    0x376, 1, 0);
3468 	}
3469 	pci_add_map(bus, dev, PCIR_BAR(4), rl, force,
3470 	    prefetchmask & (1 << 4));
3471 	pci_add_map(bus, dev, PCIR_BAR(5), rl, force,
3472 	    prefetchmask & (1 << 5));
3473 }
3474 
3475 static void
3476 pci_assign_interrupt(device_t bus, device_t dev, int force_route)
3477 {
3478 	struct pci_devinfo *dinfo = device_get_ivars(dev);
3479 	pcicfgregs *cfg = &dinfo->cfg;
3480 	char tunable_name[64];
3481 	int irq;
3482 
3483 	/* Has to have an intpin to have an interrupt. */
3484 	if (cfg->intpin == 0)
3485 		return;
3486 
3487 	/* Let the user override the IRQ with a tunable. */
3488 	irq = PCI_INVALID_IRQ;
3489 	snprintf(tunable_name, sizeof(tunable_name),
3490 	    "hw.pci%d.%d.%d.INT%c.irq",
3491 	    cfg->domain, cfg->bus, cfg->slot, cfg->intpin + 'A' - 1);
3492 	if (TUNABLE_INT_FETCH(tunable_name, &irq) && (irq >= 255 || irq <= 0))
3493 		irq = PCI_INVALID_IRQ;
3494 
3495 	/*
3496 	 * If we didn't get an IRQ via the tunable, then we either use the
3497 	 * IRQ value in the intline register or we ask the bus to route an
3498 	 * interrupt for us.  If force_route is true, then we only use the
3499 	 * value in the intline register if the bus was unable to assign an
3500 	 * IRQ.
3501 	 */
3502 	if (!PCI_INTERRUPT_VALID(irq)) {
3503 		if (!PCI_INTERRUPT_VALID(cfg->intline) || force_route)
3504 			irq = PCI_ASSIGN_INTERRUPT(bus, dev);
3505 		if (!PCI_INTERRUPT_VALID(irq))
3506 			irq = cfg->intline;
3507 	}
3508 
3509 	/* If after all that we don't have an IRQ, just bail. */
3510 	if (!PCI_INTERRUPT_VALID(irq))
3511 		return;
3512 
3513 	/* Update the config register if it changed. */
3514 	if (irq != cfg->intline) {
3515 		cfg->intline = irq;
3516 		pci_write_config(dev, PCIR_INTLINE, irq, 1);
3517 	}
3518 
3519 	/* Add this IRQ as rid 0 interrupt resource. */
3520 	resource_list_add(&dinfo->resources, SYS_RES_IRQ, 0, irq, irq, 1);
3521 }
3522 
3523 /* Perform early OHCI takeover from SMM. */
3524 static void
3525 ohci_early_takeover(device_t self)
3526 {
3527 	struct resource *res;
3528 	uint32_t ctl;
3529 	int rid;
3530 	int i;
3531 
3532 	rid = PCIR_BAR(0);
3533 	res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3534 	if (res == NULL)
3535 		return;
3536 
3537 	ctl = bus_read_4(res, OHCI_CONTROL);
3538 	if (ctl & OHCI_IR) {
3539 		if (bootverbose)
3540 			printf("ohci early: "
3541 			    "SMM active, request owner change\n");
3542 		bus_write_4(res, OHCI_COMMAND_STATUS, OHCI_OCR);
3543 		for (i = 0; (i < 100) && (ctl & OHCI_IR); i++) {
3544 			DELAY(1000);
3545 			ctl = bus_read_4(res, OHCI_CONTROL);
3546 		}
3547 		if (ctl & OHCI_IR) {
3548 			if (bootverbose)
3549 				printf("ohci early: "
3550 				    "SMM does not respond, resetting\n");
3551 			bus_write_4(res, OHCI_CONTROL, OHCI_HCFS_RESET);
3552 		}
3553 		/* Disable interrupts */
3554 		bus_write_4(res, OHCI_INTERRUPT_DISABLE, OHCI_ALL_INTRS);
3555 	}
3556 
3557 	bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3558 }
3559 
3560 /* Perform early UHCI takeover from SMM. */
3561 static void
3562 uhci_early_takeover(device_t self)
3563 {
3564 	struct resource *res;
3565 	int rid;
3566 
3567 	/*
3568 	 * Set the PIRQD enable bit and switch off all the others. We don't
3569 	 * want legacy support to interfere with us XXX Does this also mean
3570 	 * that the BIOS won't touch the keyboard anymore if it is connected
3571 	 * to the ports of the root hub?
3572 	 */
3573 	pci_write_config(self, PCI_LEGSUP, PCI_LEGSUP_USBPIRQDEN, 2);
3574 
3575 	/* Disable interrupts */
3576 	rid = PCI_UHCI_BASE_REG;
3577 	res = bus_alloc_resource_any(self, SYS_RES_IOPORT, &rid, RF_ACTIVE);
3578 	if (res != NULL) {
3579 		bus_write_2(res, UHCI_INTR, 0);
3580 		bus_release_resource(self, SYS_RES_IOPORT, rid, res);
3581 	}
3582 }
3583 
3584 /* Perform early EHCI takeover from SMM. */
3585 static void
3586 ehci_early_takeover(device_t self)
3587 {
3588 	struct resource *res;
3589 	uint32_t cparams;
3590 	uint32_t eec;
3591 	uint8_t eecp;
3592 	uint8_t bios_sem;
3593 	uint8_t offs;
3594 	int rid;
3595 	int i;
3596 
3597 	rid = PCIR_BAR(0);
3598 	res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3599 	if (res == NULL)
3600 		return;
3601 
3602 	cparams = bus_read_4(res, EHCI_HCCPARAMS);
3603 
3604 	/* Synchronise with the BIOS if it owns the controller. */
3605 	for (eecp = EHCI_HCC_EECP(cparams); eecp != 0;
3606 	    eecp = EHCI_EECP_NEXT(eec)) {
3607 		eec = pci_read_config(self, eecp, 4);
3608 		if (EHCI_EECP_ID(eec) != EHCI_EC_LEGSUP) {
3609 			continue;
3610 		}
3611 		bios_sem = pci_read_config(self, eecp +
3612 		    EHCI_LEGSUP_BIOS_SEM, 1);
3613 		if (bios_sem == 0) {
3614 			continue;
3615 		}
3616 		if (bootverbose)
3617 			printf("ehci early: "
3618 			    "SMM active, request owner change\n");
3619 
3620 		pci_write_config(self, eecp + EHCI_LEGSUP_OS_SEM, 1, 1);
3621 
3622 		for (i = 0; (i < 100) && (bios_sem != 0); i++) {
3623 			DELAY(1000);
3624 			bios_sem = pci_read_config(self, eecp +
3625 			    EHCI_LEGSUP_BIOS_SEM, 1);
3626 		}
3627 
3628 		if (bios_sem != 0) {
3629 			if (bootverbose)
3630 				printf("ehci early: "
3631 				    "SMM does not respond\n");
3632 		}
3633 		/* Disable interrupts */
3634 		offs = EHCI_CAPLENGTH(bus_read_4(res, EHCI_CAPLEN_HCIVERSION));
3635 		bus_write_4(res, offs + EHCI_USBINTR, 0);
3636 	}
3637 	bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3638 }
3639 
3640 /* Perform early XHCI takeover from SMM. */
3641 static void
3642 xhci_early_takeover(device_t self)
3643 {
3644 	struct resource *res;
3645 	uint32_t cparams;
3646 	uint32_t eec;
3647 	uint8_t eecp;
3648 	uint8_t bios_sem;
3649 	uint8_t offs;
3650 	int rid;
3651 	int i;
3652 
3653 	rid = PCIR_BAR(0);
3654 	res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3655 	if (res == NULL)
3656 		return;
3657 
3658 	cparams = bus_read_4(res, XHCI_HCSPARAMS0);
3659 
3660 	eec = -1;
3661 
3662 	/* Synchronise with the BIOS if it owns the controller. */
3663 	for (eecp = XHCI_HCS0_XECP(cparams) << 2; eecp != 0 && XHCI_XECP_NEXT(eec);
3664 	    eecp += XHCI_XECP_NEXT(eec) << 2) {
3665 		eec = bus_read_4(res, eecp);
3666 
3667 		if (XHCI_XECP_ID(eec) != XHCI_ID_USB_LEGACY)
3668 			continue;
3669 
3670 		bios_sem = bus_read_1(res, eecp + XHCI_XECP_BIOS_SEM);
3671 		if (bios_sem == 0)
3672 			continue;
3673 
3674 		if (bootverbose)
3675 			printf("xhci early: "
3676 			    "SMM active, request owner change\n");
3677 
3678 		bus_write_1(res, eecp + XHCI_XECP_OS_SEM, 1);
3679 
3680 		/* wait a maximum of 5 second */
3681 
3682 		for (i = 0; (i < 5000) && (bios_sem != 0); i++) {
3683 			DELAY(1000);
3684 			bios_sem = bus_read_1(res, eecp +
3685 			    XHCI_XECP_BIOS_SEM);
3686 		}
3687 
3688 		if (bios_sem != 0) {
3689 			if (bootverbose)
3690 				printf("xhci early: "
3691 				    "SMM does not respond\n");
3692 		}
3693 
3694 		/* Disable interrupts */
3695 		offs = bus_read_1(res, XHCI_CAPLENGTH);
3696 		bus_write_4(res, offs + XHCI_USBCMD, 0);
3697 		bus_read_4(res, offs + XHCI_USBSTS);
3698 	}
3699 	bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3700 }
3701 
3702 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
3703 static void
3704 pci_reserve_secbus(device_t bus, device_t dev, pcicfgregs *cfg,
3705     struct resource_list *rl)
3706 {
3707 	struct resource *res;
3708 	char *cp;
3709 	rman_res_t start, end, count;
3710 	int rid, sec_bus, sec_reg, sub_bus, sub_reg, sup_bus;
3711 
3712 	switch (cfg->hdrtype & PCIM_HDRTYPE) {
3713 	case PCIM_HDRTYPE_BRIDGE:
3714 		sec_reg = PCIR_SECBUS_1;
3715 		sub_reg = PCIR_SUBBUS_1;
3716 		break;
3717 	case PCIM_HDRTYPE_CARDBUS:
3718 		sec_reg = PCIR_SECBUS_2;
3719 		sub_reg = PCIR_SUBBUS_2;
3720 		break;
3721 	default:
3722 		return;
3723 	}
3724 
3725 	/*
3726 	 * If the existing bus range is valid, attempt to reserve it
3727 	 * from our parent.  If this fails for any reason, clear the
3728 	 * secbus and subbus registers.
3729 	 *
3730 	 * XXX: Should we reset sub_bus to sec_bus if it is < sec_bus?
3731 	 * This would at least preserve the existing sec_bus if it is
3732 	 * valid.
3733 	 */
3734 	sec_bus = PCI_READ_CONFIG(bus, dev, sec_reg, 1);
3735 	sub_bus = PCI_READ_CONFIG(bus, dev, sub_reg, 1);
3736 
3737 	/* Quirk handling. */
3738 	switch (pci_get_devid(dev)) {
3739 	case 0x12258086:		/* Intel 82454KX/GX (Orion) */
3740 		sup_bus = pci_read_config(dev, 0x41, 1);
3741 		if (sup_bus != 0xff) {
3742 			sec_bus = sup_bus + 1;
3743 			sub_bus = sup_bus + 1;
3744 			PCI_WRITE_CONFIG(bus, dev, sec_reg, sec_bus, 1);
3745 			PCI_WRITE_CONFIG(bus, dev, sub_reg, sub_bus, 1);
3746 		}
3747 		break;
3748 
3749 	case 0x00dd10de:
3750 		/* Compaq R3000 BIOS sets wrong subordinate bus number. */
3751 		if ((cp = kern_getenv("smbios.planar.maker")) == NULL)
3752 			break;
3753 		if (strncmp(cp, "Compal", 6) != 0) {
3754 			freeenv(cp);
3755 			break;
3756 		}
3757 		freeenv(cp);
3758 		if ((cp = kern_getenv("smbios.planar.product")) == NULL)
3759 			break;
3760 		if (strncmp(cp, "08A0", 4) != 0) {
3761 			freeenv(cp);
3762 			break;
3763 		}
3764 		freeenv(cp);
3765 		if (sub_bus < 0xa) {
3766 			sub_bus = 0xa;
3767 			PCI_WRITE_CONFIG(bus, dev, sub_reg, sub_bus, 1);
3768 		}
3769 		break;
3770 	}
3771 
3772 	if (bootverbose)
3773 		printf("\tsecbus=%d, subbus=%d\n", sec_bus, sub_bus);
3774 	if (sec_bus > 0 && sub_bus >= sec_bus) {
3775 		start = sec_bus;
3776 		end = sub_bus;
3777 		count = end - start + 1;
3778 
3779 		resource_list_add(rl, PCI_RES_BUS, 0, 0, ~0, count);
3780 
3781 		/*
3782 		 * If requested, clear secondary bus registers in
3783 		 * bridge devices to force a complete renumbering
3784 		 * rather than reserving the existing range.  However,
3785 		 * preserve the existing size.
3786 		 */
3787 		if (pci_clear_buses)
3788 			goto clear;
3789 
3790 		rid = 0;
3791 		res = resource_list_reserve(rl, bus, dev, PCI_RES_BUS, &rid,
3792 		    start, end, count, 0);
3793 		if (res != NULL)
3794 			return;
3795 
3796 		if (bootverbose)
3797 			device_printf(bus,
3798 			    "pci%d:%d:%d:%d secbus failed to allocate\n",
3799 			    pci_get_domain(dev), pci_get_bus(dev),
3800 			    pci_get_slot(dev), pci_get_function(dev));
3801 	}
3802 
3803 clear:
3804 	PCI_WRITE_CONFIG(bus, dev, sec_reg, 0, 1);
3805 	PCI_WRITE_CONFIG(bus, dev, sub_reg, 0, 1);
3806 }
3807 
3808 static struct resource *
3809 pci_alloc_secbus(device_t dev, device_t child, int *rid, rman_res_t start,
3810     rman_res_t end, rman_res_t count, u_int flags)
3811 {
3812 	struct pci_devinfo *dinfo;
3813 	pcicfgregs *cfg;
3814 	struct resource_list *rl;
3815 	struct resource *res;
3816 	int sec_reg, sub_reg;
3817 
3818 	dinfo = device_get_ivars(child);
3819 	cfg = &dinfo->cfg;
3820 	rl = &dinfo->resources;
3821 	switch (cfg->hdrtype & PCIM_HDRTYPE) {
3822 	case PCIM_HDRTYPE_BRIDGE:
3823 		sec_reg = PCIR_SECBUS_1;
3824 		sub_reg = PCIR_SUBBUS_1;
3825 		break;
3826 	case PCIM_HDRTYPE_CARDBUS:
3827 		sec_reg = PCIR_SECBUS_2;
3828 		sub_reg = PCIR_SUBBUS_2;
3829 		break;
3830 	default:
3831 		return (NULL);
3832 	}
3833 
3834 	if (*rid != 0)
3835 		return (NULL);
3836 
3837 	if (resource_list_find(rl, PCI_RES_BUS, *rid) == NULL)
3838 		resource_list_add(rl, PCI_RES_BUS, *rid, start, end, count);
3839 	if (!resource_list_reserved(rl, PCI_RES_BUS, *rid)) {
3840 		res = resource_list_reserve(rl, dev, child, PCI_RES_BUS, rid,
3841 		    start, end, count, flags & ~RF_ACTIVE);
3842 		if (res == NULL) {
3843 			resource_list_delete(rl, PCI_RES_BUS, *rid);
3844 			device_printf(child, "allocating %ju bus%s failed\n",
3845 			    count, count == 1 ? "" : "es");
3846 			return (NULL);
3847 		}
3848 		if (bootverbose)
3849 			device_printf(child,
3850 			    "Lazy allocation of %ju bus%s at %ju\n", count,
3851 			    count == 1 ? "" : "es", rman_get_start(res));
3852 		PCI_WRITE_CONFIG(dev, child, sec_reg, rman_get_start(res), 1);
3853 		PCI_WRITE_CONFIG(dev, child, sub_reg, rman_get_end(res), 1);
3854 	}
3855 	return (resource_list_alloc(rl, dev, child, PCI_RES_BUS, rid, start,
3856 	    end, count, flags));
3857 }
3858 #endif
3859 
3860 static int
3861 pci_ea_bei_to_rid(device_t dev, int bei)
3862 {
3863 #ifdef PCI_IOV
3864 	struct pci_devinfo *dinfo;
3865 	int iov_pos;
3866 	struct pcicfg_iov *iov;
3867 
3868 	dinfo = device_get_ivars(dev);
3869 	iov = dinfo->cfg.iov;
3870 	if (iov != NULL)
3871 		iov_pos = iov->iov_pos;
3872 	else
3873 		iov_pos = 0;
3874 #endif
3875 
3876 	/* Check if matches BAR */
3877 	if ((bei >= PCIM_EA_BEI_BAR_0) &&
3878 	    (bei <= PCIM_EA_BEI_BAR_5))
3879 		return (PCIR_BAR(bei));
3880 
3881 	/* Check ROM */
3882 	if (bei == PCIM_EA_BEI_ROM)
3883 		return (PCIR_BIOS);
3884 
3885 #ifdef PCI_IOV
3886 	/* Check if matches VF_BAR */
3887 	if ((iov != NULL) && (bei >= PCIM_EA_BEI_VF_BAR_0) &&
3888 	    (bei <= PCIM_EA_BEI_VF_BAR_5))
3889 		return (PCIR_SRIOV_BAR(bei - PCIM_EA_BEI_VF_BAR_0) +
3890 		    iov_pos);
3891 #endif
3892 
3893 	return (-1);
3894 }
3895 
3896 int
3897 pci_ea_is_enabled(device_t dev, int rid)
3898 {
3899 	struct pci_ea_entry *ea;
3900 	struct pci_devinfo *dinfo;
3901 
3902 	dinfo = device_get_ivars(dev);
3903 
3904 	STAILQ_FOREACH(ea, &dinfo->cfg.ea.ea_entries, eae_link) {
3905 		if (pci_ea_bei_to_rid(dev, ea->eae_bei) == rid)
3906 			return ((ea->eae_flags & PCIM_EA_ENABLE) > 0);
3907 	}
3908 
3909 	return (0);
3910 }
3911 
3912 void
3913 pci_add_resources_ea(device_t bus, device_t dev, int alloc_iov)
3914 {
3915 	struct pci_ea_entry *ea;
3916 	struct pci_devinfo *dinfo;
3917 	pci_addr_t start, end, count;
3918 	struct resource_list *rl;
3919 	int type, flags, rid;
3920 	struct resource *res;
3921 	uint32_t tmp;
3922 #ifdef PCI_IOV
3923 	struct pcicfg_iov *iov;
3924 #endif
3925 
3926 	dinfo = device_get_ivars(dev);
3927 	rl = &dinfo->resources;
3928 	flags = 0;
3929 
3930 #ifdef PCI_IOV
3931 	iov = dinfo->cfg.iov;
3932 #endif
3933 
3934 	if (dinfo->cfg.ea.ea_location == 0)
3935 		return;
3936 
3937 	STAILQ_FOREACH(ea, &dinfo->cfg.ea.ea_entries, eae_link) {
3938 		/*
3939 		 * TODO: Ignore EA-BAR if is not enabled.
3940 		 *   Currently the EA implementation supports
3941 		 *   only situation, where EA structure contains
3942 		 *   predefined entries. In case they are not enabled
3943 		 *   leave them unallocated and proceed with
3944 		 *   a legacy-BAR mechanism.
3945 		 */
3946 		if ((ea->eae_flags & PCIM_EA_ENABLE) == 0)
3947 			continue;
3948 
3949 		switch ((ea->eae_flags & PCIM_EA_PP) >> PCIM_EA_PP_OFFSET) {
3950 		case PCIM_EA_P_MEM_PREFETCH:
3951 		case PCIM_EA_P_VF_MEM_PREFETCH:
3952 			flags = RF_PREFETCHABLE;
3953 			/* FALLTHROUGH */
3954 		case PCIM_EA_P_VF_MEM:
3955 		case PCIM_EA_P_MEM:
3956 			type = SYS_RES_MEMORY;
3957 			break;
3958 		case PCIM_EA_P_IO:
3959 			type = SYS_RES_IOPORT;
3960 			break;
3961 		default:
3962 			continue;
3963 		}
3964 
3965 		if (alloc_iov != 0) {
3966 #ifdef PCI_IOV
3967 			/* Allocating IOV, confirm BEI matches */
3968 			if ((ea->eae_bei < PCIM_EA_BEI_VF_BAR_0) ||
3969 			    (ea->eae_bei > PCIM_EA_BEI_VF_BAR_5))
3970 				continue;
3971 #else
3972 			continue;
3973 #endif
3974 		} else {
3975 			/* Allocating BAR, confirm BEI matches */
3976 			if (((ea->eae_bei < PCIM_EA_BEI_BAR_0) ||
3977 			    (ea->eae_bei > PCIM_EA_BEI_BAR_5)) &&
3978 			    (ea->eae_bei != PCIM_EA_BEI_ROM))
3979 				continue;
3980 		}
3981 
3982 		rid = pci_ea_bei_to_rid(dev, ea->eae_bei);
3983 		if (rid < 0)
3984 			continue;
3985 
3986 		/* Skip resources already allocated by EA */
3987 		if ((resource_list_find(rl, SYS_RES_MEMORY, rid) != NULL) ||
3988 		    (resource_list_find(rl, SYS_RES_IOPORT, rid) != NULL))
3989 			continue;
3990 
3991 		start = ea->eae_base;
3992 		count = ea->eae_max_offset + 1;
3993 #ifdef PCI_IOV
3994 		if (iov != NULL)
3995 			count = count * iov->iov_num_vfs;
3996 #endif
3997 		end = start + count - 1;
3998 		if (count == 0)
3999 			continue;
4000 
4001 		resource_list_add(rl, type, rid, start, end, count);
4002 		res = resource_list_reserve(rl, bus, dev, type, &rid, start, end, count,
4003 		    flags);
4004 		if (res == NULL) {
4005 			resource_list_delete(rl, type, rid);
4006 
4007 			/*
4008 			 * Failed to allocate using EA, disable entry.
4009 			 * Another attempt to allocation will be performed
4010 			 * further, but this time using legacy BAR registers
4011 			 */
4012 			tmp = pci_read_config(dev, ea->eae_cfg_offset, 4);
4013 			tmp &= ~PCIM_EA_ENABLE;
4014 			pci_write_config(dev, ea->eae_cfg_offset, tmp, 4);
4015 
4016 			/*
4017 			 * Disabling entry might fail in case it is hardwired.
4018 			 * Read flags again to match current status.
4019 			 */
4020 			ea->eae_flags = pci_read_config(dev, ea->eae_cfg_offset, 4);
4021 
4022 			continue;
4023 		}
4024 
4025 		/* As per specification, fill BAR with zeros */
4026 		pci_write_config(dev, rid, 0, 4);
4027 	}
4028 }
4029 
4030 void
4031 pci_add_resources(device_t bus, device_t dev, int force, uint32_t prefetchmask)
4032 {
4033 	struct pci_devinfo *dinfo;
4034 	pcicfgregs *cfg;
4035 	struct resource_list *rl;
4036 	const struct pci_quirk *q;
4037 	uint32_t devid;
4038 	int i;
4039 
4040 	dinfo = device_get_ivars(dev);
4041 	cfg = &dinfo->cfg;
4042 	rl = &dinfo->resources;
4043 	devid = (cfg->device << 16) | cfg->vendor;
4044 
4045 	/* Allocate resources using Enhanced Allocation */
4046 	pci_add_resources_ea(bus, dev, 0);
4047 
4048 	/* ATA devices needs special map treatment */
4049 	if ((pci_get_class(dev) == PCIC_STORAGE) &&
4050 	    (pci_get_subclass(dev) == PCIS_STORAGE_IDE) &&
4051 	    ((pci_get_progif(dev) & PCIP_STORAGE_IDE_MASTERDEV) ||
4052 	     (!pci_read_config(dev, PCIR_BAR(0), 4) &&
4053 	      !pci_read_config(dev, PCIR_BAR(2), 4))) )
4054 		pci_ata_maps(bus, dev, rl, force, prefetchmask);
4055 	else
4056 		for (i = 0; i < cfg->nummaps;) {
4057 			/* Skip resources already managed by EA */
4058 			if ((resource_list_find(rl, SYS_RES_MEMORY, PCIR_BAR(i)) != NULL) ||
4059 			    (resource_list_find(rl, SYS_RES_IOPORT, PCIR_BAR(i)) != NULL) ||
4060 			    pci_ea_is_enabled(dev, PCIR_BAR(i))) {
4061 				i++;
4062 				continue;
4063 			}
4064 
4065 			/*
4066 			 * Skip quirked resources.
4067 			 */
4068 			for (q = &pci_quirks[0]; q->devid != 0; q++)
4069 				if (q->devid == devid &&
4070 				    q->type == PCI_QUIRK_UNMAP_REG &&
4071 				    q->arg1 == PCIR_BAR(i))
4072 					break;
4073 			if (q->devid != 0) {
4074 				i++;
4075 				continue;
4076 			}
4077 			i += pci_add_map(bus, dev, PCIR_BAR(i), rl, force,
4078 			    prefetchmask & (1 << i));
4079 		}
4080 
4081 	/*
4082 	 * Add additional, quirked resources.
4083 	 */
4084 	for (q = &pci_quirks[0]; q->devid != 0; q++)
4085 		if (q->devid == devid && q->type == PCI_QUIRK_MAP_REG)
4086 			pci_add_map(bus, dev, q->arg1, rl, force, 0);
4087 
4088 	if (cfg->intpin > 0 && PCI_INTERRUPT_VALID(cfg->intline)) {
4089 #ifdef __PCI_REROUTE_INTERRUPT
4090 		/*
4091 		 * Try to re-route interrupts. Sometimes the BIOS or
4092 		 * firmware may leave bogus values in these registers.
4093 		 * If the re-route fails, then just stick with what we
4094 		 * have.
4095 		 */
4096 		pci_assign_interrupt(bus, dev, 1);
4097 #else
4098 		pci_assign_interrupt(bus, dev, 0);
4099 #endif
4100 	}
4101 
4102 	if (pci_usb_takeover && pci_get_class(dev) == PCIC_SERIALBUS &&
4103 	    pci_get_subclass(dev) == PCIS_SERIALBUS_USB) {
4104 		if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_XHCI)
4105 			xhci_early_takeover(dev);
4106 		else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_EHCI)
4107 			ehci_early_takeover(dev);
4108 		else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_OHCI)
4109 			ohci_early_takeover(dev);
4110 		else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_UHCI)
4111 			uhci_early_takeover(dev);
4112 	}
4113 
4114 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
4115 	/*
4116 	 * Reserve resources for secondary bus ranges behind bridge
4117 	 * devices.
4118 	 */
4119 	pci_reserve_secbus(bus, dev, cfg, rl);
4120 #endif
4121 }
4122 
4123 static struct pci_devinfo *
4124 pci_identify_function(device_t pcib, device_t dev, int domain, int busno,
4125     int slot, int func)
4126 {
4127 	struct pci_devinfo *dinfo;
4128 
4129 	dinfo = pci_read_device(pcib, dev, domain, busno, slot, func);
4130 	if (dinfo != NULL)
4131 		pci_add_child(dev, dinfo);
4132 
4133 	return (dinfo);
4134 }
4135 
4136 void
4137 pci_add_children(device_t dev, int domain, int busno)
4138 {
4139 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
4140 	device_t pcib = device_get_parent(dev);
4141 	struct pci_devinfo *dinfo;
4142 	int maxslots;
4143 	int s, f, pcifunchigh;
4144 	uint8_t hdrtype;
4145 	int first_func;
4146 
4147 	/*
4148 	 * Try to detect a device at slot 0, function 0.  If it exists, try to
4149 	 * enable ARI.  We must enable ARI before detecting the rest of the
4150 	 * functions on this bus as ARI changes the set of slots and functions
4151 	 * that are legal on this bus.
4152 	 */
4153 	dinfo = pci_identify_function(pcib, dev, domain, busno, 0, 0);
4154 	if (dinfo != NULL && pci_enable_ari)
4155 		PCIB_TRY_ENABLE_ARI(pcib, dinfo->cfg.dev);
4156 
4157 	/*
4158 	 * Start looking for new devices on slot 0 at function 1 because we
4159 	 * just identified the device at slot 0, function 0.
4160 	 */
4161 	first_func = 1;
4162 
4163 	maxslots = PCIB_MAXSLOTS(pcib);
4164 	for (s = 0; s <= maxslots; s++, first_func = 0) {
4165 		pcifunchigh = 0;
4166 		f = 0;
4167 		DELAY(1);
4168 
4169 		/* If function 0 is not present, skip to the next slot. */
4170 		if (REG(PCIR_VENDOR, 2) == PCIV_INVALID)
4171 			continue;
4172 		hdrtype = REG(PCIR_HDRTYPE, 1);
4173 		if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
4174 			continue;
4175 		if (hdrtype & PCIM_MFDEV)
4176 			pcifunchigh = PCIB_MAXFUNCS(pcib);
4177 		for (f = first_func; f <= pcifunchigh; f++)
4178 			pci_identify_function(pcib, dev, domain, busno, s, f);
4179 	}
4180 #undef REG
4181 }
4182 
4183 int
4184 pci_rescan_method(device_t dev)
4185 {
4186 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
4187 	device_t pcib = device_get_parent(dev);
4188 	device_t child, *devlist, *unchanged;
4189 	int devcount, error, i, j, maxslots, oldcount;
4190 	int busno, domain, s, f, pcifunchigh;
4191 	uint8_t hdrtype;
4192 
4193 	/* No need to check for ARI on a rescan. */
4194 	error = device_get_children(dev, &devlist, &devcount);
4195 	if (error)
4196 		return (error);
4197 	if (devcount != 0) {
4198 		unchanged = malloc(devcount * sizeof(device_t), M_TEMP,
4199 		    M_NOWAIT | M_ZERO);
4200 		if (unchanged == NULL) {
4201 			free(devlist, M_TEMP);
4202 			return (ENOMEM);
4203 		}
4204 	} else
4205 		unchanged = NULL;
4206 
4207 	domain = pcib_get_domain(dev);
4208 	busno = pcib_get_bus(dev);
4209 	maxslots = PCIB_MAXSLOTS(pcib);
4210 	for (s = 0; s <= maxslots; s++) {
4211 		/* If function 0 is not present, skip to the next slot. */
4212 		f = 0;
4213 		if (REG(PCIR_VENDOR, 2) == PCIV_INVALID)
4214 			continue;
4215 		pcifunchigh = 0;
4216 		hdrtype = REG(PCIR_HDRTYPE, 1);
4217 		if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
4218 			continue;
4219 		if (hdrtype & PCIM_MFDEV)
4220 			pcifunchigh = PCIB_MAXFUNCS(pcib);
4221 		for (f = 0; f <= pcifunchigh; f++) {
4222 			if (REG(PCIR_VENDOR, 2) == PCIV_INVALID)
4223 				continue;
4224 
4225 			/*
4226 			 * Found a valid function.  Check if a
4227 			 * device_t for this device already exists.
4228 			 */
4229 			for (i = 0; i < devcount; i++) {
4230 				child = devlist[i];
4231 				if (child == NULL)
4232 					continue;
4233 				if (pci_get_slot(child) == s &&
4234 				    pci_get_function(child) == f) {
4235 					unchanged[i] = child;
4236 					goto next_func;
4237 				}
4238 			}
4239 
4240 			pci_identify_function(pcib, dev, domain, busno, s, f);
4241 		next_func:;
4242 		}
4243 	}
4244 
4245 	/* Remove devices that are no longer present. */
4246 	for (i = 0; i < devcount; i++) {
4247 		if (unchanged[i] != NULL)
4248 			continue;
4249 		device_delete_child(dev, devlist[i]);
4250 	}
4251 
4252 	free(devlist, M_TEMP);
4253 	oldcount = devcount;
4254 
4255 	/* Try to attach the devices just added. */
4256 	error = device_get_children(dev, &devlist, &devcount);
4257 	if (error) {
4258 		free(unchanged, M_TEMP);
4259 		return (error);
4260 	}
4261 
4262 	for (i = 0; i < devcount; i++) {
4263 		for (j = 0; j < oldcount; j++) {
4264 			if (devlist[i] == unchanged[j])
4265 				goto next_device;
4266 		}
4267 
4268 		device_probe_and_attach(devlist[i]);
4269 	next_device:;
4270 	}
4271 
4272 	free(unchanged, M_TEMP);
4273 	free(devlist, M_TEMP);
4274 	return (0);
4275 #undef REG
4276 }
4277 
4278 #ifdef PCI_IOV
4279 device_t
4280 pci_add_iov_child(device_t bus, device_t pf, uint16_t rid, uint16_t vid,
4281     uint16_t did)
4282 {
4283 	struct pci_devinfo *vf_dinfo;
4284 	device_t pcib;
4285 	int busno, slot, func;
4286 
4287 	pcib = device_get_parent(bus);
4288 
4289 	PCIB_DECODE_RID(pcib, rid, &busno, &slot, &func);
4290 
4291 	vf_dinfo = pci_fill_devinfo(pcib, bus, pci_get_domain(pcib), busno,
4292 	    slot, func, vid, did);
4293 
4294 	vf_dinfo->cfg.flags |= PCICFG_VF;
4295 	pci_add_child(bus, vf_dinfo);
4296 
4297 	return (vf_dinfo->cfg.dev);
4298 }
4299 
4300 device_t
4301 pci_create_iov_child_method(device_t bus, device_t pf, uint16_t rid,
4302     uint16_t vid, uint16_t did)
4303 {
4304 
4305 	return (pci_add_iov_child(bus, pf, rid, vid, did));
4306 }
4307 #endif
4308 
4309 /*
4310  * For PCIe device set Max_Payload_Size to match PCIe root's.
4311  */
4312 static void
4313 pcie_setup_mps(device_t dev)
4314 {
4315 	struct pci_devinfo *dinfo = device_get_ivars(dev);
4316 	device_t root;
4317 	uint16_t rmps, mmps, mps;
4318 
4319 	if (dinfo->cfg.pcie.pcie_location == 0)
4320 		return;
4321 	root = pci_find_pcie_root_port(dev);
4322 	if (root == NULL)
4323 		return;
4324 	/* Check whether the MPS is already configured. */
4325 	rmps = pcie_read_config(root, PCIER_DEVICE_CTL, 2) &
4326 	    PCIEM_CTL_MAX_PAYLOAD;
4327 	mps = pcie_read_config(dev, PCIER_DEVICE_CTL, 2) &
4328 	    PCIEM_CTL_MAX_PAYLOAD;
4329 	if (mps == rmps)
4330 		return;
4331 	/* Check whether the device is capable of the root's MPS. */
4332 	mmps = (pcie_read_config(dev, PCIER_DEVICE_CAP, 2) &
4333 	    PCIEM_CAP_MAX_PAYLOAD) << 5;
4334 	if (rmps > mmps) {
4335 		/*
4336 		 * The device is unable to handle root's MPS.  Limit root.
4337 		 * XXX: We should traverse through all the tree, applying
4338 		 * it to all the devices.
4339 		 */
4340 		pcie_adjust_config(root, PCIER_DEVICE_CTL,
4341 		    PCIEM_CTL_MAX_PAYLOAD, mmps, 2);
4342 	} else {
4343 		pcie_adjust_config(dev, PCIER_DEVICE_CTL,
4344 		    PCIEM_CTL_MAX_PAYLOAD, rmps, 2);
4345 	}
4346 }
4347 
4348 static void
4349 pci_add_child_clear_aer(device_t dev, struct pci_devinfo *dinfo)
4350 {
4351 	int aer;
4352 	uint32_t r;
4353 	uint16_t r2;
4354 
4355 	if (dinfo->cfg.pcie.pcie_location != 0 &&
4356 	    dinfo->cfg.pcie.pcie_type == PCIEM_TYPE_ROOT_PORT) {
4357 		r2 = pci_read_config(dev, dinfo->cfg.pcie.pcie_location +
4358 		    PCIER_ROOT_CTL, 2);
4359 		r2 &= ~(PCIEM_ROOT_CTL_SERR_CORR |
4360 		    PCIEM_ROOT_CTL_SERR_NONFATAL | PCIEM_ROOT_CTL_SERR_FATAL);
4361 		pci_write_config(dev, dinfo->cfg.pcie.pcie_location +
4362 		    PCIER_ROOT_CTL, r2, 2);
4363 	}
4364 	if (pci_find_extcap(dev, PCIZ_AER, &aer) == 0) {
4365 		r = pci_read_config(dev, aer + PCIR_AER_UC_STATUS, 4);
4366 		pci_write_config(dev, aer + PCIR_AER_UC_STATUS, r, 4);
4367 		if (r != 0 && bootverbose) {
4368 			pci_printf(&dinfo->cfg,
4369 			    "clearing AER UC 0x%08x -> 0x%08x\n",
4370 			    r, pci_read_config(dev, aer + PCIR_AER_UC_STATUS,
4371 			    4));
4372 		}
4373 
4374 		r = pci_read_config(dev, aer + PCIR_AER_UC_MASK, 4);
4375 		r &= ~(PCIM_AER_UC_TRAINING_ERROR |
4376 		    PCIM_AER_UC_DL_PROTOCOL_ERROR |
4377 		    PCIM_AER_UC_SURPRISE_LINK_DOWN |
4378 		    PCIM_AER_UC_POISONED_TLP |
4379 		    PCIM_AER_UC_FC_PROTOCOL_ERROR |
4380 		    PCIM_AER_UC_COMPLETION_TIMEOUT |
4381 		    PCIM_AER_UC_COMPLETER_ABORT |
4382 		    PCIM_AER_UC_UNEXPECTED_COMPLETION |
4383 		    PCIM_AER_UC_RECEIVER_OVERFLOW |
4384 		    PCIM_AER_UC_MALFORMED_TLP |
4385 		    PCIM_AER_UC_ECRC_ERROR |
4386 		    PCIM_AER_UC_UNSUPPORTED_REQUEST |
4387 		    PCIM_AER_UC_ACS_VIOLATION |
4388 		    PCIM_AER_UC_INTERNAL_ERROR |
4389 		    PCIM_AER_UC_MC_BLOCKED_TLP |
4390 		    PCIM_AER_UC_ATOMIC_EGRESS_BLK |
4391 		    PCIM_AER_UC_TLP_PREFIX_BLOCKED);
4392 		pci_write_config(dev, aer + PCIR_AER_UC_MASK, r, 4);
4393 
4394 		r = pci_read_config(dev, aer + PCIR_AER_COR_STATUS, 4);
4395 		pci_write_config(dev, aer + PCIR_AER_COR_STATUS, r, 4);
4396 		if (r != 0 && bootverbose) {
4397 			pci_printf(&dinfo->cfg,
4398 			    "clearing AER COR 0x%08x -> 0x%08x\n",
4399 			    r, pci_read_config(dev, aer + PCIR_AER_COR_STATUS,
4400 			    4));
4401 		}
4402 
4403 		r = pci_read_config(dev, aer + PCIR_AER_COR_MASK, 4);
4404 		r &= ~(PCIM_AER_COR_RECEIVER_ERROR |
4405 		    PCIM_AER_COR_BAD_TLP |
4406 		    PCIM_AER_COR_BAD_DLLP |
4407 		    PCIM_AER_COR_REPLAY_ROLLOVER |
4408 		    PCIM_AER_COR_REPLAY_TIMEOUT |
4409 		    PCIM_AER_COR_ADVISORY_NF_ERROR |
4410 		    PCIM_AER_COR_INTERNAL_ERROR |
4411 		    PCIM_AER_COR_HEADER_LOG_OVFLOW);
4412 		pci_write_config(dev, aer + PCIR_AER_COR_MASK, r, 4);
4413 
4414 		r = pci_read_config(dev, dinfo->cfg.pcie.pcie_location +
4415 		    PCIER_DEVICE_CTL, 2);
4416 		r |=  PCIEM_CTL_COR_ENABLE | PCIEM_CTL_NFER_ENABLE |
4417 		    PCIEM_CTL_FER_ENABLE | PCIEM_CTL_URR_ENABLE;
4418 		pci_write_config(dev, dinfo->cfg.pcie.pcie_location +
4419 		    PCIER_DEVICE_CTL, r, 2);
4420 	}
4421 }
4422 
4423 void
4424 pci_add_child(device_t bus, struct pci_devinfo *dinfo)
4425 {
4426 	device_t dev;
4427 
4428 	dinfo->cfg.dev = dev = device_add_child(bus, NULL, -1);
4429 	device_set_ivars(dev, dinfo);
4430 	resource_list_init(&dinfo->resources);
4431 	pci_cfg_save(dev, dinfo, 0);
4432 	pci_cfg_restore(dev, dinfo);
4433 	pci_print_verbose(dinfo);
4434 	pci_add_resources(bus, dev, 0, 0);
4435 	if (pci_enable_mps_tune)
4436 		pcie_setup_mps(dev);
4437 	pci_child_added(dinfo->cfg.dev);
4438 
4439 	if (pci_clear_aer_on_attach)
4440 		pci_add_child_clear_aer(dev, dinfo);
4441 
4442 	EVENTHANDLER_INVOKE(pci_add_device, dinfo->cfg.dev);
4443 }
4444 
4445 void
4446 pci_child_added_method(device_t dev, device_t child)
4447 {
4448 
4449 }
4450 
4451 static int
4452 pci_probe(device_t dev)
4453 {
4454 
4455 	device_set_desc(dev, "PCI bus");
4456 
4457 	/* Allow other subclasses to override this driver. */
4458 	return (BUS_PROBE_GENERIC);
4459 }
4460 
4461 int
4462 pci_attach_common(device_t dev)
4463 {
4464 	struct pci_softc *sc;
4465 	int busno, domain;
4466 #ifdef PCI_RES_BUS
4467 	int rid;
4468 #endif
4469 
4470 	sc = device_get_softc(dev);
4471 	domain = pcib_get_domain(dev);
4472 	busno = pcib_get_bus(dev);
4473 #ifdef PCI_RES_BUS
4474 	rid = 0;
4475 	sc->sc_bus = bus_alloc_resource(dev, PCI_RES_BUS, &rid, busno, busno,
4476 	    1, 0);
4477 	if (sc->sc_bus == NULL) {
4478 		device_printf(dev, "failed to allocate bus number\n");
4479 		return (ENXIO);
4480 	}
4481 #endif
4482 	if (bootverbose)
4483 		device_printf(dev, "domain=%d, physical bus=%d\n",
4484 		    domain, busno);
4485 	sc->sc_dma_tag = bus_get_dma_tag(dev);
4486 	return (0);
4487 }
4488 
4489 int
4490 pci_attach(device_t dev)
4491 {
4492 	int busno, domain, error;
4493 
4494 	error = pci_attach_common(dev);
4495 	if (error)
4496 		return (error);
4497 
4498 	/*
4499 	 * Since there can be multiple independently numbered PCI
4500 	 * buses on systems with multiple PCI domains, we can't use
4501 	 * the unit number to decide which bus we are probing. We ask
4502 	 * the parent pcib what our domain and bus numbers are.
4503 	 */
4504 	domain = pcib_get_domain(dev);
4505 	busno = pcib_get_bus(dev);
4506 	pci_add_children(dev, domain, busno);
4507 	return (bus_generic_attach(dev));
4508 }
4509 
4510 int
4511 pci_detach(device_t dev)
4512 {
4513 #ifdef PCI_RES_BUS
4514 	struct pci_softc *sc;
4515 #endif
4516 	int error;
4517 
4518 	error = bus_generic_detach(dev);
4519 	if (error)
4520 		return (error);
4521 #ifdef PCI_RES_BUS
4522 	sc = device_get_softc(dev);
4523 	error = bus_release_resource(dev, PCI_RES_BUS, 0, sc->sc_bus);
4524 	if (error)
4525 		return (error);
4526 #endif
4527 	return (device_delete_children(dev));
4528 }
4529 
4530 static void
4531 pci_hint_device_unit(device_t dev, device_t child, const char *name, int *unitp)
4532 {
4533 	int line, unit;
4534 	const char *at;
4535 	char me1[24], me2[32];
4536 	uint8_t b, s, f;
4537 	uint32_t d;
4538 	device_location_cache_t *cache;
4539 
4540 	d = pci_get_domain(child);
4541 	b = pci_get_bus(child);
4542 	s = pci_get_slot(child);
4543 	f = pci_get_function(child);
4544 	snprintf(me1, sizeof(me1), "pci%u:%u:%u", b, s, f);
4545 	snprintf(me2, sizeof(me2), "pci%u:%u:%u:%u", d, b, s, f);
4546 	line = 0;
4547 	cache = dev_wired_cache_init();
4548 	while (resource_find_dev(&line, name, &unit, "at", NULL) == 0) {
4549 		resource_string_value(name, unit, "at", &at);
4550 		if (strcmp(at, me1) == 0 || strcmp(at, me2) == 0) {
4551 			*unitp = unit;
4552 			break;
4553 		}
4554 		if (dev_wired_cache_match(cache, child, at)) {
4555 			*unitp = unit;
4556 			break;
4557 		}
4558 	}
4559 	dev_wired_cache_fini(cache);
4560 }
4561 
4562 static void
4563 pci_set_power_child(device_t dev, device_t child, int state)
4564 {
4565 	device_t pcib;
4566 	int dstate;
4567 
4568 	/*
4569 	 * Set the device to the given state.  If the firmware suggests
4570 	 * a different power state, use it instead.  If power management
4571 	 * is not present, the firmware is responsible for managing
4572 	 * device power.  Skip children who aren't attached since they
4573 	 * are handled separately.
4574 	 */
4575 	pcib = device_get_parent(dev);
4576 	dstate = state;
4577 	if (device_is_attached(child) &&
4578 	    PCIB_POWER_FOR_SLEEP(pcib, child, &dstate) == 0)
4579 		pci_set_powerstate(child, dstate);
4580 }
4581 
4582 int
4583 pci_suspend_child(device_t dev, device_t child)
4584 {
4585 	struct pci_devinfo *dinfo;
4586 	struct resource_list_entry *rle;
4587 	int error;
4588 
4589 	dinfo = device_get_ivars(child);
4590 
4591 	/*
4592 	 * Save the PCI configuration space for the child and set the
4593 	 * device in the appropriate power state for this sleep state.
4594 	 */
4595 	pci_cfg_save(child, dinfo, 0);
4596 
4597 	/* Suspend devices before potentially powering them down. */
4598 	error = bus_generic_suspend_child(dev, child);
4599 
4600 	if (error)
4601 		return (error);
4602 
4603 	if (pci_do_power_suspend) {
4604 		/*
4605 		 * Make sure this device's interrupt handler is not invoked
4606 		 * in the case the device uses a shared interrupt that can
4607 		 * be raised by some other device.
4608 		 * This is applicable only to regular (legacy) PCI interrupts
4609 		 * as MSI/MSI-X interrupts are never shared.
4610 		 */
4611 		rle = resource_list_find(&dinfo->resources,
4612 		    SYS_RES_IRQ, 0);
4613 		if (rle != NULL && rle->res != NULL)
4614 			(void)bus_suspend_intr(child, rle->res);
4615 		pci_set_power_child(dev, child, PCI_POWERSTATE_D3);
4616 	}
4617 
4618 	return (0);
4619 }
4620 
4621 int
4622 pci_resume_child(device_t dev, device_t child)
4623 {
4624 	struct pci_devinfo *dinfo;
4625 	struct resource_list_entry *rle;
4626 
4627 	if (pci_do_power_resume)
4628 		pci_set_power_child(dev, child, PCI_POWERSTATE_D0);
4629 
4630 	dinfo = device_get_ivars(child);
4631 	pci_cfg_restore(child, dinfo);
4632 	if (!device_is_attached(child))
4633 		pci_cfg_save(child, dinfo, 1);
4634 
4635 	bus_generic_resume_child(dev, child);
4636 
4637 	/*
4638 	 * Allow interrupts only after fully resuming the driver and hardware.
4639 	 */
4640 	if (pci_do_power_suspend) {
4641 		/* See pci_suspend_child for details. */
4642 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, 0);
4643 		if (rle != NULL && rle->res != NULL)
4644 			(void)bus_resume_intr(child, rle->res);
4645 	}
4646 
4647 	return (0);
4648 }
4649 
4650 int
4651 pci_resume(device_t dev)
4652 {
4653 	device_t child, *devlist;
4654 	int error, i, numdevs;
4655 
4656 	if ((error = device_get_children(dev, &devlist, &numdevs)) != 0)
4657 		return (error);
4658 
4659 	/*
4660 	 * Resume critical devices first, then everything else later.
4661 	 */
4662 	for (i = 0; i < numdevs; i++) {
4663 		child = devlist[i];
4664 		switch (pci_get_class(child)) {
4665 		case PCIC_DISPLAY:
4666 		case PCIC_MEMORY:
4667 		case PCIC_BRIDGE:
4668 		case PCIC_BASEPERIPH:
4669 			BUS_RESUME_CHILD(dev, child);
4670 			break;
4671 		}
4672 	}
4673 	for (i = 0; i < numdevs; i++) {
4674 		child = devlist[i];
4675 		switch (pci_get_class(child)) {
4676 		case PCIC_DISPLAY:
4677 		case PCIC_MEMORY:
4678 		case PCIC_BRIDGE:
4679 		case PCIC_BASEPERIPH:
4680 			break;
4681 		default:
4682 			BUS_RESUME_CHILD(dev, child);
4683 		}
4684 	}
4685 	free(devlist, M_TEMP);
4686 	return (0);
4687 }
4688 
4689 static void
4690 pci_load_vendor_data(void)
4691 {
4692 	caddr_t data;
4693 	void *ptr;
4694 	size_t sz;
4695 
4696 	data = preload_search_by_type("pci_vendor_data");
4697 	if (data != NULL) {
4698 		ptr = preload_fetch_addr(data);
4699 		sz = preload_fetch_size(data);
4700 		if (ptr != NULL && sz != 0) {
4701 			pci_vendordata = ptr;
4702 			pci_vendordata_size = sz;
4703 			/* terminate the database */
4704 			pci_vendordata[pci_vendordata_size] = '\n';
4705 		}
4706 	}
4707 }
4708 
4709 void
4710 pci_driver_added(device_t dev, driver_t *driver)
4711 {
4712 	int numdevs;
4713 	device_t *devlist;
4714 	device_t child;
4715 	struct pci_devinfo *dinfo;
4716 	int i;
4717 
4718 	if (bootverbose)
4719 		device_printf(dev, "driver added\n");
4720 	DEVICE_IDENTIFY(driver, dev);
4721 	if (device_get_children(dev, &devlist, &numdevs) != 0)
4722 		return;
4723 	for (i = 0; i < numdevs; i++) {
4724 		child = devlist[i];
4725 		if (device_get_state(child) != DS_NOTPRESENT)
4726 			continue;
4727 		dinfo = device_get_ivars(child);
4728 		pci_print_verbose(dinfo);
4729 		if (bootverbose)
4730 			pci_printf(&dinfo->cfg, "reprobing on driver added\n");
4731 		pci_cfg_restore(child, dinfo);
4732 		if (device_probe_and_attach(child) != 0)
4733 			pci_child_detached(dev, child);
4734 	}
4735 	free(devlist, M_TEMP);
4736 }
4737 
4738 int
4739 pci_setup_intr(device_t dev, device_t child, struct resource *irq, int flags,
4740     driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep)
4741 {
4742 	struct pci_devinfo *dinfo;
4743 	struct msix_table_entry *mte;
4744 	struct msix_vector *mv;
4745 	uint64_t addr;
4746 	uint32_t data;
4747 	void *cookie;
4748 	int error, rid;
4749 
4750 	error = bus_generic_setup_intr(dev, child, irq, flags, filter, intr,
4751 	    arg, &cookie);
4752 	if (error)
4753 		return (error);
4754 
4755 	/* If this is not a direct child, just bail out. */
4756 	if (device_get_parent(child) != dev) {
4757 		*cookiep = cookie;
4758 		return(0);
4759 	}
4760 
4761 	rid = rman_get_rid(irq);
4762 	if (rid == 0) {
4763 		/* Make sure that INTx is enabled */
4764 		pci_clear_command_bit(dev, child, PCIM_CMD_INTxDIS);
4765 	} else {
4766 		/*
4767 		 * Check to see if the interrupt is MSI or MSI-X.
4768 		 * Ask our parent to map the MSI and give
4769 		 * us the address and data register values.
4770 		 * If we fail for some reason, teardown the
4771 		 * interrupt handler.
4772 		 */
4773 		dinfo = device_get_ivars(child);
4774 		if (dinfo->cfg.msi.msi_alloc > 0) {
4775 			if (dinfo->cfg.msi.msi_addr == 0) {
4776 				KASSERT(dinfo->cfg.msi.msi_handlers == 0,
4777 			    ("MSI has handlers, but vectors not mapped"));
4778 				error = PCIB_MAP_MSI(device_get_parent(dev),
4779 				    child, rman_get_start(irq), &addr, &data);
4780 				if (error)
4781 					goto bad;
4782 				dinfo->cfg.msi.msi_addr = addr;
4783 				dinfo->cfg.msi.msi_data = data;
4784 			}
4785 			if (dinfo->cfg.msi.msi_handlers == 0)
4786 				pci_enable_msi(child, dinfo->cfg.msi.msi_addr,
4787 				    dinfo->cfg.msi.msi_data);
4788 			dinfo->cfg.msi.msi_handlers++;
4789 		} else {
4790 			KASSERT(dinfo->cfg.msix.msix_alloc > 0,
4791 			    ("No MSI or MSI-X interrupts allocated"));
4792 			KASSERT(rid <= dinfo->cfg.msix.msix_table_len,
4793 			    ("MSI-X index too high"));
4794 			mte = &dinfo->cfg.msix.msix_table[rid - 1];
4795 			KASSERT(mte->mte_vector != 0, ("no message vector"));
4796 			mv = &dinfo->cfg.msix.msix_vectors[mte->mte_vector - 1];
4797 			KASSERT(mv->mv_irq == rman_get_start(irq),
4798 			    ("IRQ mismatch"));
4799 			if (mv->mv_address == 0) {
4800 				KASSERT(mte->mte_handlers == 0,
4801 		    ("MSI-X table entry has handlers, but vector not mapped"));
4802 				error = PCIB_MAP_MSI(device_get_parent(dev),
4803 				    child, rman_get_start(irq), &addr, &data);
4804 				if (error)
4805 					goto bad;
4806 				mv->mv_address = addr;
4807 				mv->mv_data = data;
4808 			}
4809 
4810 			/*
4811 			 * The MSIX table entry must be made valid by
4812 			 * incrementing the mte_handlers before
4813 			 * calling pci_enable_msix() and
4814 			 * pci_resume_msix(). Else the MSIX rewrite
4815 			 * table quirk will not work as expected.
4816 			 */
4817 			mte->mte_handlers++;
4818 			if (mte->mte_handlers == 1) {
4819 				pci_enable_msix(child, rid - 1, mv->mv_address,
4820 				    mv->mv_data);
4821 				pci_unmask_msix(child, rid - 1);
4822 			}
4823 		}
4824 
4825 		/*
4826 		 * Make sure that INTx is disabled if we are using MSI/MSI-X,
4827 		 * unless the device is affected by PCI_QUIRK_MSI_INTX_BUG,
4828 		 * in which case we "enable" INTx so MSI/MSI-X actually works.
4829 		 */
4830 		if (!pci_has_quirk(pci_get_devid(child),
4831 		    PCI_QUIRK_MSI_INTX_BUG))
4832 			pci_set_command_bit(dev, child, PCIM_CMD_INTxDIS);
4833 		else
4834 			pci_clear_command_bit(dev, child, PCIM_CMD_INTxDIS);
4835 	bad:
4836 		if (error) {
4837 			(void)bus_generic_teardown_intr(dev, child, irq,
4838 			    cookie);
4839 			return (error);
4840 		}
4841 	}
4842 	*cookiep = cookie;
4843 	return (0);
4844 }
4845 
4846 int
4847 pci_teardown_intr(device_t dev, device_t child, struct resource *irq,
4848     void *cookie)
4849 {
4850 	struct msix_table_entry *mte;
4851 	struct resource_list_entry *rle;
4852 	struct pci_devinfo *dinfo;
4853 	int error, rid;
4854 
4855 	if (irq == NULL || !(rman_get_flags(irq) & RF_ACTIVE))
4856 		return (EINVAL);
4857 
4858 	/* If this isn't a direct child, just bail out */
4859 	if (device_get_parent(child) != dev)
4860 		return(bus_generic_teardown_intr(dev, child, irq, cookie));
4861 
4862 	rid = rman_get_rid(irq);
4863 	if (rid == 0) {
4864 		/* Mask INTx */
4865 		pci_set_command_bit(dev, child, PCIM_CMD_INTxDIS);
4866 	} else {
4867 		/*
4868 		 * Check to see if the interrupt is MSI or MSI-X.  If so,
4869 		 * decrement the appropriate handlers count and mask the
4870 		 * MSI-X message, or disable MSI messages if the count
4871 		 * drops to 0.
4872 		 */
4873 		dinfo = device_get_ivars(child);
4874 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, rid);
4875 		if (rle->res != irq)
4876 			return (EINVAL);
4877 		if (dinfo->cfg.msi.msi_alloc > 0) {
4878 			KASSERT(rid <= dinfo->cfg.msi.msi_alloc,
4879 			    ("MSI-X index too high"));
4880 			if (dinfo->cfg.msi.msi_handlers == 0)
4881 				return (EINVAL);
4882 			dinfo->cfg.msi.msi_handlers--;
4883 			if (dinfo->cfg.msi.msi_handlers == 0)
4884 				pci_disable_msi(child);
4885 		} else {
4886 			KASSERT(dinfo->cfg.msix.msix_alloc > 0,
4887 			    ("No MSI or MSI-X interrupts allocated"));
4888 			KASSERT(rid <= dinfo->cfg.msix.msix_table_len,
4889 			    ("MSI-X index too high"));
4890 			mte = &dinfo->cfg.msix.msix_table[rid - 1];
4891 			if (mte->mte_handlers == 0)
4892 				return (EINVAL);
4893 			mte->mte_handlers--;
4894 			if (mte->mte_handlers == 0)
4895 				pci_mask_msix(child, rid - 1);
4896 		}
4897 	}
4898 	error = bus_generic_teardown_intr(dev, child, irq, cookie);
4899 	if (rid > 0)
4900 		KASSERT(error == 0,
4901 		    ("%s: generic teardown failed for MSI/MSI-X", __func__));
4902 	return (error);
4903 }
4904 
4905 int
4906 pci_print_child(device_t dev, device_t child)
4907 {
4908 	struct pci_devinfo *dinfo;
4909 	struct resource_list *rl;
4910 	int retval = 0;
4911 
4912 	dinfo = device_get_ivars(child);
4913 	rl = &dinfo->resources;
4914 
4915 	retval += bus_print_child_header(dev, child);
4916 
4917 	retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#jx");
4918 	retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY, "%#jx");
4919 	retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%jd");
4920 	if (device_get_flags(dev))
4921 		retval += printf(" flags %#x", device_get_flags(dev));
4922 
4923 	retval += printf(" at device %d.%d", pci_get_slot(child),
4924 	    pci_get_function(child));
4925 
4926 	retval += bus_print_child_domain(dev, child);
4927 	retval += bus_print_child_footer(dev, child);
4928 
4929 	return (retval);
4930 }
4931 
4932 static const struct
4933 {
4934 	int		class;
4935 	int		subclass;
4936 	int		report; /* 0 = bootverbose, 1 = always */
4937 	const char	*desc;
4938 } pci_nomatch_tab[] = {
4939 	{PCIC_OLD,		-1,			1, "old"},
4940 	{PCIC_OLD,		PCIS_OLD_NONVGA,	1, "non-VGA display device"},
4941 	{PCIC_OLD,		PCIS_OLD_VGA,		1, "VGA-compatible display device"},
4942 	{PCIC_STORAGE,		-1,			1, "mass storage"},
4943 	{PCIC_STORAGE,		PCIS_STORAGE_SCSI,	1, "SCSI"},
4944 	{PCIC_STORAGE,		PCIS_STORAGE_IDE,	1, "ATA"},
4945 	{PCIC_STORAGE,		PCIS_STORAGE_FLOPPY,	1, "floppy disk"},
4946 	{PCIC_STORAGE,		PCIS_STORAGE_IPI,	1, "IPI"},
4947 	{PCIC_STORAGE,		PCIS_STORAGE_RAID,	1, "RAID"},
4948 	{PCIC_STORAGE,		PCIS_STORAGE_ATA_ADMA,	1, "ATA (ADMA)"},
4949 	{PCIC_STORAGE,		PCIS_STORAGE_SATA,	1, "SATA"},
4950 	{PCIC_STORAGE,		PCIS_STORAGE_SAS,	1, "SAS"},
4951 	{PCIC_STORAGE,		PCIS_STORAGE_NVM,	1, "NVM"},
4952 	{PCIC_NETWORK,		-1,			1, "network"},
4953 	{PCIC_NETWORK,		PCIS_NETWORK_ETHERNET,	1, "ethernet"},
4954 	{PCIC_NETWORK,		PCIS_NETWORK_TOKENRING,	1, "token ring"},
4955 	{PCIC_NETWORK,		PCIS_NETWORK_FDDI,	1, "fddi"},
4956 	{PCIC_NETWORK,		PCIS_NETWORK_ATM,	1, "ATM"},
4957 	{PCIC_NETWORK,		PCIS_NETWORK_ISDN,	1, "ISDN"},
4958 	{PCIC_DISPLAY,		-1,			1, "display"},
4959 	{PCIC_DISPLAY,		PCIS_DISPLAY_VGA,	1, "VGA"},
4960 	{PCIC_DISPLAY,		PCIS_DISPLAY_XGA,	1, "XGA"},
4961 	{PCIC_DISPLAY,		PCIS_DISPLAY_3D,	1, "3D"},
4962 	{PCIC_MULTIMEDIA,	-1,			1, "multimedia"},
4963 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_VIDEO,	1, "video"},
4964 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_AUDIO,	1, "audio"},
4965 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_TELE,	1, "telephony"},
4966 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_HDA,	1, "HDA"},
4967 	{PCIC_MEMORY,		-1,			1, "memory"},
4968 	{PCIC_MEMORY,		PCIS_MEMORY_RAM,	1, "RAM"},
4969 	{PCIC_MEMORY,		PCIS_MEMORY_FLASH,	1, "flash"},
4970 	{PCIC_BRIDGE,		-1,			1, "bridge"},
4971 	{PCIC_BRIDGE,		PCIS_BRIDGE_HOST,	1, "HOST-PCI"},
4972 	{PCIC_BRIDGE,		PCIS_BRIDGE_ISA,	1, "PCI-ISA"},
4973 	{PCIC_BRIDGE,		PCIS_BRIDGE_EISA,	1, "PCI-EISA"},
4974 	{PCIC_BRIDGE,		PCIS_BRIDGE_MCA,	1, "PCI-MCA"},
4975 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI,	1, "PCI-PCI"},
4976 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCMCIA,	1, "PCI-PCMCIA"},
4977 	{PCIC_BRIDGE,		PCIS_BRIDGE_NUBUS,	1, "PCI-NuBus"},
4978 	{PCIC_BRIDGE,		PCIS_BRIDGE_CARDBUS,	1, "PCI-CardBus"},
4979 	{PCIC_BRIDGE,		PCIS_BRIDGE_RACEWAY,	1, "PCI-RACEway"},
4980 	{PCIC_SIMPLECOMM,	-1,			1, "simple comms"},
4981 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_UART,	1, "UART"},	/* could detect 16550 */
4982 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_PAR,	1, "parallel port"},
4983 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MULSER,	1, "multiport serial"},
4984 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MODEM,	1, "generic modem"},
4985 	{PCIC_BASEPERIPH,	-1,			0, "base peripheral"},
4986 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PIC,	1, "interrupt controller"},
4987 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_DMA,	1, "DMA controller"},
4988 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_TIMER,	1, "timer"},
4989 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RTC,	1, "realtime clock"},
4990 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PCIHOT,	1, "PCI hot-plug controller"},
4991 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_SDHC,	1, "SD host controller"},
4992 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_IOMMU,	1, "IOMMU"},
4993 	{PCIC_INPUTDEV,		-1,			1, "input device"},
4994 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_KEYBOARD,	1, "keyboard"},
4995 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_DIGITIZER,1, "digitizer"},
4996 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_MOUSE,	1, "mouse"},
4997 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_SCANNER,	1, "scanner"},
4998 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_GAMEPORT,	1, "gameport"},
4999 	{PCIC_DOCKING,		-1,			1, "docking station"},
5000 	{PCIC_PROCESSOR,	-1,			1, "processor"},
5001 	{PCIC_SERIALBUS,	-1,			1, "serial bus"},
5002 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FW,	1, "FireWire"},
5003 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_ACCESS,	1, "AccessBus"},
5004 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SSA,	1, "SSA"},
5005 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_USB,	1, "USB"},
5006 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FC,	1, "Fibre Channel"},
5007 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SMBUS,	0, "SMBus"},
5008 	{PCIC_WIRELESS,		-1,			1, "wireless controller"},
5009 	{PCIC_WIRELESS,		PCIS_WIRELESS_IRDA,	1, "iRDA"},
5010 	{PCIC_WIRELESS,		PCIS_WIRELESS_IR,	1, "IR"},
5011 	{PCIC_WIRELESS,		PCIS_WIRELESS_RF,	1, "RF"},
5012 	{PCIC_INTELLIIO,	-1,			1, "intelligent I/O controller"},
5013 	{PCIC_INTELLIIO,	PCIS_INTELLIIO_I2O,	1, "I2O"},
5014 	{PCIC_SATCOM,		-1,			1, "satellite communication"},
5015 	{PCIC_SATCOM,		PCIS_SATCOM_TV,		1, "sat TV"},
5016 	{PCIC_SATCOM,		PCIS_SATCOM_AUDIO,	1, "sat audio"},
5017 	{PCIC_SATCOM,		PCIS_SATCOM_VOICE,	1, "sat voice"},
5018 	{PCIC_SATCOM,		PCIS_SATCOM_DATA,	1, "sat data"},
5019 	{PCIC_CRYPTO,		-1,			1, "encrypt/decrypt"},
5020 	{PCIC_CRYPTO,		PCIS_CRYPTO_NETCOMP,	1, "network/computer crypto"},
5021 	{PCIC_CRYPTO,		PCIS_CRYPTO_ENTERTAIN,	1, "entertainment crypto"},
5022 	{PCIC_DASP,		-1,			0, "dasp"},
5023 	{PCIC_DASP,		PCIS_DASP_DPIO,		1, "DPIO module"},
5024 	{PCIC_DASP,		PCIS_DASP_PERFCNTRS,	1, "performance counters"},
5025 	{PCIC_DASP,		PCIS_DASP_COMM_SYNC,	1, "communication synchronizer"},
5026 	{PCIC_DASP,		PCIS_DASP_MGMT_CARD,	1, "signal processing management"},
5027 	{PCIC_INSTRUMENT,	-1,			0, "non-essential instrumentation"},
5028 	{0, 0, 0,		NULL}
5029 };
5030 
5031 void
5032 pci_probe_nomatch(device_t dev, device_t child)
5033 {
5034 	int i, report;
5035 	const char *cp, *scp;
5036 	char *device;
5037 
5038 	/*
5039 	 * Look for a listing for this device in a loaded device database.
5040 	 */
5041 	report = 1;
5042 	if ((device = pci_describe_device(child)) != NULL) {
5043 		device_printf(dev, "<%s>", device);
5044 		free(device, M_DEVBUF);
5045 	} else {
5046 		/*
5047 		 * Scan the class/subclass descriptions for a general
5048 		 * description.
5049 		 */
5050 		cp = "unknown";
5051 		scp = NULL;
5052 		for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
5053 			if (pci_nomatch_tab[i].class == pci_get_class(child)) {
5054 				if (pci_nomatch_tab[i].subclass == -1) {
5055 					cp = pci_nomatch_tab[i].desc;
5056 					report = pci_nomatch_tab[i].report;
5057 				} else if (pci_nomatch_tab[i].subclass ==
5058 				    pci_get_subclass(child)) {
5059 					scp = pci_nomatch_tab[i].desc;
5060 					report = pci_nomatch_tab[i].report;
5061 				}
5062 			}
5063 		}
5064 		if (report || bootverbose) {
5065 			device_printf(dev, "<%s%s%s>",
5066 			    cp ? cp : "",
5067 			    ((cp != NULL) && (scp != NULL)) ? ", " : "",
5068 			    scp ? scp : "");
5069 		}
5070 	}
5071 	if (report || bootverbose) {
5072 		printf(" at device %d.%d (no driver attached)\n",
5073 		    pci_get_slot(child), pci_get_function(child));
5074 	}
5075 	pci_cfg_save(child, device_get_ivars(child), 1);
5076 }
5077 
5078 void
5079 pci_child_detached(device_t dev, device_t child)
5080 {
5081 	struct pci_devinfo *dinfo;
5082 	struct resource_list *rl;
5083 
5084 	dinfo = device_get_ivars(child);
5085 	rl = &dinfo->resources;
5086 
5087 	/*
5088 	 * Have to deallocate IRQs before releasing any MSI messages and
5089 	 * have to release MSI messages before deallocating any memory
5090 	 * BARs.
5091 	 */
5092 	if (resource_list_release_active(rl, dev, child, SYS_RES_IRQ) != 0)
5093 		pci_printf(&dinfo->cfg, "Device leaked IRQ resources\n");
5094 	if (dinfo->cfg.msi.msi_alloc != 0 || dinfo->cfg.msix.msix_alloc != 0) {
5095 		if (dinfo->cfg.msi.msi_alloc != 0)
5096 			pci_printf(&dinfo->cfg, "Device leaked %d MSI "
5097 			    "vectors\n", dinfo->cfg.msi.msi_alloc);
5098 		else
5099 			pci_printf(&dinfo->cfg, "Device leaked %d MSI-X "
5100 			    "vectors\n", dinfo->cfg.msix.msix_alloc);
5101 		(void)pci_release_msi(child);
5102 	}
5103 	if (resource_list_release_active(rl, dev, child, SYS_RES_MEMORY) != 0)
5104 		pci_printf(&dinfo->cfg, "Device leaked memory resources\n");
5105 	if (resource_list_release_active(rl, dev, child, SYS_RES_IOPORT) != 0)
5106 		pci_printf(&dinfo->cfg, "Device leaked I/O resources\n");
5107 #ifdef PCI_RES_BUS
5108 	if (resource_list_release_active(rl, dev, child, PCI_RES_BUS) != 0)
5109 		pci_printf(&dinfo->cfg, "Device leaked PCI bus numbers\n");
5110 #endif
5111 
5112 	pci_cfg_save(child, dinfo, 1);
5113 }
5114 
5115 /*
5116  * Parse the PCI device database, if loaded, and return a pointer to a
5117  * description of the device.
5118  *
5119  * The database is flat text formatted as follows:
5120  *
5121  * Any line not in a valid format is ignored.
5122  * Lines are terminated with newline '\n' characters.
5123  *
5124  * A VENDOR line consists of the 4 digit (hex) vendor code, a TAB, then
5125  * the vendor name.
5126  *
5127  * A DEVICE line is entered immediately below the corresponding VENDOR ID.
5128  * - devices cannot be listed without a corresponding VENDOR line.
5129  * A DEVICE line consists of a TAB, the 4 digit (hex) device code,
5130  * another TAB, then the device name.
5131  */
5132 
5133 /*
5134  * Assuming (ptr) points to the beginning of a line in the database,
5135  * return the vendor or device and description of the next entry.
5136  * The value of (vendor) or (device) inappropriate for the entry type
5137  * is set to -1.  Returns nonzero at the end of the database.
5138  *
5139  * Note that this is slightly unrobust in the face of corrupt data;
5140  * we attempt to safeguard against this by spamming the end of the
5141  * database with a newline when we initialise.
5142  */
5143 static int
5144 pci_describe_parse_line(char **ptr, int *vendor, int *device, char **desc)
5145 {
5146 	char	*cp = *ptr;
5147 	int	left;
5148 
5149 	*device = -1;
5150 	*vendor = -1;
5151 	**desc = '\0';
5152 	for (;;) {
5153 		left = pci_vendordata_size - (cp - pci_vendordata);
5154 		if (left <= 0) {
5155 			*ptr = cp;
5156 			return(1);
5157 		}
5158 
5159 		/* vendor entry? */
5160 		if (*cp != '\t' &&
5161 		    sscanf(cp, "%x\t%80[^\n]", vendor, *desc) == 2)
5162 			break;
5163 		/* device entry? */
5164 		if (*cp == '\t' &&
5165 		    sscanf(cp, "%x\t%80[^\n]", device, *desc) == 2)
5166 			break;
5167 
5168 		/* skip to next line */
5169 		while (*cp != '\n' && left > 0) {
5170 			cp++;
5171 			left--;
5172 		}
5173 		if (*cp == '\n') {
5174 			cp++;
5175 			left--;
5176 		}
5177 	}
5178 	/* skip to next line */
5179 	while (*cp != '\n' && left > 0) {
5180 		cp++;
5181 		left--;
5182 	}
5183 	if (*cp == '\n' && left > 0)
5184 		cp++;
5185 	*ptr = cp;
5186 	return(0);
5187 }
5188 
5189 static char *
5190 pci_describe_device(device_t dev)
5191 {
5192 	int	vendor, device;
5193 	char	*desc, *vp, *dp, *line;
5194 
5195 	desc = vp = dp = NULL;
5196 
5197 	/*
5198 	 * If we have no vendor data, we can't do anything.
5199 	 */
5200 	if (pci_vendordata == NULL)
5201 		goto out;
5202 
5203 	/*
5204 	 * Scan the vendor data looking for this device
5205 	 */
5206 	line = pci_vendordata;
5207 	if ((vp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
5208 		goto out;
5209 	for (;;) {
5210 		if (pci_describe_parse_line(&line, &vendor, &device, &vp))
5211 			goto out;
5212 		if (vendor == pci_get_vendor(dev))
5213 			break;
5214 	}
5215 	if ((dp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
5216 		goto out;
5217 	for (;;) {
5218 		if (pci_describe_parse_line(&line, &vendor, &device, &dp)) {
5219 			*dp = 0;
5220 			break;
5221 		}
5222 		if (vendor != -1) {
5223 			*dp = 0;
5224 			break;
5225 		}
5226 		if (device == pci_get_device(dev))
5227 			break;
5228 	}
5229 	if (dp[0] == '\0')
5230 		snprintf(dp, 80, "0x%x", pci_get_device(dev));
5231 	if ((desc = malloc(strlen(vp) + strlen(dp) + 3, M_DEVBUF, M_NOWAIT)) !=
5232 	    NULL)
5233 		sprintf(desc, "%s, %s", vp, dp);
5234 out:
5235 	if (vp != NULL)
5236 		free(vp, M_DEVBUF);
5237 	if (dp != NULL)
5238 		free(dp, M_DEVBUF);
5239 	return(desc);
5240 }
5241 
5242 int
5243 pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
5244 {
5245 	struct pci_devinfo *dinfo;
5246 	pcicfgregs *cfg;
5247 
5248 	dinfo = device_get_ivars(child);
5249 	cfg = &dinfo->cfg;
5250 
5251 	switch (which) {
5252 	case PCI_IVAR_ETHADDR:
5253 		/*
5254 		 * The generic accessor doesn't deal with failure, so
5255 		 * we set the return value, then return an error.
5256 		 */
5257 		*((uint8_t **) result) = NULL;
5258 		return (EINVAL);
5259 	case PCI_IVAR_SUBVENDOR:
5260 		*result = cfg->subvendor;
5261 		break;
5262 	case PCI_IVAR_SUBDEVICE:
5263 		*result = cfg->subdevice;
5264 		break;
5265 	case PCI_IVAR_VENDOR:
5266 		*result = cfg->vendor;
5267 		break;
5268 	case PCI_IVAR_DEVICE:
5269 		*result = cfg->device;
5270 		break;
5271 	case PCI_IVAR_DEVID:
5272 		*result = (cfg->device << 16) | cfg->vendor;
5273 		break;
5274 	case PCI_IVAR_CLASS:
5275 		*result = cfg->baseclass;
5276 		break;
5277 	case PCI_IVAR_SUBCLASS:
5278 		*result = cfg->subclass;
5279 		break;
5280 	case PCI_IVAR_PROGIF:
5281 		*result = cfg->progif;
5282 		break;
5283 	case PCI_IVAR_REVID:
5284 		*result = cfg->revid;
5285 		break;
5286 	case PCI_IVAR_INTPIN:
5287 		*result = cfg->intpin;
5288 		break;
5289 	case PCI_IVAR_IRQ:
5290 		*result = cfg->intline;
5291 		break;
5292 	case PCI_IVAR_DOMAIN:
5293 		*result = cfg->domain;
5294 		break;
5295 	case PCI_IVAR_BUS:
5296 		*result = cfg->bus;
5297 		break;
5298 	case PCI_IVAR_SLOT:
5299 		*result = cfg->slot;
5300 		break;
5301 	case PCI_IVAR_FUNCTION:
5302 		*result = cfg->func;
5303 		break;
5304 	case PCI_IVAR_CMDREG:
5305 		*result = cfg->cmdreg;
5306 		break;
5307 	case PCI_IVAR_CACHELNSZ:
5308 		*result = cfg->cachelnsz;
5309 		break;
5310 	case PCI_IVAR_MINGNT:
5311 		if (cfg->hdrtype != PCIM_HDRTYPE_NORMAL) {
5312 			*result = -1;
5313 			return (EINVAL);
5314 		}
5315 		*result = cfg->mingnt;
5316 		break;
5317 	case PCI_IVAR_MAXLAT:
5318 		if (cfg->hdrtype != PCIM_HDRTYPE_NORMAL) {
5319 			*result = -1;
5320 			return (EINVAL);
5321 		}
5322 		*result = cfg->maxlat;
5323 		break;
5324 	case PCI_IVAR_LATTIMER:
5325 		*result = cfg->lattimer;
5326 		break;
5327 	default:
5328 		return (ENOENT);
5329 	}
5330 	return (0);
5331 }
5332 
5333 int
5334 pci_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
5335 {
5336 	struct pci_devinfo *dinfo;
5337 
5338 	dinfo = device_get_ivars(child);
5339 
5340 	switch (which) {
5341 	case PCI_IVAR_INTPIN:
5342 		dinfo->cfg.intpin = value;
5343 		return (0);
5344 	case PCI_IVAR_ETHADDR:
5345 	case PCI_IVAR_SUBVENDOR:
5346 	case PCI_IVAR_SUBDEVICE:
5347 	case PCI_IVAR_VENDOR:
5348 	case PCI_IVAR_DEVICE:
5349 	case PCI_IVAR_DEVID:
5350 	case PCI_IVAR_CLASS:
5351 	case PCI_IVAR_SUBCLASS:
5352 	case PCI_IVAR_PROGIF:
5353 	case PCI_IVAR_REVID:
5354 	case PCI_IVAR_IRQ:
5355 	case PCI_IVAR_DOMAIN:
5356 	case PCI_IVAR_BUS:
5357 	case PCI_IVAR_SLOT:
5358 	case PCI_IVAR_FUNCTION:
5359 		return (EINVAL);	/* disallow for now */
5360 
5361 	default:
5362 		return (ENOENT);
5363 	}
5364 }
5365 
5366 #include "opt_ddb.h"
5367 #ifdef DDB
5368 #include <ddb/ddb.h>
5369 #include <sys/cons.h>
5370 
5371 /*
5372  * List resources based on pci map registers, used for within ddb
5373  */
5374 
5375 DB_SHOW_COMMAND_FLAGS(pciregs, db_pci_dump, DB_CMD_MEMSAFE)
5376 {
5377 	struct pci_devinfo *dinfo;
5378 	struct devlist *devlist_head;
5379 	struct pci_conf *p;
5380 	const char *name;
5381 	int i, error, none_count;
5382 
5383 	none_count = 0;
5384 	/* get the head of the device queue */
5385 	devlist_head = &pci_devq;
5386 
5387 	/*
5388 	 * Go through the list of devices and print out devices
5389 	 */
5390 	for (error = 0, i = 0,
5391 	     dinfo = STAILQ_FIRST(devlist_head);
5392 	     (dinfo != NULL) && (error == 0) && (i < pci_numdevs) && !db_pager_quit;
5393 	     dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {
5394 		/* Populate pd_name and pd_unit */
5395 		name = NULL;
5396 		if (dinfo->cfg.dev)
5397 			name = device_get_name(dinfo->cfg.dev);
5398 
5399 		p = &dinfo->conf;
5400 		db_printf("%s%d@pci%d:%d:%d:%d:\tclass=0x%06x card=0x%08x "
5401 			"chip=0x%08x rev=0x%02x hdr=0x%02x\n",
5402 			(name && *name) ? name : "none",
5403 			(name && *name) ? (int)device_get_unit(dinfo->cfg.dev) :
5404 			none_count++,
5405 			p->pc_sel.pc_domain, p->pc_sel.pc_bus, p->pc_sel.pc_dev,
5406 			p->pc_sel.pc_func, (p->pc_class << 16) |
5407 			(p->pc_subclass << 8) | p->pc_progif,
5408 			(p->pc_subdevice << 16) | p->pc_subvendor,
5409 			(p->pc_device << 16) | p->pc_vendor,
5410 			p->pc_revid, p->pc_hdr);
5411 	}
5412 }
5413 #endif /* DDB */
5414 
5415 struct resource *
5416 pci_reserve_map(device_t dev, device_t child, int type, int *rid,
5417     rman_res_t start, rman_res_t end, rman_res_t count, u_int num,
5418     u_int flags)
5419 {
5420 	struct pci_devinfo *dinfo = device_get_ivars(child);
5421 	struct resource_list *rl = &dinfo->resources;
5422 	struct resource *res;
5423 	struct pci_map *pm;
5424 	uint16_t cmd;
5425 	pci_addr_t map, testval;
5426 	int mapsize;
5427 
5428 	res = NULL;
5429 
5430 	/* If rid is managed by EA, ignore it */
5431 	if (pci_ea_is_enabled(child, *rid))
5432 		goto out;
5433 
5434 	pm = pci_find_bar(child, *rid);
5435 	if (pm != NULL) {
5436 		/* This is a BAR that we failed to allocate earlier. */
5437 		mapsize = pm->pm_size;
5438 		map = pm->pm_value;
5439 	} else {
5440 		/*
5441 		 * Weed out the bogons, and figure out how large the
5442 		 * BAR/map is.  BARs that read back 0 here are bogus
5443 		 * and unimplemented.  Note: atapci in legacy mode are
5444 		 * special and handled elsewhere in the code.  If you
5445 		 * have a atapci device in legacy mode and it fails
5446 		 * here, that other code is broken.
5447 		 */
5448 		pci_read_bar(child, *rid, &map, &testval, NULL);
5449 
5450 		/*
5451 		 * Determine the size of the BAR and ignore BARs with a size
5452 		 * of 0.  Device ROM BARs use a different mask value.
5453 		 */
5454 		if (PCIR_IS_BIOS(&dinfo->cfg, *rid))
5455 			mapsize = pci_romsize(testval);
5456 		else
5457 			mapsize = pci_mapsize(testval);
5458 		if (mapsize == 0)
5459 			goto out;
5460 		pm = pci_add_bar(child, *rid, map, mapsize);
5461 	}
5462 
5463 	if (PCI_BAR_MEM(map) || PCIR_IS_BIOS(&dinfo->cfg, *rid)) {
5464 		if (type != SYS_RES_MEMORY) {
5465 			if (bootverbose)
5466 				device_printf(dev,
5467 				    "child %s requested type %d for rid %#x,"
5468 				    " but the BAR says it is an memio\n",
5469 				    device_get_nameunit(child), type, *rid);
5470 			goto out;
5471 		}
5472 	} else {
5473 		if (type != SYS_RES_IOPORT) {
5474 			if (bootverbose)
5475 				device_printf(dev,
5476 				    "child %s requested type %d for rid %#x,"
5477 				    " but the BAR says it is an ioport\n",
5478 				    device_get_nameunit(child), type, *rid);
5479 			goto out;
5480 		}
5481 	}
5482 
5483 	/*
5484 	 * For real BARs, we need to override the size that
5485 	 * the driver requests, because that's what the BAR
5486 	 * actually uses and we would otherwise have a
5487 	 * situation where we might allocate the excess to
5488 	 * another driver, which won't work.
5489 	 */
5490 	count = ((pci_addr_t)1 << mapsize) * num;
5491 	if (RF_ALIGNMENT(flags) < mapsize)
5492 		flags = (flags & ~RF_ALIGNMENT_MASK) | RF_ALIGNMENT_LOG2(mapsize);
5493 	if (PCI_BAR_MEM(map) && (map & PCIM_BAR_MEM_PREFETCH))
5494 		flags |= RF_PREFETCHABLE;
5495 
5496 	/*
5497 	 * Allocate enough resource, and then write back the
5498 	 * appropriate BAR for that resource.
5499 	 */
5500 	resource_list_add(rl, type, *rid, start, end, count);
5501 	res = resource_list_reserve(rl, dev, child, type, rid, start, end,
5502 	    count, flags & ~RF_ACTIVE);
5503 	if (res == NULL) {
5504 		resource_list_delete(rl, type, *rid);
5505 		device_printf(child,
5506 		    "%#jx bytes of rid %#x res %d failed (%#jx, %#jx).\n",
5507 		    count, *rid, type, start, end);
5508 		goto out;
5509 	}
5510 	if (bootverbose)
5511 		device_printf(child,
5512 		    "Lazy allocation of %#jx bytes rid %#x type %d at %#jx\n",
5513 		    count, *rid, type, rman_get_start(res));
5514 
5515 	/* Disable decoding via the CMD register before updating the BAR */
5516 	cmd = pci_read_config(child, PCIR_COMMAND, 2);
5517 	pci_write_config(child, PCIR_COMMAND,
5518 	    cmd & ~(PCI_BAR_MEM(map) ? PCIM_CMD_MEMEN : PCIM_CMD_PORTEN), 2);
5519 
5520 	map = rman_get_start(res);
5521 	pci_write_bar(child, pm, map);
5522 
5523 	/* Restore the original value of the CMD register */
5524 	pci_write_config(child, PCIR_COMMAND, cmd, 2);
5525 out:
5526 	return (res);
5527 }
5528 
5529 struct resource *
5530 pci_alloc_multi_resource(device_t dev, device_t child, int type, int *rid,
5531     rman_res_t start, rman_res_t end, rman_res_t count, u_long num,
5532     u_int flags)
5533 {
5534 	struct pci_devinfo *dinfo;
5535 	struct resource_list *rl;
5536 	struct resource_list_entry *rle;
5537 	struct resource *res;
5538 	pcicfgregs *cfg;
5539 
5540 	/*
5541 	 * Perform lazy resource allocation
5542 	 */
5543 	dinfo = device_get_ivars(child);
5544 	rl = &dinfo->resources;
5545 	cfg = &dinfo->cfg;
5546 	switch (type) {
5547 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
5548 	case PCI_RES_BUS:
5549 		return (pci_alloc_secbus(dev, child, rid, start, end, count,
5550 		    flags));
5551 #endif
5552 	case SYS_RES_IRQ:
5553 		/*
5554 		 * Can't alloc legacy interrupt once MSI messages have
5555 		 * been allocated.
5556 		 */
5557 		if (*rid == 0 && (cfg->msi.msi_alloc > 0 ||
5558 		    cfg->msix.msix_alloc > 0))
5559 			return (NULL);
5560 
5561 		/*
5562 		 * If the child device doesn't have an interrupt
5563 		 * routed and is deserving of an interrupt, try to
5564 		 * assign it one.
5565 		 */
5566 		if (*rid == 0 && !PCI_INTERRUPT_VALID(cfg->intline) &&
5567 		    (cfg->intpin != 0))
5568 			pci_assign_interrupt(dev, child, 0);
5569 		break;
5570 	case SYS_RES_IOPORT:
5571 	case SYS_RES_MEMORY:
5572 #ifdef NEW_PCIB
5573 		/*
5574 		 * PCI-PCI bridge I/O window resources are not BARs.
5575 		 * For those allocations just pass the request up the
5576 		 * tree.
5577 		 */
5578 		if (cfg->hdrtype == PCIM_HDRTYPE_BRIDGE) {
5579 			switch (*rid) {
5580 			case PCIR_IOBASEL_1:
5581 			case PCIR_MEMBASE_1:
5582 			case PCIR_PMBASEL_1:
5583 				/*
5584 				 * XXX: Should we bother creating a resource
5585 				 * list entry?
5586 				 */
5587 				return (bus_generic_alloc_resource(dev, child,
5588 				    type, rid, start, end, count, flags));
5589 			}
5590 		}
5591 #endif
5592 		/* Reserve resources for this BAR if needed. */
5593 		rle = resource_list_find(rl, type, *rid);
5594 		if (rle == NULL) {
5595 			res = pci_reserve_map(dev, child, type, rid, start, end,
5596 			    count, num, flags);
5597 			if (res == NULL)
5598 				return (NULL);
5599 		}
5600 	}
5601 	return (resource_list_alloc(rl, dev, child, type, rid,
5602 	    start, end, count, flags));
5603 }
5604 
5605 struct resource *
5606 pci_alloc_resource(device_t dev, device_t child, int type, int *rid,
5607     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
5608 {
5609 #ifdef PCI_IOV
5610 	struct pci_devinfo *dinfo;
5611 #endif
5612 
5613 	if (device_get_parent(child) != dev)
5614 		return (BUS_ALLOC_RESOURCE(device_get_parent(dev), child,
5615 		    type, rid, start, end, count, flags));
5616 
5617 #ifdef PCI_IOV
5618 	dinfo = device_get_ivars(child);
5619 	if (dinfo->cfg.flags & PCICFG_VF) {
5620 		switch (type) {
5621 		/* VFs can't have I/O BARs. */
5622 		case SYS_RES_IOPORT:
5623 			return (NULL);
5624 		case SYS_RES_MEMORY:
5625 			return (pci_vf_alloc_mem_resource(dev, child, rid,
5626 			    start, end, count, flags));
5627 		}
5628 
5629 		/* Fall through for other types of resource allocations. */
5630 	}
5631 #endif
5632 
5633 	return (pci_alloc_multi_resource(dev, child, type, rid, start, end,
5634 	    count, 1, flags));
5635 }
5636 
5637 int
5638 pci_release_resource(device_t dev, device_t child, int type, int rid,
5639     struct resource *r)
5640 {
5641 	struct pci_devinfo *dinfo;
5642 	struct resource_list *rl;
5643 	pcicfgregs *cfg __unused;
5644 
5645 	if (device_get_parent(child) != dev)
5646 		return (BUS_RELEASE_RESOURCE(device_get_parent(dev), child,
5647 		    type, rid, r));
5648 
5649 	dinfo = device_get_ivars(child);
5650 	cfg = &dinfo->cfg;
5651 
5652 #ifdef PCI_IOV
5653 	if (cfg->flags & PCICFG_VF) {
5654 		switch (type) {
5655 		/* VFs can't have I/O BARs. */
5656 		case SYS_RES_IOPORT:
5657 			return (EDOOFUS);
5658 		case SYS_RES_MEMORY:
5659 			return (pci_vf_release_mem_resource(dev, child, rid,
5660 			    r));
5661 		}
5662 
5663 		/* Fall through for other types of resource allocations. */
5664 	}
5665 #endif
5666 
5667 #ifdef NEW_PCIB
5668 	/*
5669 	 * PCI-PCI bridge I/O window resources are not BARs.  For
5670 	 * those allocations just pass the request up the tree.
5671 	 */
5672 	if (cfg->hdrtype == PCIM_HDRTYPE_BRIDGE &&
5673 	    (type == SYS_RES_IOPORT || type == SYS_RES_MEMORY)) {
5674 		switch (rid) {
5675 		case PCIR_IOBASEL_1:
5676 		case PCIR_MEMBASE_1:
5677 		case PCIR_PMBASEL_1:
5678 			return (bus_generic_release_resource(dev, child, type,
5679 			    rid, r));
5680 		}
5681 	}
5682 #endif
5683 
5684 	rl = &dinfo->resources;
5685 	return (resource_list_release(rl, dev, child, type, rid, r));
5686 }
5687 
5688 int
5689 pci_activate_resource(device_t dev, device_t child, int type, int rid,
5690     struct resource *r)
5691 {
5692 	struct pci_devinfo *dinfo;
5693 	int error;
5694 
5695 	error = bus_generic_activate_resource(dev, child, type, rid, r);
5696 	if (error)
5697 		return (error);
5698 
5699 	/* Enable decoding in the command register when activating BARs. */
5700 	if (device_get_parent(child) == dev) {
5701 		/* Device ROMs need their decoding explicitly enabled. */
5702 		dinfo = device_get_ivars(child);
5703 		if (type == SYS_RES_MEMORY && PCIR_IS_BIOS(&dinfo->cfg, rid))
5704 			pci_write_bar(child, pci_find_bar(child, rid),
5705 			    rman_get_start(r) | PCIM_BIOS_ENABLE);
5706 		switch (type) {
5707 		case SYS_RES_IOPORT:
5708 		case SYS_RES_MEMORY:
5709 			error = PCI_ENABLE_IO(dev, child, type);
5710 			break;
5711 		}
5712 	}
5713 	return (error);
5714 }
5715 
5716 int
5717 pci_deactivate_resource(device_t dev, device_t child, int type,
5718     int rid, struct resource *r)
5719 {
5720 	struct pci_devinfo *dinfo;
5721 	int error;
5722 
5723 	error = bus_generic_deactivate_resource(dev, child, type, rid, r);
5724 	if (error)
5725 		return (error);
5726 
5727 	/* Disable decoding for device ROMs. */
5728 	if (device_get_parent(child) == dev) {
5729 		dinfo = device_get_ivars(child);
5730 		if (type == SYS_RES_MEMORY && PCIR_IS_BIOS(&dinfo->cfg, rid))
5731 			pci_write_bar(child, pci_find_bar(child, rid),
5732 			    rman_get_start(r));
5733 	}
5734 	return (0);
5735 }
5736 
5737 void
5738 pci_child_deleted(device_t dev, device_t child)
5739 {
5740 	struct resource_list_entry *rle;
5741 	struct resource_list *rl;
5742 	struct pci_devinfo *dinfo;
5743 
5744 	dinfo = device_get_ivars(child);
5745 	rl = &dinfo->resources;
5746 
5747 	EVENTHANDLER_INVOKE(pci_delete_device, child);
5748 
5749 	/* Turn off access to resources we're about to free */
5750 	if (bus_child_present(child) != 0) {
5751 		pci_write_config(child, PCIR_COMMAND, pci_read_config(child,
5752 		    PCIR_COMMAND, 2) & ~(PCIM_CMD_MEMEN | PCIM_CMD_PORTEN), 2);
5753 
5754 		pci_disable_busmaster(child);
5755 	}
5756 
5757 	/* Free all allocated resources */
5758 	STAILQ_FOREACH(rle, rl, link) {
5759 		if (rle->res) {
5760 			if (rman_get_flags(rle->res) & RF_ACTIVE ||
5761 			    resource_list_busy(rl, rle->type, rle->rid)) {
5762 				pci_printf(&dinfo->cfg,
5763 				    "Resource still owned, oops. "
5764 				    "(type=%d, rid=%d, addr=%lx)\n",
5765 				    rle->type, rle->rid,
5766 				    rman_get_start(rle->res));
5767 				bus_release_resource(child, rle->type, rle->rid,
5768 				    rle->res);
5769 			}
5770 			resource_list_unreserve(rl, dev, child, rle->type,
5771 			    rle->rid);
5772 		}
5773 	}
5774 	resource_list_free(rl);
5775 
5776 	pci_freecfg(dinfo);
5777 }
5778 
5779 void
5780 pci_delete_resource(device_t dev, device_t child, int type, int rid)
5781 {
5782 	struct pci_devinfo *dinfo;
5783 	struct resource_list *rl;
5784 	struct resource_list_entry *rle;
5785 
5786 	if (device_get_parent(child) != dev)
5787 		return;
5788 
5789 	dinfo = device_get_ivars(child);
5790 	rl = &dinfo->resources;
5791 	rle = resource_list_find(rl, type, rid);
5792 	if (rle == NULL)
5793 		return;
5794 
5795 	if (rle->res) {
5796 		if (rman_get_flags(rle->res) & RF_ACTIVE ||
5797 		    resource_list_busy(rl, type, rid)) {
5798 			device_printf(dev, "delete_resource: "
5799 			    "Resource still owned by child, oops. "
5800 			    "(type=%d, rid=%d, addr=%jx)\n",
5801 			    type, rid, rman_get_start(rle->res));
5802 			return;
5803 		}
5804 		resource_list_unreserve(rl, dev, child, type, rid);
5805 	}
5806 	resource_list_delete(rl, type, rid);
5807 }
5808 
5809 struct resource_list *
5810 pci_get_resource_list (device_t dev, device_t child)
5811 {
5812 	struct pci_devinfo *dinfo = device_get_ivars(child);
5813 
5814 	return (&dinfo->resources);
5815 }
5816 
5817 #ifdef IOMMU
5818 bus_dma_tag_t
5819 pci_get_dma_tag(device_t bus, device_t dev)
5820 {
5821 	bus_dma_tag_t tag;
5822 	struct pci_softc *sc;
5823 
5824 	if (device_get_parent(dev) == bus) {
5825 		/* try iommu and return if it works */
5826 		tag = iommu_get_dma_tag(bus, dev);
5827 	} else
5828 		tag = NULL;
5829 	if (tag == NULL) {
5830 		sc = device_get_softc(bus);
5831 		tag = sc->sc_dma_tag;
5832 	}
5833 	return (tag);
5834 }
5835 #else
5836 bus_dma_tag_t
5837 pci_get_dma_tag(device_t bus, device_t dev)
5838 {
5839 	struct pci_softc *sc = device_get_softc(bus);
5840 
5841 	return (sc->sc_dma_tag);
5842 }
5843 #endif
5844 
5845 uint32_t
5846 pci_read_config_method(device_t dev, device_t child, int reg, int width)
5847 {
5848 	struct pci_devinfo *dinfo = device_get_ivars(child);
5849 	pcicfgregs *cfg = &dinfo->cfg;
5850 
5851 #ifdef PCI_IOV
5852 	/*
5853 	 * SR-IOV VFs don't implement the VID or DID registers, so we have to
5854 	 * emulate them here.
5855 	 */
5856 	if (cfg->flags & PCICFG_VF) {
5857 		if (reg == PCIR_VENDOR) {
5858 			switch (width) {
5859 			case 4:
5860 				return (cfg->device << 16 | cfg->vendor);
5861 			case 2:
5862 				return (cfg->vendor);
5863 			case 1:
5864 				return (cfg->vendor & 0xff);
5865 			default:
5866 				return (0xffffffff);
5867 			}
5868 		} else if (reg == PCIR_DEVICE) {
5869 			switch (width) {
5870 			/* Note that an unaligned 4-byte read is an error. */
5871 			case 2:
5872 				return (cfg->device);
5873 			case 1:
5874 				return (cfg->device & 0xff);
5875 			default:
5876 				return (0xffffffff);
5877 			}
5878 		}
5879 	}
5880 #endif
5881 
5882 	return (PCIB_READ_CONFIG(device_get_parent(dev),
5883 	    cfg->bus, cfg->slot, cfg->func, reg, width));
5884 }
5885 
5886 void
5887 pci_write_config_method(device_t dev, device_t child, int reg,
5888     uint32_t val, int width)
5889 {
5890 	struct pci_devinfo *dinfo = device_get_ivars(child);
5891 	pcicfgregs *cfg = &dinfo->cfg;
5892 
5893 	PCIB_WRITE_CONFIG(device_get_parent(dev),
5894 	    cfg->bus, cfg->slot, cfg->func, reg, val, width);
5895 }
5896 
5897 int
5898 pci_child_location_method(device_t dev, device_t child, struct sbuf *sb)
5899 {
5900 
5901 	sbuf_printf(sb, "slot=%d function=%d dbsf=pci%d:%d:%d:%d",
5902 	    pci_get_slot(child), pci_get_function(child), pci_get_domain(child),
5903 	    pci_get_bus(child), pci_get_slot(child), pci_get_function(child));
5904 	return (0);
5905 }
5906 
5907 int
5908 pci_child_pnpinfo_method(device_t dev, device_t child, struct sbuf *sb)
5909 {
5910 	struct pci_devinfo *dinfo;
5911 	pcicfgregs *cfg;
5912 
5913 	dinfo = device_get_ivars(child);
5914 	cfg = &dinfo->cfg;
5915 	sbuf_printf(sb, "vendor=0x%04x device=0x%04x subvendor=0x%04x "
5916 	    "subdevice=0x%04x class=0x%02x%02x%02x", cfg->vendor, cfg->device,
5917 	    cfg->subvendor, cfg->subdevice, cfg->baseclass, cfg->subclass,
5918 	    cfg->progif);
5919 	return (0);
5920 }
5921 
5922 int
5923 pci_get_device_path_method(device_t bus, device_t child, const char *locator,
5924     struct sbuf *sb)
5925 {
5926 	device_t parent = device_get_parent(bus);
5927 	int rv;
5928 
5929 	if (strcmp(locator, BUS_LOCATOR_UEFI) == 0) {
5930 		rv = bus_generic_get_device_path(parent, bus, locator, sb);
5931 		if (rv == 0) {
5932 			sbuf_printf(sb, "/Pci(0x%x,0x%x)", pci_get_slot(child),
5933 			    pci_get_function(child));
5934 		}
5935 		return (0);
5936 	}
5937 	return (bus_generic_get_device_path(bus, child, locator, sb));
5938 }
5939 
5940 int
5941 pci_assign_interrupt_method(device_t dev, device_t child)
5942 {
5943 	struct pci_devinfo *dinfo = device_get_ivars(child);
5944 	pcicfgregs *cfg = &dinfo->cfg;
5945 
5946 	return (PCIB_ROUTE_INTERRUPT(device_get_parent(dev), child,
5947 	    cfg->intpin));
5948 }
5949 
5950 static void
5951 pci_lookup(void *arg, const char *name, device_t *dev)
5952 {
5953 	long val;
5954 	char *end;
5955 	int domain, bus, slot, func;
5956 
5957 	if (*dev != NULL)
5958 		return;
5959 
5960 	/*
5961 	 * Accept pciconf-style selectors of either pciD:B:S:F or
5962 	 * pciB:S:F.  In the latter case, the domain is assumed to
5963 	 * be zero.
5964 	 */
5965 	if (strncmp(name, "pci", 3) != 0)
5966 		return;
5967 	val = strtol(name + 3, &end, 10);
5968 	if (val < 0 || val > INT_MAX || *end != ':')
5969 		return;
5970 	domain = val;
5971 	val = strtol(end + 1, &end, 10);
5972 	if (val < 0 || val > INT_MAX || *end != ':')
5973 		return;
5974 	bus = val;
5975 	val = strtol(end + 1, &end, 10);
5976 	if (val < 0 || val > INT_MAX)
5977 		return;
5978 	slot = val;
5979 	if (*end == ':') {
5980 		val = strtol(end + 1, &end, 10);
5981 		if (val < 0 || val > INT_MAX || *end != '\0')
5982 			return;
5983 		func = val;
5984 	} else if (*end == '\0') {
5985 		func = slot;
5986 		slot = bus;
5987 		bus = domain;
5988 		domain = 0;
5989 	} else
5990 		return;
5991 
5992 	if (domain > PCI_DOMAINMAX || bus > PCI_BUSMAX || slot > PCI_SLOTMAX ||
5993 	    func > PCIE_ARI_FUNCMAX || (slot != 0 && func > PCI_FUNCMAX))
5994 		return;
5995 
5996 	*dev = pci_find_dbsf(domain, bus, slot, func);
5997 }
5998 
5999 static int
6000 pci_modevent(module_t mod, int what, void *arg)
6001 {
6002 	static struct cdev *pci_cdev;
6003 	static eventhandler_tag tag;
6004 
6005 	switch (what) {
6006 	case MOD_LOAD:
6007 		STAILQ_INIT(&pci_devq);
6008 		pci_generation = 0;
6009 		pci_cdev = make_dev(&pcicdev, 0, UID_ROOT, GID_WHEEL, 0644,
6010 		    "pci");
6011 		pci_load_vendor_data();
6012 		tag = EVENTHANDLER_REGISTER(dev_lookup, pci_lookup, NULL,
6013 		    1000);
6014 		break;
6015 
6016 	case MOD_UNLOAD:
6017 		if (tag != NULL)
6018 			EVENTHANDLER_DEREGISTER(dev_lookup, tag);
6019 		destroy_dev(pci_cdev);
6020 		break;
6021 	}
6022 
6023 	return (0);
6024 }
6025 
6026 static void
6027 pci_cfg_restore_pcie(device_t dev, struct pci_devinfo *dinfo)
6028 {
6029 #define	WREG(n, v)	pci_write_config(dev, pos + (n), (v), 2)
6030 	struct pcicfg_pcie *cfg;
6031 	int version, pos;
6032 
6033 	cfg = &dinfo->cfg.pcie;
6034 	pos = cfg->pcie_location;
6035 
6036 	version = cfg->pcie_flags & PCIEM_FLAGS_VERSION;
6037 
6038 	WREG(PCIER_DEVICE_CTL, cfg->pcie_device_ctl);
6039 
6040 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
6041 	    cfg->pcie_type == PCIEM_TYPE_ENDPOINT ||
6042 	    cfg->pcie_type == PCIEM_TYPE_LEGACY_ENDPOINT)
6043 		WREG(PCIER_LINK_CTL, cfg->pcie_link_ctl);
6044 
6045 	if (version > 1 || (cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
6046 	    (cfg->pcie_type == PCIEM_TYPE_DOWNSTREAM_PORT &&
6047 	     (cfg->pcie_flags & PCIEM_FLAGS_SLOT))))
6048 		WREG(PCIER_SLOT_CTL, cfg->pcie_slot_ctl);
6049 
6050 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
6051 	    cfg->pcie_type == PCIEM_TYPE_ROOT_EC)
6052 		WREG(PCIER_ROOT_CTL, cfg->pcie_root_ctl);
6053 
6054 	if (version > 1) {
6055 		WREG(PCIER_DEVICE_CTL2, cfg->pcie_device_ctl2);
6056 		WREG(PCIER_LINK_CTL2, cfg->pcie_link_ctl2);
6057 		WREG(PCIER_SLOT_CTL2, cfg->pcie_slot_ctl2);
6058 	}
6059 #undef WREG
6060 }
6061 
6062 static void
6063 pci_cfg_restore_pcix(device_t dev, struct pci_devinfo *dinfo)
6064 {
6065 	pci_write_config(dev, dinfo->cfg.pcix.pcix_location + PCIXR_COMMAND,
6066 	    dinfo->cfg.pcix.pcix_command,  2);
6067 }
6068 
6069 void
6070 pci_cfg_restore(device_t dev, struct pci_devinfo *dinfo)
6071 {
6072 
6073 	/*
6074 	 * Restore the device to full power mode.  We must do this
6075 	 * before we restore the registers because moving from D3 to
6076 	 * D0 will cause the chip's BARs and some other registers to
6077 	 * be reset to some unknown power on reset values.  Cut down
6078 	 * the noise on boot by doing nothing if we are already in
6079 	 * state D0.
6080 	 */
6081 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0)
6082 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
6083 	pci_write_config(dev, PCIR_INTLINE, dinfo->cfg.intline, 1);
6084 	pci_write_config(dev, PCIR_INTPIN, dinfo->cfg.intpin, 1);
6085 	pci_write_config(dev, PCIR_CACHELNSZ, dinfo->cfg.cachelnsz, 1);
6086 	pci_write_config(dev, PCIR_LATTIMER, dinfo->cfg.lattimer, 1);
6087 	pci_write_config(dev, PCIR_PROGIF, dinfo->cfg.progif, 1);
6088 	pci_write_config(dev, PCIR_REVID, dinfo->cfg.revid, 1);
6089 	switch (dinfo->cfg.hdrtype & PCIM_HDRTYPE) {
6090 	case PCIM_HDRTYPE_NORMAL:
6091 		pci_write_config(dev, PCIR_MINGNT, dinfo->cfg.mingnt, 1);
6092 		pci_write_config(dev, PCIR_MAXLAT, dinfo->cfg.maxlat, 1);
6093 		break;
6094 	case PCIM_HDRTYPE_BRIDGE:
6095 		pci_write_config(dev, PCIR_SECLAT_1,
6096 		    dinfo->cfg.bridge.br_seclat, 1);
6097 		pci_write_config(dev, PCIR_SUBBUS_1,
6098 		    dinfo->cfg.bridge.br_subbus, 1);
6099 		pci_write_config(dev, PCIR_SECBUS_1,
6100 		    dinfo->cfg.bridge.br_secbus, 1);
6101 		pci_write_config(dev, PCIR_PRIBUS_1,
6102 		    dinfo->cfg.bridge.br_pribus, 1);
6103 		pci_write_config(dev, PCIR_BRIDGECTL_1,
6104 		    dinfo->cfg.bridge.br_control, 2);
6105 		break;
6106 	case PCIM_HDRTYPE_CARDBUS:
6107 		pci_write_config(dev, PCIR_SECLAT_2,
6108 		    dinfo->cfg.bridge.br_seclat, 1);
6109 		pci_write_config(dev, PCIR_SUBBUS_2,
6110 		    dinfo->cfg.bridge.br_subbus, 1);
6111 		pci_write_config(dev, PCIR_SECBUS_2,
6112 		    dinfo->cfg.bridge.br_secbus, 1);
6113 		pci_write_config(dev, PCIR_PRIBUS_2,
6114 		    dinfo->cfg.bridge.br_pribus, 1);
6115 		pci_write_config(dev, PCIR_BRIDGECTL_2,
6116 		    dinfo->cfg.bridge.br_control, 2);
6117 		break;
6118 	}
6119 	pci_restore_bars(dev);
6120 
6121 	if ((dinfo->cfg.hdrtype & PCIM_HDRTYPE) != PCIM_HDRTYPE_BRIDGE)
6122 		pci_write_config(dev, PCIR_COMMAND, dinfo->cfg.cmdreg, 2);
6123 
6124 	/*
6125 	 * Restore extended capabilities for PCI-Express and PCI-X
6126 	 */
6127 	if (dinfo->cfg.pcie.pcie_location != 0)
6128 		pci_cfg_restore_pcie(dev, dinfo);
6129 	if (dinfo->cfg.pcix.pcix_location != 0)
6130 		pci_cfg_restore_pcix(dev, dinfo);
6131 
6132 	/* Restore MSI and MSI-X configurations if they are present. */
6133 	if (dinfo->cfg.msi.msi_location != 0)
6134 		pci_resume_msi(dev);
6135 	if (dinfo->cfg.msix.msix_location != 0)
6136 		pci_resume_msix(dev);
6137 
6138 #ifdef PCI_IOV
6139 	if (dinfo->cfg.iov != NULL)
6140 		pci_iov_cfg_restore(dev, dinfo);
6141 #endif
6142 }
6143 
6144 static void
6145 pci_cfg_save_pcie(device_t dev, struct pci_devinfo *dinfo)
6146 {
6147 #define	RREG(n)	pci_read_config(dev, pos + (n), 2)
6148 	struct pcicfg_pcie *cfg;
6149 	int version, pos;
6150 
6151 	cfg = &dinfo->cfg.pcie;
6152 	pos = cfg->pcie_location;
6153 
6154 	cfg->pcie_flags = RREG(PCIER_FLAGS);
6155 
6156 	version = cfg->pcie_flags & PCIEM_FLAGS_VERSION;
6157 
6158 	cfg->pcie_device_ctl = RREG(PCIER_DEVICE_CTL);
6159 
6160 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
6161 	    cfg->pcie_type == PCIEM_TYPE_ENDPOINT ||
6162 	    cfg->pcie_type == PCIEM_TYPE_LEGACY_ENDPOINT)
6163 		cfg->pcie_link_ctl = RREG(PCIER_LINK_CTL);
6164 
6165 	if (version > 1 || (cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
6166 	    (cfg->pcie_type == PCIEM_TYPE_DOWNSTREAM_PORT &&
6167 	     (cfg->pcie_flags & PCIEM_FLAGS_SLOT))))
6168 		cfg->pcie_slot_ctl = RREG(PCIER_SLOT_CTL);
6169 
6170 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
6171 	    cfg->pcie_type == PCIEM_TYPE_ROOT_EC)
6172 		cfg->pcie_root_ctl = RREG(PCIER_ROOT_CTL);
6173 
6174 	if (version > 1) {
6175 		cfg->pcie_device_ctl2 = RREG(PCIER_DEVICE_CTL2);
6176 		cfg->pcie_link_ctl2 = RREG(PCIER_LINK_CTL2);
6177 		cfg->pcie_slot_ctl2 = RREG(PCIER_SLOT_CTL2);
6178 	}
6179 #undef RREG
6180 }
6181 
6182 static void
6183 pci_cfg_save_pcix(device_t dev, struct pci_devinfo *dinfo)
6184 {
6185 	dinfo->cfg.pcix.pcix_command = pci_read_config(dev,
6186 	    dinfo->cfg.pcix.pcix_location + PCIXR_COMMAND, 2);
6187 }
6188 
6189 void
6190 pci_cfg_save(device_t dev, struct pci_devinfo *dinfo, int setstate)
6191 {
6192 	uint32_t cls;
6193 	int ps;
6194 
6195 	/*
6196 	 * Some drivers apparently write to these registers w/o updating our
6197 	 * cached copy.  No harm happens if we update the copy, so do so here
6198 	 * so we can restore them.  The COMMAND register is modified by the
6199 	 * bus w/o updating the cache.  This should represent the normally
6200 	 * writable portion of the 'defined' part of type 0/1/2 headers.
6201 	 */
6202 	dinfo->cfg.vendor = pci_read_config(dev, PCIR_VENDOR, 2);
6203 	dinfo->cfg.device = pci_read_config(dev, PCIR_DEVICE, 2);
6204 	dinfo->cfg.cmdreg = pci_read_config(dev, PCIR_COMMAND, 2);
6205 	dinfo->cfg.intline = pci_read_config(dev, PCIR_INTLINE, 1);
6206 	dinfo->cfg.intpin = pci_read_config(dev, PCIR_INTPIN, 1);
6207 	dinfo->cfg.cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
6208 	dinfo->cfg.lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
6209 	dinfo->cfg.baseclass = pci_read_config(dev, PCIR_CLASS, 1);
6210 	dinfo->cfg.subclass = pci_read_config(dev, PCIR_SUBCLASS, 1);
6211 	dinfo->cfg.progif = pci_read_config(dev, PCIR_PROGIF, 1);
6212 	dinfo->cfg.revid = pci_read_config(dev, PCIR_REVID, 1);
6213 	switch (dinfo->cfg.hdrtype & PCIM_HDRTYPE) {
6214 	case PCIM_HDRTYPE_NORMAL:
6215 		dinfo->cfg.subvendor = pci_read_config(dev, PCIR_SUBVEND_0, 2);
6216 		dinfo->cfg.subdevice = pci_read_config(dev, PCIR_SUBDEV_0, 2);
6217 		dinfo->cfg.mingnt = pci_read_config(dev, PCIR_MINGNT, 1);
6218 		dinfo->cfg.maxlat = pci_read_config(dev, PCIR_MAXLAT, 1);
6219 		break;
6220 	case PCIM_HDRTYPE_BRIDGE:
6221 		dinfo->cfg.bridge.br_seclat = pci_read_config(dev,
6222 		    PCIR_SECLAT_1, 1);
6223 		dinfo->cfg.bridge.br_subbus = pci_read_config(dev,
6224 		    PCIR_SUBBUS_1, 1);
6225 		dinfo->cfg.bridge.br_secbus = pci_read_config(dev,
6226 		    PCIR_SECBUS_1, 1);
6227 		dinfo->cfg.bridge.br_pribus = pci_read_config(dev,
6228 		    PCIR_PRIBUS_1, 1);
6229 		dinfo->cfg.bridge.br_control = pci_read_config(dev,
6230 		    PCIR_BRIDGECTL_1, 2);
6231 		break;
6232 	case PCIM_HDRTYPE_CARDBUS:
6233 		dinfo->cfg.bridge.br_seclat = pci_read_config(dev,
6234 		    PCIR_SECLAT_2, 1);
6235 		dinfo->cfg.bridge.br_subbus = pci_read_config(dev,
6236 		    PCIR_SUBBUS_2, 1);
6237 		dinfo->cfg.bridge.br_secbus = pci_read_config(dev,
6238 		    PCIR_SECBUS_2, 1);
6239 		dinfo->cfg.bridge.br_pribus = pci_read_config(dev,
6240 		    PCIR_PRIBUS_2, 1);
6241 		dinfo->cfg.bridge.br_control = pci_read_config(dev,
6242 		    PCIR_BRIDGECTL_2, 2);
6243 		dinfo->cfg.subvendor = pci_read_config(dev, PCIR_SUBVEND_2, 2);
6244 		dinfo->cfg.subdevice = pci_read_config(dev, PCIR_SUBDEV_2, 2);
6245 		break;
6246 	}
6247 
6248 	if (dinfo->cfg.pcie.pcie_location != 0)
6249 		pci_cfg_save_pcie(dev, dinfo);
6250 
6251 	if (dinfo->cfg.pcix.pcix_location != 0)
6252 		pci_cfg_save_pcix(dev, dinfo);
6253 
6254 #ifdef PCI_IOV
6255 	if (dinfo->cfg.iov != NULL)
6256 		pci_iov_cfg_save(dev, dinfo);
6257 #endif
6258 
6259 	/*
6260 	 * don't set the state for display devices, base peripherals and
6261 	 * memory devices since bad things happen when they are powered down.
6262 	 * We should (a) have drivers that can easily detach and (b) use
6263 	 * generic drivers for these devices so that some device actually
6264 	 * attaches.  We need to make sure that when we implement (a) we don't
6265 	 * power the device down on a reattach.
6266 	 */
6267 	cls = pci_get_class(dev);
6268 	if (!setstate)
6269 		return;
6270 	switch (pci_do_power_nodriver)
6271 	{
6272 		case 0:		/* NO powerdown at all */
6273 			return;
6274 		case 1:		/* Conservative about what to power down */
6275 			if (cls == PCIC_STORAGE)
6276 				return;
6277 			/*FALLTHROUGH*/
6278 		case 2:		/* Aggressive about what to power down */
6279 			if (cls == PCIC_DISPLAY || cls == PCIC_MEMORY ||
6280 			    cls == PCIC_BASEPERIPH)
6281 				return;
6282 			/*FALLTHROUGH*/
6283 		case 3:		/* Power down everything */
6284 			break;
6285 	}
6286 	/*
6287 	 * PCI spec says we can only go into D3 state from D0 state.
6288 	 * Transition from D[12] into D0 before going to D3 state.
6289 	 */
6290 	ps = pci_get_powerstate(dev);
6291 	if (ps != PCI_POWERSTATE_D0 && ps != PCI_POWERSTATE_D3)
6292 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
6293 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D3)
6294 		pci_set_powerstate(dev, PCI_POWERSTATE_D3);
6295 }
6296 
6297 /* Wrapper APIs suitable for device driver use. */
6298 void
6299 pci_save_state(device_t dev)
6300 {
6301 	struct pci_devinfo *dinfo;
6302 
6303 	dinfo = device_get_ivars(dev);
6304 	pci_cfg_save(dev, dinfo, 0);
6305 }
6306 
6307 void
6308 pci_restore_state(device_t dev)
6309 {
6310 	struct pci_devinfo *dinfo;
6311 
6312 	dinfo = device_get_ivars(dev);
6313 	pci_cfg_restore(dev, dinfo);
6314 }
6315 
6316 static int
6317 pci_get_id_method(device_t dev, device_t child, enum pci_id_type type,
6318     uintptr_t *id)
6319 {
6320 
6321 	return (PCIB_GET_ID(device_get_parent(dev), child, type, id));
6322 }
6323 
6324 /* Find the upstream port of a given PCI device in a root complex. */
6325 device_t
6326 pci_find_pcie_root_port(device_t dev)
6327 {
6328 	struct pci_devinfo *dinfo;
6329 	devclass_t pci_class;
6330 	device_t pcib, bus;
6331 
6332 	pci_class = devclass_find("pci");
6333 	KASSERT(device_get_devclass(device_get_parent(dev)) == pci_class,
6334 	    ("%s: non-pci device %s", __func__, device_get_nameunit(dev)));
6335 
6336 	/*
6337 	 * Walk the bridge hierarchy until we find a PCI-e root
6338 	 * port or a non-PCI device.
6339 	 */
6340 	for (;;) {
6341 		bus = device_get_parent(dev);
6342 		KASSERT(bus != NULL, ("%s: null parent of %s", __func__,
6343 		    device_get_nameunit(dev)));
6344 
6345 		pcib = device_get_parent(bus);
6346 		KASSERT(pcib != NULL, ("%s: null bridge of %s", __func__,
6347 		    device_get_nameunit(bus)));
6348 
6349 		/*
6350 		 * pcib's parent must be a PCI bus for this to be a
6351 		 * PCI-PCI bridge.
6352 		 */
6353 		if (device_get_devclass(device_get_parent(pcib)) != pci_class)
6354 			return (NULL);
6355 
6356 		dinfo = device_get_ivars(pcib);
6357 		if (dinfo->cfg.pcie.pcie_location != 0 &&
6358 		    dinfo->cfg.pcie.pcie_type == PCIEM_TYPE_ROOT_PORT)
6359 			return (pcib);
6360 
6361 		dev = pcib;
6362 	}
6363 }
6364 
6365 /*
6366  * Wait for pending transactions to complete on a PCI-express function.
6367  *
6368  * The maximum delay is specified in milliseconds in max_delay.  Note
6369  * that this function may sleep.
6370  *
6371  * Returns true if the function is idle and false if the timeout is
6372  * exceeded.  If dev is not a PCI-express function, this returns true.
6373  */
6374 bool
6375 pcie_wait_for_pending_transactions(device_t dev, u_int max_delay)
6376 {
6377 	struct pci_devinfo *dinfo = device_get_ivars(dev);
6378 	uint16_t sta;
6379 	int cap;
6380 
6381 	cap = dinfo->cfg.pcie.pcie_location;
6382 	if (cap == 0)
6383 		return (true);
6384 
6385 	sta = pci_read_config(dev, cap + PCIER_DEVICE_STA, 2);
6386 	while (sta & PCIEM_STA_TRANSACTION_PND) {
6387 		if (max_delay == 0)
6388 			return (false);
6389 
6390 		/* Poll once every 100 milliseconds up to the timeout. */
6391 		if (max_delay > 100) {
6392 			pause_sbt("pcietp", 100 * SBT_1MS, 0, C_HARDCLOCK);
6393 			max_delay -= 100;
6394 		} else {
6395 			pause_sbt("pcietp", max_delay * SBT_1MS, 0,
6396 			    C_HARDCLOCK);
6397 			max_delay = 0;
6398 		}
6399 		sta = pci_read_config(dev, cap + PCIER_DEVICE_STA, 2);
6400 	}
6401 
6402 	return (true);
6403 }
6404 
6405 /*
6406  * Determine the maximum Completion Timeout in microseconds.
6407  *
6408  * For non-PCI-express functions this returns 0.
6409  */
6410 int
6411 pcie_get_max_completion_timeout(device_t dev)
6412 {
6413 	struct pci_devinfo *dinfo = device_get_ivars(dev);
6414 	int cap;
6415 
6416 	cap = dinfo->cfg.pcie.pcie_location;
6417 	if (cap == 0)
6418 		return (0);
6419 
6420 	/*
6421 	 * Functions using the 1.x spec use the default timeout range of
6422 	 * 50 microseconds to 50 milliseconds.  Functions that do not
6423 	 * support programmable timeouts also use this range.
6424 	 */
6425 	if ((dinfo->cfg.pcie.pcie_flags & PCIEM_FLAGS_VERSION) < 2 ||
6426 	    (pci_read_config(dev, cap + PCIER_DEVICE_CAP2, 4) &
6427 	    PCIEM_CAP2_COMP_TIMO_RANGES) == 0)
6428 		return (50 * 1000);
6429 
6430 	switch (pci_read_config(dev, cap + PCIER_DEVICE_CTL2, 2) &
6431 	    PCIEM_CTL2_COMP_TIMO_VAL) {
6432 	case PCIEM_CTL2_COMP_TIMO_100US:
6433 		return (100);
6434 	case PCIEM_CTL2_COMP_TIMO_10MS:
6435 		return (10 * 1000);
6436 	case PCIEM_CTL2_COMP_TIMO_55MS:
6437 		return (55 * 1000);
6438 	case PCIEM_CTL2_COMP_TIMO_210MS:
6439 		return (210 * 1000);
6440 	case PCIEM_CTL2_COMP_TIMO_900MS:
6441 		return (900 * 1000);
6442 	case PCIEM_CTL2_COMP_TIMO_3500MS:
6443 		return (3500 * 1000);
6444 	case PCIEM_CTL2_COMP_TIMO_13S:
6445 		return (13 * 1000 * 1000);
6446 	case PCIEM_CTL2_COMP_TIMO_64S:
6447 		return (64 * 1000 * 1000);
6448 	default:
6449 		return (50 * 1000);
6450 	}
6451 }
6452 
6453 void
6454 pcie_apei_error(device_t dev, int sev, uint8_t *aerp)
6455 {
6456 	struct pci_devinfo *dinfo = device_get_ivars(dev);
6457 	const char *s;
6458 	int aer;
6459 	uint32_t r, r1;
6460 	uint16_t rs;
6461 
6462 	if (sev == PCIEM_STA_CORRECTABLE_ERROR)
6463 		s = "Correctable";
6464 	else if (sev == PCIEM_STA_NON_FATAL_ERROR)
6465 		s = "Uncorrectable (Non-Fatal)";
6466 	else
6467 		s = "Uncorrectable (Fatal)";
6468 	device_printf(dev, "%s PCIe error reported by APEI\n", s);
6469 	if (aerp) {
6470 		if (sev == PCIEM_STA_CORRECTABLE_ERROR) {
6471 			r = le32dec(aerp + PCIR_AER_COR_STATUS);
6472 			r1 = le32dec(aerp + PCIR_AER_COR_MASK);
6473 		} else {
6474 			r = le32dec(aerp + PCIR_AER_UC_STATUS);
6475 			r1 = le32dec(aerp + PCIR_AER_UC_MASK);
6476 		}
6477 		device_printf(dev, "status 0x%08x mask 0x%08x", r, r1);
6478 		if (sev != PCIEM_STA_CORRECTABLE_ERROR) {
6479 			r = le32dec(aerp + PCIR_AER_UC_SEVERITY);
6480 			rs = le16dec(aerp + PCIR_AER_CAP_CONTROL);
6481 			printf(" severity 0x%08x first %d\n",
6482 			    r, rs & 0x1f);
6483 		} else
6484 			printf("\n");
6485 	}
6486 
6487 	/* As kind of recovery just report and clear the error statuses. */
6488 	if (pci_find_extcap(dev, PCIZ_AER, &aer) == 0) {
6489 		r = pci_read_config(dev, aer + PCIR_AER_UC_STATUS, 4);
6490 		if (r != 0) {
6491 			pci_write_config(dev, aer + PCIR_AER_UC_STATUS, r, 4);
6492 			device_printf(dev, "Clearing UC AER errors 0x%08x\n", r);
6493 		}
6494 
6495 		r = pci_read_config(dev, aer + PCIR_AER_COR_STATUS, 4);
6496 		if (r != 0) {
6497 			pci_write_config(dev, aer + PCIR_AER_COR_STATUS, r, 4);
6498 			device_printf(dev, "Clearing COR AER errors 0x%08x\n", r);
6499 		}
6500 	}
6501 	if (dinfo->cfg.pcie.pcie_location != 0) {
6502 		rs = pci_read_config(dev, dinfo->cfg.pcie.pcie_location +
6503 		    PCIER_DEVICE_STA, 2);
6504 		if ((rs & (PCIEM_STA_CORRECTABLE_ERROR |
6505 		    PCIEM_STA_NON_FATAL_ERROR | PCIEM_STA_FATAL_ERROR |
6506 		    PCIEM_STA_UNSUPPORTED_REQ)) != 0) {
6507 			pci_write_config(dev, dinfo->cfg.pcie.pcie_location +
6508 			    PCIER_DEVICE_STA, rs, 2);
6509 			device_printf(dev, "Clearing PCIe errors 0x%04x\n", rs);
6510 		}
6511 	}
6512 }
6513 
6514 /*
6515  * Perform a Function Level Reset (FLR) on a device.
6516  *
6517  * This function first waits for any pending transactions to complete
6518  * within the timeout specified by max_delay.  If transactions are
6519  * still pending, the function will return false without attempting a
6520  * reset.
6521  *
6522  * If dev is not a PCI-express function or does not support FLR, this
6523  * function returns false.
6524  *
6525  * Note that no registers are saved or restored.  The caller is
6526  * responsible for saving and restoring any registers including
6527  * PCI-standard registers via pci_save_state() and
6528  * pci_restore_state().
6529  */
6530 bool
6531 pcie_flr(device_t dev, u_int max_delay, bool force)
6532 {
6533 	struct pci_devinfo *dinfo = device_get_ivars(dev);
6534 	uint16_t cmd, ctl;
6535 	int compl_delay;
6536 	int cap;
6537 
6538 	cap = dinfo->cfg.pcie.pcie_location;
6539 	if (cap == 0)
6540 		return (false);
6541 
6542 	if (!(pci_read_config(dev, cap + PCIER_DEVICE_CAP, 4) & PCIEM_CAP_FLR))
6543 		return (false);
6544 
6545 	/*
6546 	 * Disable busmastering to prevent generation of new
6547 	 * transactions while waiting for the device to go idle.  If
6548 	 * the idle timeout fails, the command register is restored
6549 	 * which will re-enable busmastering.
6550 	 */
6551 	cmd = pci_read_config(dev, PCIR_COMMAND, 2);
6552 	pci_write_config(dev, PCIR_COMMAND, cmd & ~(PCIM_CMD_BUSMASTEREN), 2);
6553 	if (!pcie_wait_for_pending_transactions(dev, max_delay)) {
6554 		if (!force) {
6555 			pci_write_config(dev, PCIR_COMMAND, cmd, 2);
6556 			return (false);
6557 		}
6558 		pci_printf(&dinfo->cfg,
6559 		    "Resetting with transactions pending after %d ms\n",
6560 		    max_delay);
6561 
6562 		/*
6563 		 * Extend the post-FLR delay to cover the maximum
6564 		 * Completion Timeout delay of anything in flight
6565 		 * during the FLR delay.  Enforce a minimum delay of
6566 		 * at least 10ms.
6567 		 */
6568 		compl_delay = pcie_get_max_completion_timeout(dev) / 1000;
6569 		if (compl_delay < 10)
6570 			compl_delay = 10;
6571 	} else
6572 		compl_delay = 0;
6573 
6574 	/* Initiate the reset. */
6575 	ctl = pci_read_config(dev, cap + PCIER_DEVICE_CTL, 2);
6576 	pci_write_config(dev, cap + PCIER_DEVICE_CTL, ctl |
6577 	    PCIEM_CTL_INITIATE_FLR, 2);
6578 
6579 	/* Wait for 100ms. */
6580 	pause_sbt("pcieflr", (100 + compl_delay) * SBT_1MS, 0, C_HARDCLOCK);
6581 
6582 	if (pci_read_config(dev, cap + PCIER_DEVICE_STA, 2) &
6583 	    PCIEM_STA_TRANSACTION_PND)
6584 		pci_printf(&dinfo->cfg, "Transactions pending after FLR!\n");
6585 	return (true);
6586 }
6587 
6588 /*
6589  * Attempt a power-management reset by cycling the device in/out of D3
6590  * state.  PCI spec says we can only go into D3 state from D0 state.
6591  * Transition from D[12] into D0 before going to D3 state.
6592  */
6593 int
6594 pci_power_reset(device_t dev)
6595 {
6596 	int ps;
6597 
6598 	ps = pci_get_powerstate(dev);
6599 	if (ps != PCI_POWERSTATE_D0 && ps != PCI_POWERSTATE_D3)
6600 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
6601 	pci_set_powerstate(dev, PCI_POWERSTATE_D3);
6602 	pci_set_powerstate(dev, ps);
6603 	return (0);
6604 }
6605 
6606 /*
6607  * Try link drop and retrain of the downstream port of upstream
6608  * switch, for PCIe.  According to the PCIe 3.0 spec 6.6.1, this must
6609  * cause Conventional Hot reset of the device in the slot.
6610  * Alternative, for PCIe, could be the secondary bus reset initiatied
6611  * on the upstream switch PCIR_BRIDGECTL_1, bit 6.
6612  */
6613 int
6614 pcie_link_reset(device_t port, int pcie_location)
6615 {
6616 	uint16_t v;
6617 
6618 	v = pci_read_config(port, pcie_location + PCIER_LINK_CTL, 2);
6619 	v |= PCIEM_LINK_CTL_LINK_DIS;
6620 	pci_write_config(port, pcie_location + PCIER_LINK_CTL, v, 2);
6621 	pause_sbt("pcier1", mstosbt(20), 0, 0);
6622 	v &= ~PCIEM_LINK_CTL_LINK_DIS;
6623 	v |= PCIEM_LINK_CTL_RETRAIN_LINK;
6624 	pci_write_config(port, pcie_location + PCIER_LINK_CTL, v, 2);
6625 	pause_sbt("pcier2", mstosbt(100), 0, 0); /* 100 ms */
6626 	v = pci_read_config(port, pcie_location + PCIER_LINK_STA, 2);
6627 	return ((v & PCIEM_LINK_STA_TRAINING) != 0 ? ETIMEDOUT : 0);
6628 }
6629 
6630 static int
6631 pci_reset_post(device_t dev, device_t child)
6632 {
6633 
6634 	if (dev == device_get_parent(child))
6635 		pci_restore_state(child);
6636 	return (0);
6637 }
6638 
6639 static int
6640 pci_reset_prepare(device_t dev, device_t child)
6641 {
6642 
6643 	if (dev == device_get_parent(child))
6644 		pci_save_state(child);
6645 	return (0);
6646 }
6647 
6648 static int
6649 pci_reset_child(device_t dev, device_t child, int flags)
6650 {
6651 	int error;
6652 
6653 	if (dev == NULL || device_get_parent(child) != dev)
6654 		return (0);
6655 	if ((flags & DEVF_RESET_DETACH) != 0) {
6656 		error = device_get_state(child) == DS_ATTACHED ?
6657 		    device_detach(child) : 0;
6658 	} else {
6659 		error = BUS_SUSPEND_CHILD(dev, child);
6660 	}
6661 	if (error == 0) {
6662 		if (!pcie_flr(child, 1000, false)) {
6663 			error = BUS_RESET_PREPARE(dev, child);
6664 			if (error == 0)
6665 				pci_power_reset(child);
6666 			BUS_RESET_POST(dev, child);
6667 		}
6668 		if ((flags & DEVF_RESET_DETACH) != 0)
6669 			device_probe_and_attach(child);
6670 		else
6671 			BUS_RESUME_CHILD(dev, child);
6672 	}
6673 	return (error);
6674 }
6675 
6676 const struct pci_device_table *
6677 pci_match_device(device_t child, const struct pci_device_table *id, size_t nelt)
6678 {
6679 	bool match;
6680 	uint16_t vendor, device, subvendor, subdevice, class, subclass, revid;
6681 
6682 	vendor = pci_get_vendor(child);
6683 	device = pci_get_device(child);
6684 	subvendor = pci_get_subvendor(child);
6685 	subdevice = pci_get_subdevice(child);
6686 	class = pci_get_class(child);
6687 	subclass = pci_get_subclass(child);
6688 	revid = pci_get_revid(child);
6689 	while (nelt-- > 0) {
6690 		match = true;
6691 		if (id->match_flag_vendor)
6692 			match &= vendor == id->vendor;
6693 		if (id->match_flag_device)
6694 			match &= device == id->device;
6695 		if (id->match_flag_subvendor)
6696 			match &= subvendor == id->subvendor;
6697 		if (id->match_flag_subdevice)
6698 			match &= subdevice == id->subdevice;
6699 		if (id->match_flag_class)
6700 			match &= class == id->class_id;
6701 		if (id->match_flag_subclass)
6702 			match &= subclass == id->subclass;
6703 		if (id->match_flag_revid)
6704 			match &= revid == id->revid;
6705 		if (match)
6706 			return (id);
6707 		id++;
6708 	}
6709 	return (NULL);
6710 }
6711 
6712 static void
6713 pci_print_faulted_dev_name(const struct pci_devinfo *dinfo)
6714 {
6715 	const char *dev_name;
6716 	device_t dev;
6717 
6718 	dev = dinfo->cfg.dev;
6719 	printf("pci%d:%d:%d:%d", dinfo->cfg.domain, dinfo->cfg.bus,
6720 	    dinfo->cfg.slot, dinfo->cfg.func);
6721 	dev_name = device_get_name(dev);
6722 	if (dev_name != NULL)
6723 		printf(" (%s%d)", dev_name, device_get_unit(dev));
6724 }
6725 
6726 void
6727 pci_print_faulted_dev(void)
6728 {
6729 	struct pci_devinfo *dinfo;
6730 	device_t dev;
6731 	int aer, i;
6732 	uint32_t r1, r2;
6733 	uint16_t status;
6734 
6735 	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
6736 		dev = dinfo->cfg.dev;
6737 		status = pci_read_config(dev, PCIR_STATUS, 2);
6738 		status &= PCIM_STATUS_MDPERR | PCIM_STATUS_STABORT |
6739 		    PCIM_STATUS_RTABORT | PCIM_STATUS_RMABORT |
6740 		    PCIM_STATUS_SERR | PCIM_STATUS_PERR;
6741 		if (status != 0) {
6742 			pci_print_faulted_dev_name(dinfo);
6743 			printf(" error 0x%04x\n", status);
6744 		}
6745 		if (dinfo->cfg.pcie.pcie_location != 0) {
6746 			status = pci_read_config(dev,
6747 			    dinfo->cfg.pcie.pcie_location +
6748 			    PCIER_DEVICE_STA, 2);
6749 			if ((status & (PCIEM_STA_CORRECTABLE_ERROR |
6750 			    PCIEM_STA_NON_FATAL_ERROR | PCIEM_STA_FATAL_ERROR |
6751 			    PCIEM_STA_UNSUPPORTED_REQ)) != 0) {
6752 				pci_print_faulted_dev_name(dinfo);
6753 				printf(" PCIe DEVCTL 0x%04x DEVSTA 0x%04x\n",
6754 				    pci_read_config(dev,
6755 				    dinfo->cfg.pcie.pcie_location +
6756 				    PCIER_DEVICE_CTL, 2),
6757 				    status);
6758 			}
6759 		}
6760 		if (pci_find_extcap(dev, PCIZ_AER, &aer) == 0) {
6761 			r1 = pci_read_config(dev, aer + PCIR_AER_UC_STATUS, 4);
6762 			r2 = pci_read_config(dev, aer + PCIR_AER_COR_STATUS, 4);
6763 			if (r1 != 0 || r2 != 0) {
6764 				pci_print_faulted_dev_name(dinfo);
6765 				printf(" AER UC 0x%08x Mask 0x%08x Svr 0x%08x\n"
6766 				    "  COR 0x%08x Mask 0x%08x Ctl 0x%08x\n",
6767 				    r1, pci_read_config(dev, aer +
6768 				    PCIR_AER_UC_MASK, 4),
6769 				    pci_read_config(dev, aer +
6770 				    PCIR_AER_UC_SEVERITY, 4),
6771 				    r2, pci_read_config(dev, aer +
6772 				    PCIR_AER_COR_MASK, 4),
6773 				    pci_read_config(dev, aer +
6774 				    PCIR_AER_CAP_CONTROL, 4));
6775 				for (i = 0; i < 4; i++) {
6776 					r1 = pci_read_config(dev, aer +
6777 					    PCIR_AER_HEADER_LOG + i * 4, 4);
6778 					printf("    HL%d: 0x%08x\n", i, r1);
6779 				}
6780 			}
6781 		}
6782 	}
6783 }
6784 
6785 #ifdef DDB
6786 DB_SHOW_COMMAND_FLAGS(pcierr, pci_print_faulted_dev_db, DB_CMD_MEMSAFE)
6787 {
6788 
6789 	pci_print_faulted_dev();
6790 }
6791 
6792 static void
6793 db_clear_pcie_errors(const struct pci_devinfo *dinfo)
6794 {
6795 	device_t dev;
6796 	int aer;
6797 	uint32_t r;
6798 
6799 	dev = dinfo->cfg.dev;
6800 	r = pci_read_config(dev, dinfo->cfg.pcie.pcie_location +
6801 	    PCIER_DEVICE_STA, 2);
6802 	pci_write_config(dev, dinfo->cfg.pcie.pcie_location +
6803 	    PCIER_DEVICE_STA, r, 2);
6804 
6805 	if (pci_find_extcap(dev, PCIZ_AER, &aer) != 0)
6806 		return;
6807 	r = pci_read_config(dev, aer + PCIR_AER_UC_STATUS, 4);
6808 	if (r != 0)
6809 		pci_write_config(dev, aer + PCIR_AER_UC_STATUS, r, 4);
6810 	r = pci_read_config(dev, aer + PCIR_AER_COR_STATUS, 4);
6811 	if (r != 0)
6812 		pci_write_config(dev, aer + PCIR_AER_COR_STATUS, r, 4);
6813 }
6814 
6815 DB_COMMAND_FLAGS(pci_clearerr, db_pci_clearerr, DB_CMD_MEMSAFE)
6816 {
6817 	struct pci_devinfo *dinfo;
6818 	device_t dev;
6819 	uint16_t status, status1;
6820 
6821 	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
6822 		dev = dinfo->cfg.dev;
6823 		status1 = status = pci_read_config(dev, PCIR_STATUS, 2);
6824 		status1 &= PCIM_STATUS_MDPERR | PCIM_STATUS_STABORT |
6825 		    PCIM_STATUS_RTABORT | PCIM_STATUS_RMABORT |
6826 		    PCIM_STATUS_SERR | PCIM_STATUS_PERR;
6827 		if (status1 != 0) {
6828 			status &= ~status1;
6829 			pci_write_config(dev, PCIR_STATUS, status, 2);
6830 		}
6831 		if (dinfo->cfg.pcie.pcie_location != 0)
6832 			db_clear_pcie_errors(dinfo);
6833 	}
6834 }
6835 #endif
6836