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