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