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