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