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