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