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