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