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