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