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