xref: /freebsd-12.1/sys/dev/pci/pci.c (revision 889db3af)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1997, Stefan Esser <[email protected]>
5  * Copyright (c) 2000, Michael Smith <[email protected]>
6  * Copyright (c) 2000, BSDi
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice unmodified, this list of conditions, and the following
14  *    disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include "opt_bus.h"
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/limits.h>
41 #include <sys/linker.h>
42 #include <sys/fcntl.h>
43 #include <sys/conf.h>
44 #include <sys/kernel.h>
45 #include <sys/queue.h>
46 #include <sys/sysctl.h>
47 #include <sys/endian.h>
48 
49 #include <vm/vm.h>
50 #include <vm/pmap.h>
51 #include <vm/vm_extern.h>
52 
53 #include <sys/bus.h>
54 #include <machine/bus.h>
55 #include <sys/rman.h>
56 #include <machine/resource.h>
57 #include <machine/stdarg.h>
58 
59 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
60 #include <machine/intr_machdep.h>
61 #endif
62 
63 #include <sys/pciio.h>
64 #include <dev/pci/pcireg.h>
65 #include <dev/pci/pcivar.h>
66 #include <dev/pci/pci_private.h>
67 
68 #ifdef PCI_IOV
69 #include <sys/nv.h>
70 #include <dev/pci/pci_iov_private.h>
71 #endif
72 
73 #include <dev/usb/controller/xhcireg.h>
74 #include <dev/usb/controller/ehcireg.h>
75 #include <dev/usb/controller/ohcireg.h>
76 #include <dev/usb/controller/uhcireg.h>
77 
78 #include "pcib_if.h"
79 #include "pci_if.h"
80 
81 #define	PCIR_IS_BIOS(cfg, reg)						\
82 	(((cfg)->hdrtype == PCIM_HDRTYPE_NORMAL && reg == PCIR_BIOS) ||	\
83 	 ((cfg)->hdrtype == PCIM_HDRTYPE_BRIDGE && reg == PCIR_BIOS_1))
84 
85 static int		pci_has_quirk(uint32_t devid, int quirk);
86 static pci_addr_t	pci_mapbase(uint64_t mapreg);
87 static const char	*pci_maptype(uint64_t mapreg);
88 static int		pci_maprange(uint64_t mapreg);
89 static pci_addr_t	pci_rombase(uint64_t mapreg);
90 static int		pci_romsize(uint64_t testval);
91 static void		pci_fixancient(pcicfgregs *cfg);
92 static int		pci_printf(pcicfgregs *cfg, const char *fmt, ...);
93 
94 static int		pci_porten(device_t dev);
95 static int		pci_memen(device_t dev);
96 static void		pci_assign_interrupt(device_t bus, device_t dev,
97 			    int force_route);
98 static int		pci_add_map(device_t bus, device_t dev, int reg,
99 			    struct resource_list *rl, int force, int prefetch);
100 static int		pci_probe(device_t dev);
101 static int		pci_attach(device_t dev);
102 static int		pci_detach(device_t dev);
103 static void		pci_load_vendor_data(void);
104 static int		pci_describe_parse_line(char **ptr, int *vendor,
105 			    int *device, char **desc);
106 static char		*pci_describe_device(device_t dev);
107 static int		pci_modevent(module_t mod, int what, void *arg);
108 static void		pci_hdrtypedata(device_t pcib, int b, int s, int f,
109 			    pcicfgregs *cfg);
110 static void		pci_read_cap(device_t pcib, pcicfgregs *cfg);
111 static int		pci_read_vpd_reg(device_t pcib, pcicfgregs *cfg,
112 			    int reg, uint32_t *data);
113 #if 0
114 static int		pci_write_vpd_reg(device_t pcib, pcicfgregs *cfg,
115 			    int reg, uint32_t data);
116 #endif
117 static void		pci_read_vpd(device_t pcib, pcicfgregs *cfg);
118 static void		pci_mask_msix(device_t dev, u_int index);
119 static void		pci_unmask_msix(device_t dev, u_int index);
120 static int		pci_msi_blacklisted(void);
121 static int		pci_msix_blacklisted(void);
122 static void		pci_resume_msi(device_t dev);
123 static void		pci_resume_msix(device_t dev);
124 static int		pci_remap_intr_method(device_t bus, device_t dev,
125 			    u_int irq);
126 static void		pci_hint_device_unit(device_t acdev, device_t child,
127 			    const char *name, int *unitp);
128 static int		pci_reset_post(device_t dev, device_t child);
129 static int		pci_reset_prepare(device_t dev, device_t child);
130 static int		pci_reset_child(device_t dev, device_t child,
131 			    int flags);
132 
133 static int		pci_get_id_method(device_t dev, device_t child,
134 			    enum pci_id_type type, uintptr_t *rid);
135 
136 static struct pci_devinfo * pci_fill_devinfo(device_t pcib, device_t bus, int d,
137     int b, int s, int f, uint16_t vid, uint16_t did);
138 
139 static device_method_t pci_methods[] = {
140 	/* Device interface */
141 	DEVMETHOD(device_probe,		pci_probe),
142 	DEVMETHOD(device_attach,	pci_attach),
143 	DEVMETHOD(device_detach,	pci_detach),
144 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
145 	DEVMETHOD(device_suspend,	bus_generic_suspend),
146 	DEVMETHOD(device_resume,	pci_resume),
147 
148 	/* Bus interface */
149 	DEVMETHOD(bus_print_child,	pci_print_child),
150 	DEVMETHOD(bus_probe_nomatch,	pci_probe_nomatch),
151 	DEVMETHOD(bus_read_ivar,	pci_read_ivar),
152 	DEVMETHOD(bus_write_ivar,	pci_write_ivar),
153 	DEVMETHOD(bus_driver_added,	pci_driver_added),
154 	DEVMETHOD(bus_setup_intr,	pci_setup_intr),
155 	DEVMETHOD(bus_teardown_intr,	pci_teardown_intr),
156 	DEVMETHOD(bus_reset_prepare,	pci_reset_prepare),
157 	DEVMETHOD(bus_reset_post,	pci_reset_post),
158 	DEVMETHOD(bus_reset_child,	pci_reset_child),
159 
160 	DEVMETHOD(bus_get_dma_tag,	pci_get_dma_tag),
161 	DEVMETHOD(bus_get_resource_list,pci_get_resource_list),
162 	DEVMETHOD(bus_set_resource,	bus_generic_rl_set_resource),
163 	DEVMETHOD(bus_get_resource,	bus_generic_rl_get_resource),
164 	DEVMETHOD(bus_delete_resource,	pci_delete_resource),
165 	DEVMETHOD(bus_alloc_resource,	pci_alloc_resource),
166 	DEVMETHOD(bus_adjust_resource,	bus_generic_adjust_resource),
167 	DEVMETHOD(bus_release_resource,	pci_release_resource),
168 	DEVMETHOD(bus_activate_resource, pci_activate_resource),
169 	DEVMETHOD(bus_deactivate_resource, pci_deactivate_resource),
170 	DEVMETHOD(bus_child_deleted,	pci_child_deleted),
171 	DEVMETHOD(bus_child_detached,	pci_child_detached),
172 	DEVMETHOD(bus_child_pnpinfo_str, pci_child_pnpinfo_str_method),
173 	DEVMETHOD(bus_child_location_str, pci_child_location_str_method),
174 	DEVMETHOD(bus_hint_device_unit,	pci_hint_device_unit),
175 	DEVMETHOD(bus_remap_intr,	pci_remap_intr_method),
176 	DEVMETHOD(bus_suspend_child,	pci_suspend_child),
177 	DEVMETHOD(bus_resume_child,	pci_resume_child),
178 	DEVMETHOD(bus_rescan,		pci_rescan_method),
179 
180 	/* PCI interface */
181 	DEVMETHOD(pci_read_config,	pci_read_config_method),
182 	DEVMETHOD(pci_write_config,	pci_write_config_method),
183 	DEVMETHOD(pci_enable_busmaster,	pci_enable_busmaster_method),
184 	DEVMETHOD(pci_disable_busmaster, pci_disable_busmaster_method),
185 	DEVMETHOD(pci_enable_io,	pci_enable_io_method),
186 	DEVMETHOD(pci_disable_io,	pci_disable_io_method),
187 	DEVMETHOD(pci_get_vpd_ident,	pci_get_vpd_ident_method),
188 	DEVMETHOD(pci_get_vpd_readonly,	pci_get_vpd_readonly_method),
189 	DEVMETHOD(pci_get_powerstate,	pci_get_powerstate_method),
190 	DEVMETHOD(pci_set_powerstate,	pci_set_powerstate_method),
191 	DEVMETHOD(pci_assign_interrupt,	pci_assign_interrupt_method),
192 	DEVMETHOD(pci_find_cap,		pci_find_cap_method),
193 	DEVMETHOD(pci_find_next_cap,	pci_find_next_cap_method),
194 	DEVMETHOD(pci_find_extcap,	pci_find_extcap_method),
195 	DEVMETHOD(pci_find_next_extcap,	pci_find_next_extcap_method),
196 	DEVMETHOD(pci_find_htcap,	pci_find_htcap_method),
197 	DEVMETHOD(pci_find_next_htcap,	pci_find_next_htcap_method),
198 	DEVMETHOD(pci_alloc_msi,	pci_alloc_msi_method),
199 	DEVMETHOD(pci_alloc_msix,	pci_alloc_msix_method),
200 	DEVMETHOD(pci_enable_msi,	pci_enable_msi_method),
201 	DEVMETHOD(pci_enable_msix,	pci_enable_msix_method),
202 	DEVMETHOD(pci_disable_msi,	pci_disable_msi_method),
203 	DEVMETHOD(pci_remap_msix,	pci_remap_msix_method),
204 	DEVMETHOD(pci_release_msi,	pci_release_msi_method),
205 	DEVMETHOD(pci_msi_count,	pci_msi_count_method),
206 	DEVMETHOD(pci_msix_count,	pci_msix_count_method),
207 	DEVMETHOD(pci_msix_pba_bar,	pci_msix_pba_bar_method),
208 	DEVMETHOD(pci_msix_table_bar,	pci_msix_table_bar_method),
209 	DEVMETHOD(pci_get_id,		pci_get_id_method),
210 	DEVMETHOD(pci_alloc_devinfo,	pci_alloc_devinfo_method),
211 	DEVMETHOD(pci_child_added,	pci_child_added_method),
212 #ifdef PCI_IOV
213 	DEVMETHOD(pci_iov_attach,	pci_iov_attach_method),
214 	DEVMETHOD(pci_iov_detach,	pci_iov_detach_method),
215 	DEVMETHOD(pci_create_iov_child,	pci_create_iov_child_method),
216 #endif
217 
218 	DEVMETHOD_END
219 };
220 
221 DEFINE_CLASS_0(pci, pci_driver, pci_methods, sizeof(struct pci_softc));
222 
223 static devclass_t pci_devclass;
224 DRIVER_MODULE(pci, pcib, pci_driver, pci_devclass, pci_modevent, NULL);
225 MODULE_VERSION(pci, 1);
226 
227 static char	*pci_vendordata;
228 static size_t	pci_vendordata_size;
229 
230 struct pci_quirk {
231 	uint32_t devid;	/* Vendor/device of the card */
232 	int	type;
233 #define	PCI_QUIRK_MAP_REG	1 /* PCI map register in weird place */
234 #define	PCI_QUIRK_DISABLE_MSI	2 /* Neither MSI nor MSI-X work */
235 #define	PCI_QUIRK_ENABLE_MSI_VM	3 /* Older chipset in VM where MSI works */
236 #define	PCI_QUIRK_UNMAP_REG	4 /* Ignore PCI map register */
237 #define	PCI_QUIRK_DISABLE_MSIX	5 /* MSI-X doesn't work */
238 #define	PCI_QUIRK_MSI_INTX_BUG	6 /* PCIM_CMD_INTxDIS disables MSI */
239 	int	arg1;
240 	int	arg2;
241 };
242 
243 static const struct pci_quirk pci_quirks[] = {
244 	/* The Intel 82371AB and 82443MX have a map register at offset 0x90. */
245 	{ 0x71138086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
246 	{ 0x719b8086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
247 	/* As does the Serverworks OSB4 (the SMBus mapping register) */
248 	{ 0x02001166, PCI_QUIRK_MAP_REG,	0x90,	 0 },
249 
250 	/*
251 	 * MSI doesn't work with the ServerWorks CNB20-HE Host Bridge
252 	 * or the CMIC-SL (AKA ServerWorks GC_LE).
253 	 */
254 	{ 0x00141166, PCI_QUIRK_DISABLE_MSI,	0,	0 },
255 	{ 0x00171166, PCI_QUIRK_DISABLE_MSI,	0,	0 },
256 
257 	/*
258 	 * MSI doesn't work on earlier Intel chipsets including
259 	 * E7500, E7501, E7505, 845, 865, 875/E7210, and 855.
260 	 */
261 	{ 0x25408086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
262 	{ 0x254c8086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
263 	{ 0x25508086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
264 	{ 0x25608086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
265 	{ 0x25708086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
266 	{ 0x25788086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
267 	{ 0x35808086, PCI_QUIRK_DISABLE_MSI,	0,	0 },
268 
269 	/*
270 	 * MSI doesn't work with devices behind the AMD 8131 HT-PCIX
271 	 * bridge.
272 	 */
273 	{ 0x74501022, PCI_QUIRK_DISABLE_MSI,	0,	0 },
274 
275 	/*
276 	 * MSI-X allocation doesn't work properly for devices passed through
277 	 * by VMware up to at least ESXi 5.1.
278 	 */
279 	{ 0x079015ad, PCI_QUIRK_DISABLE_MSIX,	0,	0 }, /* PCI/PCI-X */
280 	{ 0x07a015ad, PCI_QUIRK_DISABLE_MSIX,	0,	0 }, /* PCIe */
281 
282 	/*
283 	 * Some virtualization environments emulate an older chipset
284 	 * but support MSI just fine.  QEMU uses the Intel 82440.
285 	 */
286 	{ 0x12378086, PCI_QUIRK_ENABLE_MSI_VM,	0,	0 },
287 
288 	/*
289 	 * HPET MMIO base address may appear in Bar1 for AMD SB600 SMBus
290 	 * controller depending on SoftPciRst register (PM_IO 0x55 [7]).
291 	 * It prevents us from attaching hpet(4) when the bit is unset.
292 	 * Note this quirk only affects SB600 revision A13 and earlier.
293 	 * For SB600 A21 and later, firmware must set the bit to hide it.
294 	 * For SB700 and later, it is unused and hardcoded to zero.
295 	 */
296 	{ 0x43851002, PCI_QUIRK_UNMAP_REG,	0x14,	0 },
297 
298 	/*
299 	 * Atheros AR8161/AR8162/E2200/E2400/E2500 Ethernet controllers have
300 	 * a bug that MSI interrupt does not assert if PCIM_CMD_INTxDIS bit
301 	 * of the command register is set.
302 	 */
303 	{ 0x10911969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
304 	{ 0xE0911969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
305 	{ 0xE0A11969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
306 	{ 0xE0B11969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
307 	{ 0x10901969, PCI_QUIRK_MSI_INTX_BUG,	0,	0 },
308 
309 	/*
310 	 * Broadcom BCM5714(S)/BCM5715(S)/BCM5780(S) Ethernet MACs don't
311 	 * issue MSI interrupts with PCIM_CMD_INTxDIS set either.
312 	 */
313 	{ 0x166814e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5714 */
314 	{ 0x166914e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5714S */
315 	{ 0x166a14e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5780 */
316 	{ 0x166b14e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5780S */
317 	{ 0x167814e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5715 */
318 	{ 0x167914e4, PCI_QUIRK_MSI_INTX_BUG,	0,	0 }, /* BCM5715S */
319 
320 	{ 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 	 * NB: according to the PCI Local Bus Specification, rev. 3.0:
3034 	 * "Software writes 0FFFFFFFFh to both registers, reads them back,
3035 	 * and combines the result into a 64-bit value." (section 6.2.5.1)
3036 	 *
3037 	 * Writes to both registers must be performed before attempting to
3038 	 * read back the size value.
3039 	 */
3040 	testval = 0;
3041 	pci_write_config(dev, reg, 0xffffffff, 4);
3042 	if (ln2range == 64) {
3043 		pci_write_config(dev, reg + 4, 0xffffffff, 4);
3044 		testval |= (pci_addr_t)pci_read_config(dev, reg + 4, 4) << 32;
3045 	}
3046 	testval |= pci_read_config(dev, reg, 4);
3047 
3048 	/*
3049 	 * Restore the original value of the BAR.  We may have reprogrammed
3050 	 * the BAR of the low-level console device and when booting verbose,
3051 	 * we need the console device addressable.
3052 	 */
3053 	pci_write_config(dev, reg, map, 4);
3054 	if (ln2range == 64)
3055 		pci_write_config(dev, reg + 4, map >> 32, 4);
3056 	pci_write_config(dev, PCIR_COMMAND, cmd, 2);
3057 
3058 	*mapp = map;
3059 	*testvalp = testval;
3060 	if (bar64 != NULL)
3061 		*bar64 = (ln2range == 64);
3062 }
3063 
3064 static void
pci_write_bar(device_t dev,struct pci_map * pm,pci_addr_t base)3065 pci_write_bar(device_t dev, struct pci_map *pm, pci_addr_t base)
3066 {
3067 	struct pci_devinfo *dinfo;
3068 	int ln2range;
3069 
3070 	/* The device ROM BAR is always a 32-bit memory BAR. */
3071 	dinfo = device_get_ivars(dev);
3072 	if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg))
3073 		ln2range = 32;
3074 	else
3075 		ln2range = pci_maprange(pm->pm_value);
3076 	pci_write_config(dev, pm->pm_reg, base, 4);
3077 	if (ln2range == 64)
3078 		pci_write_config(dev, pm->pm_reg + 4, base >> 32, 4);
3079 	pm->pm_value = pci_read_config(dev, pm->pm_reg, 4);
3080 	if (ln2range == 64)
3081 		pm->pm_value |= (pci_addr_t)pci_read_config(dev,
3082 		    pm->pm_reg + 4, 4) << 32;
3083 }
3084 
3085 struct pci_map *
pci_find_bar(device_t dev,int reg)3086 pci_find_bar(device_t dev, int reg)
3087 {
3088 	struct pci_devinfo *dinfo;
3089 	struct pci_map *pm;
3090 
3091 	dinfo = device_get_ivars(dev);
3092 	STAILQ_FOREACH(pm, &dinfo->cfg.maps, pm_link) {
3093 		if (pm->pm_reg == reg)
3094 			return (pm);
3095 	}
3096 	return (NULL);
3097 }
3098 
3099 int
pci_bar_enabled(device_t dev,struct pci_map * pm)3100 pci_bar_enabled(device_t dev, struct pci_map *pm)
3101 {
3102 	struct pci_devinfo *dinfo;
3103 	uint16_t cmd;
3104 
3105 	dinfo = device_get_ivars(dev);
3106 	if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg) &&
3107 	    !(pm->pm_value & PCIM_BIOS_ENABLE))
3108 		return (0);
3109 	cmd = pci_read_config(dev, PCIR_COMMAND, 2);
3110 	if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg) || PCI_BAR_MEM(pm->pm_value))
3111 		return ((cmd & PCIM_CMD_MEMEN) != 0);
3112 	else
3113 		return ((cmd & PCIM_CMD_PORTEN) != 0);
3114 }
3115 
3116 struct pci_map *
pci_add_bar(device_t dev,int reg,pci_addr_t value,pci_addr_t size)3117 pci_add_bar(device_t dev, int reg, pci_addr_t value, pci_addr_t size)
3118 {
3119 	struct pci_devinfo *dinfo;
3120 	struct pci_map *pm, *prev;
3121 
3122 	dinfo = device_get_ivars(dev);
3123 	pm = malloc(sizeof(*pm), M_DEVBUF, M_WAITOK | M_ZERO);
3124 	pm->pm_reg = reg;
3125 	pm->pm_value = value;
3126 	pm->pm_size = size;
3127 	STAILQ_FOREACH(prev, &dinfo->cfg.maps, pm_link) {
3128 		KASSERT(prev->pm_reg != pm->pm_reg, ("duplicate map %02x",
3129 		    reg));
3130 		if (STAILQ_NEXT(prev, pm_link) == NULL ||
3131 		    STAILQ_NEXT(prev, pm_link)->pm_reg > pm->pm_reg)
3132 			break;
3133 	}
3134 	if (prev != NULL)
3135 		STAILQ_INSERT_AFTER(&dinfo->cfg.maps, prev, pm, pm_link);
3136 	else
3137 		STAILQ_INSERT_TAIL(&dinfo->cfg.maps, pm, pm_link);
3138 	return (pm);
3139 }
3140 
3141 static void
pci_restore_bars(device_t dev)3142 pci_restore_bars(device_t dev)
3143 {
3144 	struct pci_devinfo *dinfo;
3145 	struct pci_map *pm;
3146 	int ln2range;
3147 
3148 	dinfo = device_get_ivars(dev);
3149 	STAILQ_FOREACH(pm, &dinfo->cfg.maps, pm_link) {
3150 		if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg))
3151 			ln2range = 32;
3152 		else
3153 			ln2range = pci_maprange(pm->pm_value);
3154 		pci_write_config(dev, pm->pm_reg, pm->pm_value, 4);
3155 		if (ln2range == 64)
3156 			pci_write_config(dev, pm->pm_reg + 4,
3157 			    pm->pm_value >> 32, 4);
3158 	}
3159 }
3160 
3161 /*
3162  * Add a resource based on a pci map register. Return 1 if the map
3163  * register is a 32bit map register or 2 if it is a 64bit register.
3164  */
3165 static int
pci_add_map(device_t bus,device_t dev,int reg,struct resource_list * rl,int force,int prefetch)3166 pci_add_map(device_t bus, device_t dev, int reg, struct resource_list *rl,
3167     int force, int prefetch)
3168 {
3169 	struct pci_map *pm;
3170 	pci_addr_t base, map, testval;
3171 	pci_addr_t start, end, count;
3172 	int barlen, basezero, flags, maprange, mapsize, type;
3173 	uint16_t cmd;
3174 	struct resource *res;
3175 
3176 	/*
3177 	 * The BAR may already exist if the device is a CardBus card
3178 	 * whose CIS is stored in this BAR.
3179 	 */
3180 	pm = pci_find_bar(dev, reg);
3181 	if (pm != NULL) {
3182 		maprange = pci_maprange(pm->pm_value);
3183 		barlen = maprange == 64 ? 2 : 1;
3184 		return (barlen);
3185 	}
3186 
3187 	pci_read_bar(dev, reg, &map, &testval, NULL);
3188 	if (PCI_BAR_MEM(map)) {
3189 		type = SYS_RES_MEMORY;
3190 		if (map & PCIM_BAR_MEM_PREFETCH)
3191 			prefetch = 1;
3192 	} else
3193 		type = SYS_RES_IOPORT;
3194 	mapsize = pci_mapsize(testval);
3195 	base = pci_mapbase(map);
3196 #ifdef __PCI_BAR_ZERO_VALID
3197 	basezero = 0;
3198 #else
3199 	basezero = base == 0;
3200 #endif
3201 	maprange = pci_maprange(map);
3202 	barlen = maprange == 64 ? 2 : 1;
3203 
3204 	/*
3205 	 * For I/O registers, if bottom bit is set, and the next bit up
3206 	 * isn't clear, we know we have a BAR that doesn't conform to the
3207 	 * spec, so ignore it.  Also, sanity check the size of the data
3208 	 * areas to the type of memory involved.  Memory must be at least
3209 	 * 16 bytes in size, while I/O ranges must be at least 4.
3210 	 */
3211 	if (PCI_BAR_IO(testval) && (testval & PCIM_BAR_IO_RESERVED) != 0)
3212 		return (barlen);
3213 	if ((type == SYS_RES_MEMORY && mapsize < 4) ||
3214 	    (type == SYS_RES_IOPORT && mapsize < 2))
3215 		return (barlen);
3216 
3217 	/* Save a record of this BAR. */
3218 	pm = pci_add_bar(dev, reg, map, mapsize);
3219 	if (bootverbose) {
3220 		printf("\tmap[%02x]: type %s, range %2d, base %#jx, size %2d",
3221 		    reg, pci_maptype(map), maprange, (uintmax_t)base, mapsize);
3222 		if (type == SYS_RES_IOPORT && !pci_porten(dev))
3223 			printf(", port disabled\n");
3224 		else if (type == SYS_RES_MEMORY && !pci_memen(dev))
3225 			printf(", memory disabled\n");
3226 		else
3227 			printf(", enabled\n");
3228 	}
3229 
3230 	/*
3231 	 * If base is 0, then we have problems if this architecture does
3232 	 * not allow that.  It is best to ignore such entries for the
3233 	 * moment.  These will be allocated later if the driver specifically
3234 	 * requests them.  However, some removable buses look better when
3235 	 * all resources are allocated, so allow '0' to be overriden.
3236 	 *
3237 	 * Similarly treat maps whose values is the same as the test value
3238 	 * read back.  These maps have had all f's written to them by the
3239 	 * BIOS in an attempt to disable the resources.
3240 	 */
3241 	if (!force && (basezero || map == testval))
3242 		return (barlen);
3243 	if ((u_long)base != base) {
3244 		device_printf(bus,
3245 		    "pci%d:%d:%d:%d bar %#x too many address bits",
3246 		    pci_get_domain(dev), pci_get_bus(dev), pci_get_slot(dev),
3247 		    pci_get_function(dev), reg);
3248 		return (barlen);
3249 	}
3250 
3251 	/*
3252 	 * This code theoretically does the right thing, but has
3253 	 * undesirable side effects in some cases where peripherals
3254 	 * respond oddly to having these bits enabled.  Let the user
3255 	 * be able to turn them off (since pci_enable_io_modes is 1 by
3256 	 * default).
3257 	 */
3258 	if (pci_enable_io_modes) {
3259 		/* Turn on resources that have been left off by a lazy BIOS */
3260 		if (type == SYS_RES_IOPORT && !pci_porten(dev)) {
3261 			cmd = pci_read_config(dev, PCIR_COMMAND, 2);
3262 			cmd |= PCIM_CMD_PORTEN;
3263 			pci_write_config(dev, PCIR_COMMAND, cmd, 2);
3264 		}
3265 		if (type == SYS_RES_MEMORY && !pci_memen(dev)) {
3266 			cmd = pci_read_config(dev, PCIR_COMMAND, 2);
3267 			cmd |= PCIM_CMD_MEMEN;
3268 			pci_write_config(dev, PCIR_COMMAND, cmd, 2);
3269 		}
3270 	} else {
3271 		if (type == SYS_RES_IOPORT && !pci_porten(dev))
3272 			return (barlen);
3273 		if (type == SYS_RES_MEMORY && !pci_memen(dev))
3274 			return (barlen);
3275 	}
3276 
3277 	count = (pci_addr_t)1 << mapsize;
3278 	flags = RF_ALIGNMENT_LOG2(mapsize);
3279 	if (prefetch)
3280 		flags |= RF_PREFETCHABLE;
3281 	if (basezero || base == pci_mapbase(testval) || pci_clear_bars) {
3282 		start = 0;	/* Let the parent decide. */
3283 		end = ~0;
3284 	} else {
3285 		start = base;
3286 		end = base + count - 1;
3287 	}
3288 	resource_list_add(rl, type, reg, start, end, count);
3289 
3290 	/*
3291 	 * Try to allocate the resource for this BAR from our parent
3292 	 * so that this resource range is already reserved.  The
3293 	 * driver for this device will later inherit this resource in
3294 	 * pci_alloc_resource().
3295 	 */
3296 	res = resource_list_reserve(rl, bus, dev, type, &reg, start, end, count,
3297 	    flags);
3298 	if (pci_do_realloc_bars && res == NULL && (start != 0 || end != ~0)) {
3299 		/*
3300 		 * If the allocation fails, try to allocate a resource for
3301 		 * this BAR using any available range.  The firmware felt
3302 		 * it was important enough to assign a resource, so don't
3303 		 * disable decoding if we can help it.
3304 		 */
3305 		resource_list_delete(rl, type, reg);
3306 		resource_list_add(rl, type, reg, 0, ~0, count);
3307 		res = resource_list_reserve(rl, bus, dev, type, &reg, 0, ~0,
3308 		    count, flags);
3309 	}
3310 	if (res == NULL) {
3311 		/*
3312 		 * If the allocation fails, delete the resource list entry
3313 		 * and disable decoding for this device.
3314 		 *
3315 		 * If the driver requests this resource in the future,
3316 		 * pci_reserve_map() will try to allocate a fresh
3317 		 * resource range.
3318 		 */
3319 		resource_list_delete(rl, type, reg);
3320 		pci_disable_io(dev, type);
3321 		if (bootverbose)
3322 			device_printf(bus,
3323 			    "pci%d:%d:%d:%d bar %#x failed to allocate\n",
3324 			    pci_get_domain(dev), pci_get_bus(dev),
3325 			    pci_get_slot(dev), pci_get_function(dev), reg);
3326 	} else {
3327 		start = rman_get_start(res);
3328 		pci_write_bar(dev, pm, start);
3329 	}
3330 	return (barlen);
3331 }
3332 
3333 /*
3334  * For ATA devices we need to decide early what addressing mode to use.
3335  * Legacy demands that the primary and secondary ATA ports sits on the
3336  * same addresses that old ISA hardware did. This dictates that we use
3337  * those addresses and ignore the BAR's if we cannot set PCI native
3338  * addressing mode.
3339  */
3340 static void
pci_ata_maps(device_t bus,device_t dev,struct resource_list * rl,int force,uint32_t prefetchmask)3341 pci_ata_maps(device_t bus, device_t dev, struct resource_list *rl, int force,
3342     uint32_t prefetchmask)
3343 {
3344 	int rid, type, progif;
3345 #if 0
3346 	/* if this device supports PCI native addressing use it */
3347 	progif = pci_read_config(dev, PCIR_PROGIF, 1);
3348 	if ((progif & 0x8a) == 0x8a) {
3349 		if (pci_mapbase(pci_read_config(dev, PCIR_BAR(0), 4)) &&
3350 		    pci_mapbase(pci_read_config(dev, PCIR_BAR(2), 4))) {
3351 			printf("Trying ATA native PCI addressing mode\n");
3352 			pci_write_config(dev, PCIR_PROGIF, progif | 0x05, 1);
3353 		}
3354 	}
3355 #endif
3356 	progif = pci_read_config(dev, PCIR_PROGIF, 1);
3357 	type = SYS_RES_IOPORT;
3358 	if (progif & PCIP_STORAGE_IDE_MODEPRIM) {
3359 		pci_add_map(bus, dev, PCIR_BAR(0), rl, force,
3360 		    prefetchmask & (1 << 0));
3361 		pci_add_map(bus, dev, PCIR_BAR(1), rl, force,
3362 		    prefetchmask & (1 << 1));
3363 	} else {
3364 		rid = PCIR_BAR(0);
3365 		resource_list_add(rl, type, rid, 0x1f0, 0x1f7, 8);
3366 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x1f0,
3367 		    0x1f7, 8, 0);
3368 		rid = PCIR_BAR(1);
3369 		resource_list_add(rl, type, rid, 0x3f6, 0x3f6, 1);
3370 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x3f6,
3371 		    0x3f6, 1, 0);
3372 	}
3373 	if (progif & PCIP_STORAGE_IDE_MODESEC) {
3374 		pci_add_map(bus, dev, PCIR_BAR(2), rl, force,
3375 		    prefetchmask & (1 << 2));
3376 		pci_add_map(bus, dev, PCIR_BAR(3), rl, force,
3377 		    prefetchmask & (1 << 3));
3378 	} else {
3379 		rid = PCIR_BAR(2);
3380 		resource_list_add(rl, type, rid, 0x170, 0x177, 8);
3381 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x170,
3382 		    0x177, 8, 0);
3383 		rid = PCIR_BAR(3);
3384 		resource_list_add(rl, type, rid, 0x376, 0x376, 1);
3385 		(void)resource_list_reserve(rl, bus, dev, type, &rid, 0x376,
3386 		    0x376, 1, 0);
3387 	}
3388 	pci_add_map(bus, dev, PCIR_BAR(4), rl, force,
3389 	    prefetchmask & (1 << 4));
3390 	pci_add_map(bus, dev, PCIR_BAR(5), rl, force,
3391 	    prefetchmask & (1 << 5));
3392 }
3393 
3394 static void
pci_assign_interrupt(device_t bus,device_t dev,int force_route)3395 pci_assign_interrupt(device_t bus, device_t dev, int force_route)
3396 {
3397 	struct pci_devinfo *dinfo = device_get_ivars(dev);
3398 	pcicfgregs *cfg = &dinfo->cfg;
3399 	char tunable_name[64];
3400 	int irq;
3401 
3402 	/* Has to have an intpin to have an interrupt. */
3403 	if (cfg->intpin == 0)
3404 		return;
3405 
3406 	/* Let the user override the IRQ with a tunable. */
3407 	irq = PCI_INVALID_IRQ;
3408 	snprintf(tunable_name, sizeof(tunable_name),
3409 	    "hw.pci%d.%d.%d.INT%c.irq",
3410 	    cfg->domain, cfg->bus, cfg->slot, cfg->intpin + 'A' - 1);
3411 	if (TUNABLE_INT_FETCH(tunable_name, &irq) && (irq >= 255 || irq <= 0))
3412 		irq = PCI_INVALID_IRQ;
3413 
3414 	/*
3415 	 * If we didn't get an IRQ via the tunable, then we either use the
3416 	 * IRQ value in the intline register or we ask the bus to route an
3417 	 * interrupt for us.  If force_route is true, then we only use the
3418 	 * value in the intline register if the bus was unable to assign an
3419 	 * IRQ.
3420 	 */
3421 	if (!PCI_INTERRUPT_VALID(irq)) {
3422 		if (!PCI_INTERRUPT_VALID(cfg->intline) || force_route)
3423 			irq = PCI_ASSIGN_INTERRUPT(bus, dev);
3424 		if (!PCI_INTERRUPT_VALID(irq))
3425 			irq = cfg->intline;
3426 	}
3427 
3428 	/* If after all that we don't have an IRQ, just bail. */
3429 	if (!PCI_INTERRUPT_VALID(irq))
3430 		return;
3431 
3432 	/* Update the config register if it changed. */
3433 	if (irq != cfg->intline) {
3434 		cfg->intline = irq;
3435 		pci_write_config(dev, PCIR_INTLINE, irq, 1);
3436 	}
3437 
3438 	/* Add this IRQ as rid 0 interrupt resource. */
3439 	resource_list_add(&dinfo->resources, SYS_RES_IRQ, 0, irq, irq, 1);
3440 }
3441 
3442 /* Perform early OHCI takeover from SMM. */
3443 static void
ohci_early_takeover(device_t self)3444 ohci_early_takeover(device_t self)
3445 {
3446 	struct resource *res;
3447 	uint32_t ctl;
3448 	int rid;
3449 	int i;
3450 
3451 	rid = PCIR_BAR(0);
3452 	res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3453 	if (res == NULL)
3454 		return;
3455 
3456 	ctl = bus_read_4(res, OHCI_CONTROL);
3457 	if (ctl & OHCI_IR) {
3458 		if (bootverbose)
3459 			printf("ohci early: "
3460 			    "SMM active, request owner change\n");
3461 		bus_write_4(res, OHCI_COMMAND_STATUS, OHCI_OCR);
3462 		for (i = 0; (i < 100) && (ctl & OHCI_IR); i++) {
3463 			DELAY(1000);
3464 			ctl = bus_read_4(res, OHCI_CONTROL);
3465 		}
3466 		if (ctl & OHCI_IR) {
3467 			if (bootverbose)
3468 				printf("ohci early: "
3469 				    "SMM does not respond, resetting\n");
3470 			bus_write_4(res, OHCI_CONTROL, OHCI_HCFS_RESET);
3471 		}
3472 		/* Disable interrupts */
3473 		bus_write_4(res, OHCI_INTERRUPT_DISABLE, OHCI_ALL_INTRS);
3474 	}
3475 
3476 	bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3477 }
3478 
3479 /* Perform early UHCI takeover from SMM. */
3480 static void
uhci_early_takeover(device_t self)3481 uhci_early_takeover(device_t self)
3482 {
3483 	struct resource *res;
3484 	int rid;
3485 
3486 	/*
3487 	 * Set the PIRQD enable bit and switch off all the others. We don't
3488 	 * want legacy support to interfere with us XXX Does this also mean
3489 	 * that the BIOS won't touch the keyboard anymore if it is connected
3490 	 * to the ports of the root hub?
3491 	 */
3492 	pci_write_config(self, PCI_LEGSUP, PCI_LEGSUP_USBPIRQDEN, 2);
3493 
3494 	/* Disable interrupts */
3495 	rid = PCI_UHCI_BASE_REG;
3496 	res = bus_alloc_resource_any(self, SYS_RES_IOPORT, &rid, RF_ACTIVE);
3497 	if (res != NULL) {
3498 		bus_write_2(res, UHCI_INTR, 0);
3499 		bus_release_resource(self, SYS_RES_IOPORT, rid, res);
3500 	}
3501 }
3502 
3503 /* Perform early EHCI takeover from SMM. */
3504 static void
ehci_early_takeover(device_t self)3505 ehci_early_takeover(device_t self)
3506 {
3507 	struct resource *res;
3508 	uint32_t cparams;
3509 	uint32_t eec;
3510 	uint8_t eecp;
3511 	uint8_t bios_sem;
3512 	uint8_t offs;
3513 	int rid;
3514 	int i;
3515 
3516 	rid = PCIR_BAR(0);
3517 	res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3518 	if (res == NULL)
3519 		return;
3520 
3521 	cparams = bus_read_4(res, EHCI_HCCPARAMS);
3522 
3523 	/* Synchronise with the BIOS if it owns the controller. */
3524 	for (eecp = EHCI_HCC_EECP(cparams); eecp != 0;
3525 	    eecp = EHCI_EECP_NEXT(eec)) {
3526 		eec = pci_read_config(self, eecp, 4);
3527 		if (EHCI_EECP_ID(eec) != EHCI_EC_LEGSUP) {
3528 			continue;
3529 		}
3530 		bios_sem = pci_read_config(self, eecp +
3531 		    EHCI_LEGSUP_BIOS_SEM, 1);
3532 		if (bios_sem == 0) {
3533 			continue;
3534 		}
3535 		if (bootverbose)
3536 			printf("ehci early: "
3537 			    "SMM active, request owner change\n");
3538 
3539 		pci_write_config(self, eecp + EHCI_LEGSUP_OS_SEM, 1, 1);
3540 
3541 		for (i = 0; (i < 100) && (bios_sem != 0); i++) {
3542 			DELAY(1000);
3543 			bios_sem = pci_read_config(self, eecp +
3544 			    EHCI_LEGSUP_BIOS_SEM, 1);
3545 		}
3546 
3547 		if (bios_sem != 0) {
3548 			if (bootverbose)
3549 				printf("ehci early: "
3550 				    "SMM does not respond\n");
3551 		}
3552 		/* Disable interrupts */
3553 		offs = EHCI_CAPLENGTH(bus_read_4(res, EHCI_CAPLEN_HCIVERSION));
3554 		bus_write_4(res, offs + EHCI_USBINTR, 0);
3555 	}
3556 	bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3557 }
3558 
3559 /* Perform early XHCI takeover from SMM. */
3560 static void
xhci_early_takeover(device_t self)3561 xhci_early_takeover(device_t self)
3562 {
3563 	struct resource *res;
3564 	uint32_t cparams;
3565 	uint32_t eec;
3566 	uint8_t eecp;
3567 	uint8_t bios_sem;
3568 	uint8_t offs;
3569 	int rid;
3570 	int i;
3571 
3572 	rid = PCIR_BAR(0);
3573 	res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3574 	if (res == NULL)
3575 		return;
3576 
3577 	cparams = bus_read_4(res, XHCI_HCSPARAMS0);
3578 
3579 	eec = -1;
3580 
3581 	/* Synchronise with the BIOS if it owns the controller. */
3582 	for (eecp = XHCI_HCS0_XECP(cparams) << 2; eecp != 0 && XHCI_XECP_NEXT(eec);
3583 	    eecp += XHCI_XECP_NEXT(eec) << 2) {
3584 		eec = bus_read_4(res, eecp);
3585 
3586 		if (XHCI_XECP_ID(eec) != XHCI_ID_USB_LEGACY)
3587 			continue;
3588 
3589 		bios_sem = bus_read_1(res, eecp + XHCI_XECP_BIOS_SEM);
3590 		if (bios_sem == 0)
3591 			continue;
3592 
3593 		if (bootverbose)
3594 			printf("xhci early: "
3595 			    "SMM active, request owner change\n");
3596 
3597 		bus_write_1(res, eecp + XHCI_XECP_OS_SEM, 1);
3598 
3599 		/* wait a maximum of 5 second */
3600 
3601 		for (i = 0; (i < 5000) && (bios_sem != 0); i++) {
3602 			DELAY(1000);
3603 			bios_sem = bus_read_1(res, eecp +
3604 			    XHCI_XECP_BIOS_SEM);
3605 		}
3606 
3607 		if (bios_sem != 0) {
3608 			if (bootverbose)
3609 				printf("xhci early: "
3610 				    "SMM does not respond\n");
3611 		}
3612 
3613 		/* Disable interrupts */
3614 		offs = bus_read_1(res, XHCI_CAPLENGTH);
3615 		bus_write_4(res, offs + XHCI_USBCMD, 0);
3616 		bus_read_4(res, offs + XHCI_USBSTS);
3617 	}
3618 	bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3619 }
3620 
3621 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
3622 static void
pci_reserve_secbus(device_t bus,device_t dev,pcicfgregs * cfg,struct resource_list * rl)3623 pci_reserve_secbus(device_t bus, device_t dev, pcicfgregs *cfg,
3624     struct resource_list *rl)
3625 {
3626 	struct resource *res;
3627 	char *cp;
3628 	rman_res_t start, end, count;
3629 	int rid, sec_bus, sec_reg, sub_bus, sub_reg, sup_bus;
3630 
3631 	switch (cfg->hdrtype & PCIM_HDRTYPE) {
3632 	case PCIM_HDRTYPE_BRIDGE:
3633 		sec_reg = PCIR_SECBUS_1;
3634 		sub_reg = PCIR_SUBBUS_1;
3635 		break;
3636 	case PCIM_HDRTYPE_CARDBUS:
3637 		sec_reg = PCIR_SECBUS_2;
3638 		sub_reg = PCIR_SUBBUS_2;
3639 		break;
3640 	default:
3641 		return;
3642 	}
3643 
3644 	/*
3645 	 * If the existing bus range is valid, attempt to reserve it
3646 	 * from our parent.  If this fails for any reason, clear the
3647 	 * secbus and subbus registers.
3648 	 *
3649 	 * XXX: Should we reset sub_bus to sec_bus if it is < sec_bus?
3650 	 * This would at least preserve the existing sec_bus if it is
3651 	 * valid.
3652 	 */
3653 	sec_bus = PCI_READ_CONFIG(bus, dev, sec_reg, 1);
3654 	sub_bus = PCI_READ_CONFIG(bus, dev, sub_reg, 1);
3655 
3656 	/* Quirk handling. */
3657 	switch (pci_get_devid(dev)) {
3658 	case 0x12258086:		/* Intel 82454KX/GX (Orion) */
3659 		sup_bus = pci_read_config(dev, 0x41, 1);
3660 		if (sup_bus != 0xff) {
3661 			sec_bus = sup_bus + 1;
3662 			sub_bus = sup_bus + 1;
3663 			PCI_WRITE_CONFIG(bus, dev, sec_reg, sec_bus, 1);
3664 			PCI_WRITE_CONFIG(bus, dev, sub_reg, sub_bus, 1);
3665 		}
3666 		break;
3667 
3668 	case 0x00dd10de:
3669 		/* Compaq R3000 BIOS sets wrong subordinate bus number. */
3670 		if ((cp = kern_getenv("smbios.planar.maker")) == NULL)
3671 			break;
3672 		if (strncmp(cp, "Compal", 6) != 0) {
3673 			freeenv(cp);
3674 			break;
3675 		}
3676 		freeenv(cp);
3677 		if ((cp = kern_getenv("smbios.planar.product")) == NULL)
3678 			break;
3679 		if (strncmp(cp, "08A0", 4) != 0) {
3680 			freeenv(cp);
3681 			break;
3682 		}
3683 		freeenv(cp);
3684 		if (sub_bus < 0xa) {
3685 			sub_bus = 0xa;
3686 			PCI_WRITE_CONFIG(bus, dev, sub_reg, sub_bus, 1);
3687 		}
3688 		break;
3689 	}
3690 
3691 	if (bootverbose)
3692 		printf("\tsecbus=%d, subbus=%d\n", sec_bus, sub_bus);
3693 	if (sec_bus > 0 && sub_bus >= sec_bus) {
3694 		start = sec_bus;
3695 		end = sub_bus;
3696 		count = end - start + 1;
3697 
3698 		resource_list_add(rl, PCI_RES_BUS, 0, 0, ~0, count);
3699 
3700 		/*
3701 		 * If requested, clear secondary bus registers in
3702 		 * bridge devices to force a complete renumbering
3703 		 * rather than reserving the existing range.  However,
3704 		 * preserve the existing size.
3705 		 */
3706 		if (pci_clear_buses)
3707 			goto clear;
3708 
3709 		rid = 0;
3710 		res = resource_list_reserve(rl, bus, dev, PCI_RES_BUS, &rid,
3711 		    start, end, count, 0);
3712 		if (res != NULL)
3713 			return;
3714 
3715 		if (bootverbose)
3716 			device_printf(bus,
3717 			    "pci%d:%d:%d:%d secbus failed to allocate\n",
3718 			    pci_get_domain(dev), pci_get_bus(dev),
3719 			    pci_get_slot(dev), pci_get_function(dev));
3720 	}
3721 
3722 clear:
3723 	PCI_WRITE_CONFIG(bus, dev, sec_reg, 0, 1);
3724 	PCI_WRITE_CONFIG(bus, dev, sub_reg, 0, 1);
3725 }
3726 
3727 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)3728 pci_alloc_secbus(device_t dev, device_t child, int *rid, rman_res_t start,
3729     rman_res_t end, rman_res_t count, u_int flags)
3730 {
3731 	struct pci_devinfo *dinfo;
3732 	pcicfgregs *cfg;
3733 	struct resource_list *rl;
3734 	struct resource *res;
3735 	int sec_reg, sub_reg;
3736 
3737 	dinfo = device_get_ivars(child);
3738 	cfg = &dinfo->cfg;
3739 	rl = &dinfo->resources;
3740 	switch (cfg->hdrtype & PCIM_HDRTYPE) {
3741 	case PCIM_HDRTYPE_BRIDGE:
3742 		sec_reg = PCIR_SECBUS_1;
3743 		sub_reg = PCIR_SUBBUS_1;
3744 		break;
3745 	case PCIM_HDRTYPE_CARDBUS:
3746 		sec_reg = PCIR_SECBUS_2;
3747 		sub_reg = PCIR_SUBBUS_2;
3748 		break;
3749 	default:
3750 		return (NULL);
3751 	}
3752 
3753 	if (*rid != 0)
3754 		return (NULL);
3755 
3756 	if (resource_list_find(rl, PCI_RES_BUS, *rid) == NULL)
3757 		resource_list_add(rl, PCI_RES_BUS, *rid, start, end, count);
3758 	if (!resource_list_reserved(rl, PCI_RES_BUS, *rid)) {
3759 		res = resource_list_reserve(rl, dev, child, PCI_RES_BUS, rid,
3760 		    start, end, count, flags & ~RF_ACTIVE);
3761 		if (res == NULL) {
3762 			resource_list_delete(rl, PCI_RES_BUS, *rid);
3763 			device_printf(child, "allocating %ju bus%s failed\n",
3764 			    count, count == 1 ? "" : "es");
3765 			return (NULL);
3766 		}
3767 		if (bootverbose)
3768 			device_printf(child,
3769 			    "Lazy allocation of %ju bus%s at %ju\n", count,
3770 			    count == 1 ? "" : "es", rman_get_start(res));
3771 		PCI_WRITE_CONFIG(dev, child, sec_reg, rman_get_start(res), 1);
3772 		PCI_WRITE_CONFIG(dev, child, sub_reg, rman_get_end(res), 1);
3773 	}
3774 	return (resource_list_alloc(rl, dev, child, PCI_RES_BUS, rid, start,
3775 	    end, count, flags));
3776 }
3777 #endif
3778 
3779 static int
pci_ea_bei_to_rid(device_t dev,int bei)3780 pci_ea_bei_to_rid(device_t dev, int bei)
3781 {
3782 #ifdef PCI_IOV
3783 	struct pci_devinfo *dinfo;
3784 	int iov_pos;
3785 	struct pcicfg_iov *iov;
3786 
3787 	dinfo = device_get_ivars(dev);
3788 	iov = dinfo->cfg.iov;
3789 	if (iov != NULL)
3790 		iov_pos = iov->iov_pos;
3791 	else
3792 		iov_pos = 0;
3793 #endif
3794 
3795 	/* Check if matches BAR */
3796 	if ((bei >= PCIM_EA_BEI_BAR_0) &&
3797 	    (bei <= PCIM_EA_BEI_BAR_5))
3798 		return (PCIR_BAR(bei));
3799 
3800 	/* Check ROM */
3801 	if (bei == PCIM_EA_BEI_ROM)
3802 		return (PCIR_BIOS);
3803 
3804 #ifdef PCI_IOV
3805 	/* Check if matches VF_BAR */
3806 	if ((iov != NULL) && (bei >= PCIM_EA_BEI_VF_BAR_0) &&
3807 	    (bei <= PCIM_EA_BEI_VF_BAR_5))
3808 		return (PCIR_SRIOV_BAR(bei - PCIM_EA_BEI_VF_BAR_0) +
3809 		    iov_pos);
3810 #endif
3811 
3812 	return (-1);
3813 }
3814 
3815 int
pci_ea_is_enabled(device_t dev,int rid)3816 pci_ea_is_enabled(device_t dev, int rid)
3817 {
3818 	struct pci_ea_entry *ea;
3819 	struct pci_devinfo *dinfo;
3820 
3821 	dinfo = device_get_ivars(dev);
3822 
3823 	STAILQ_FOREACH(ea, &dinfo->cfg.ea.ea_entries, eae_link) {
3824 		if (pci_ea_bei_to_rid(dev, ea->eae_bei) == rid)
3825 			return ((ea->eae_flags & PCIM_EA_ENABLE) > 0);
3826 	}
3827 
3828 	return (0);
3829 }
3830 
3831 void
pci_add_resources_ea(device_t bus,device_t dev,int alloc_iov)3832 pci_add_resources_ea(device_t bus, device_t dev, int alloc_iov)
3833 {
3834 	struct pci_ea_entry *ea;
3835 	struct pci_devinfo *dinfo;
3836 	pci_addr_t start, end, count;
3837 	struct resource_list *rl;
3838 	int type, flags, rid;
3839 	struct resource *res;
3840 	uint32_t tmp;
3841 #ifdef PCI_IOV
3842 	struct pcicfg_iov *iov;
3843 #endif
3844 
3845 	dinfo = device_get_ivars(dev);
3846 	rl = &dinfo->resources;
3847 	flags = 0;
3848 
3849 #ifdef PCI_IOV
3850 	iov = dinfo->cfg.iov;
3851 #endif
3852 
3853 	if (dinfo->cfg.ea.ea_location == 0)
3854 		return;
3855 
3856 	STAILQ_FOREACH(ea, &dinfo->cfg.ea.ea_entries, eae_link) {
3857 
3858 		/*
3859 		 * TODO: Ignore EA-BAR if is not enabled.
3860 		 *   Currently the EA implementation supports
3861 		 *   only situation, where EA structure contains
3862 		 *   predefined entries. In case they are not enabled
3863 		 *   leave them unallocated and proceed with
3864 		 *   a legacy-BAR mechanism.
3865 		 */
3866 		if ((ea->eae_flags & PCIM_EA_ENABLE) == 0)
3867 			continue;
3868 
3869 		switch ((ea->eae_flags & PCIM_EA_PP) >> PCIM_EA_PP_OFFSET) {
3870 		case PCIM_EA_P_MEM_PREFETCH:
3871 		case PCIM_EA_P_VF_MEM_PREFETCH:
3872 			flags = RF_PREFETCHABLE;
3873 			/* FALLTHROUGH */
3874 		case PCIM_EA_P_VF_MEM:
3875 		case PCIM_EA_P_MEM:
3876 			type = SYS_RES_MEMORY;
3877 			break;
3878 		case PCIM_EA_P_IO:
3879 			type = SYS_RES_IOPORT;
3880 			break;
3881 		default:
3882 			continue;
3883 		}
3884 
3885 		if (alloc_iov != 0) {
3886 #ifdef PCI_IOV
3887 			/* Allocating IOV, confirm BEI matches */
3888 			if ((ea->eae_bei < PCIM_EA_BEI_VF_BAR_0) ||
3889 			    (ea->eae_bei > PCIM_EA_BEI_VF_BAR_5))
3890 				continue;
3891 #else
3892 			continue;
3893 #endif
3894 		} else {
3895 			/* Allocating BAR, confirm BEI matches */
3896 			if (((ea->eae_bei < PCIM_EA_BEI_BAR_0) ||
3897 			    (ea->eae_bei > PCIM_EA_BEI_BAR_5)) &&
3898 			    (ea->eae_bei != PCIM_EA_BEI_ROM))
3899 				continue;
3900 		}
3901 
3902 		rid = pci_ea_bei_to_rid(dev, ea->eae_bei);
3903 		if (rid < 0)
3904 			continue;
3905 
3906 		/* Skip resources already allocated by EA */
3907 		if ((resource_list_find(rl, SYS_RES_MEMORY, rid) != NULL) ||
3908 		    (resource_list_find(rl, SYS_RES_IOPORT, rid) != NULL))
3909 			continue;
3910 
3911 		start = ea->eae_base;
3912 		count = ea->eae_max_offset + 1;
3913 #ifdef PCI_IOV
3914 		if (iov != NULL)
3915 			count = count * iov->iov_num_vfs;
3916 #endif
3917 		end = start + count - 1;
3918 		if (count == 0)
3919 			continue;
3920 
3921 		resource_list_add(rl, type, rid, start, end, count);
3922 		res = resource_list_reserve(rl, bus, dev, type, &rid, start, end, count,
3923 		    flags);
3924 		if (res == NULL) {
3925 			resource_list_delete(rl, type, rid);
3926 
3927 			/*
3928 			 * Failed to allocate using EA, disable entry.
3929 			 * Another attempt to allocation will be performed
3930 			 * further, but this time using legacy BAR registers
3931 			 */
3932 			tmp = pci_read_config(dev, ea->eae_cfg_offset, 4);
3933 			tmp &= ~PCIM_EA_ENABLE;
3934 			pci_write_config(dev, ea->eae_cfg_offset, tmp, 4);
3935 
3936 			/*
3937 			 * Disabling entry might fail in case it is hardwired.
3938 			 * Read flags again to match current status.
3939 			 */
3940 			ea->eae_flags = pci_read_config(dev, ea->eae_cfg_offset, 4);
3941 
3942 			continue;
3943 		}
3944 
3945 		/* As per specification, fill BAR with zeros */
3946 		pci_write_config(dev, rid, 0, 4);
3947 	}
3948 }
3949 
3950 void
pci_add_resources(device_t bus,device_t dev,int force,uint32_t prefetchmask)3951 pci_add_resources(device_t bus, device_t dev, int force, uint32_t prefetchmask)
3952 {
3953 	struct pci_devinfo *dinfo;
3954 	pcicfgregs *cfg;
3955 	struct resource_list *rl;
3956 	const struct pci_quirk *q;
3957 	uint32_t devid;
3958 	int i;
3959 
3960 	dinfo = device_get_ivars(dev);
3961 	cfg = &dinfo->cfg;
3962 	rl = &dinfo->resources;
3963 	devid = (cfg->device << 16) | cfg->vendor;
3964 
3965 	/* Allocate resources using Enhanced Allocation */
3966 	pci_add_resources_ea(bus, dev, 0);
3967 
3968 	/* ATA devices needs special map treatment */
3969 	if ((pci_get_class(dev) == PCIC_STORAGE) &&
3970 	    (pci_get_subclass(dev) == PCIS_STORAGE_IDE) &&
3971 	    ((pci_get_progif(dev) & PCIP_STORAGE_IDE_MASTERDEV) ||
3972 	     (!pci_read_config(dev, PCIR_BAR(0), 4) &&
3973 	      !pci_read_config(dev, PCIR_BAR(2), 4))) )
3974 		pci_ata_maps(bus, dev, rl, force, prefetchmask);
3975 	else
3976 		for (i = 0; i < cfg->nummaps;) {
3977 			/* Skip resources already managed by EA */
3978 			if ((resource_list_find(rl, SYS_RES_MEMORY, PCIR_BAR(i)) != NULL) ||
3979 			    (resource_list_find(rl, SYS_RES_IOPORT, PCIR_BAR(i)) != NULL) ||
3980 			    pci_ea_is_enabled(dev, PCIR_BAR(i))) {
3981 				i++;
3982 				continue;
3983 			}
3984 
3985 			/*
3986 			 * Skip quirked resources.
3987 			 */
3988 			for (q = &pci_quirks[0]; q->devid != 0; q++)
3989 				if (q->devid == devid &&
3990 				    q->type == PCI_QUIRK_UNMAP_REG &&
3991 				    q->arg1 == PCIR_BAR(i))
3992 					break;
3993 			if (q->devid != 0) {
3994 				i++;
3995 				continue;
3996 			}
3997 			i += pci_add_map(bus, dev, PCIR_BAR(i), rl, force,
3998 			    prefetchmask & (1 << i));
3999 		}
4000 
4001 	/*
4002 	 * Add additional, quirked resources.
4003 	 */
4004 	for (q = &pci_quirks[0]; q->devid != 0; q++)
4005 		if (q->devid == devid && q->type == PCI_QUIRK_MAP_REG)
4006 			pci_add_map(bus, dev, q->arg1, rl, force, 0);
4007 
4008 	if (cfg->intpin > 0 && PCI_INTERRUPT_VALID(cfg->intline)) {
4009 #ifdef __PCI_REROUTE_INTERRUPT
4010 		/*
4011 		 * Try to re-route interrupts. Sometimes the BIOS or
4012 		 * firmware may leave bogus values in these registers.
4013 		 * If the re-route fails, then just stick with what we
4014 		 * have.
4015 		 */
4016 		pci_assign_interrupt(bus, dev, 1);
4017 #else
4018 		pci_assign_interrupt(bus, dev, 0);
4019 #endif
4020 	}
4021 
4022 	if (pci_usb_takeover && pci_get_class(dev) == PCIC_SERIALBUS &&
4023 	    pci_get_subclass(dev) == PCIS_SERIALBUS_USB) {
4024 		if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_XHCI)
4025 			xhci_early_takeover(dev);
4026 		else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_EHCI)
4027 			ehci_early_takeover(dev);
4028 		else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_OHCI)
4029 			ohci_early_takeover(dev);
4030 		else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_UHCI)
4031 			uhci_early_takeover(dev);
4032 	}
4033 
4034 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
4035 	/*
4036 	 * Reserve resources for secondary bus ranges behind bridge
4037 	 * devices.
4038 	 */
4039 	pci_reserve_secbus(bus, dev, cfg, rl);
4040 #endif
4041 }
4042 
4043 static struct pci_devinfo *
pci_identify_function(device_t pcib,device_t dev,int domain,int busno,int slot,int func)4044 pci_identify_function(device_t pcib, device_t dev, int domain, int busno,
4045     int slot, int func)
4046 {
4047 	struct pci_devinfo *dinfo;
4048 
4049 	dinfo = pci_read_device(pcib, dev, domain, busno, slot, func);
4050 	if (dinfo != NULL)
4051 		pci_add_child(dev, dinfo);
4052 
4053 	return (dinfo);
4054 }
4055 
4056 void
pci_add_children(device_t dev,int domain,int busno)4057 pci_add_children(device_t dev, int domain, int busno)
4058 {
4059 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
4060 	device_t pcib = device_get_parent(dev);
4061 	struct pci_devinfo *dinfo;
4062 	int maxslots;
4063 	int s, f, pcifunchigh;
4064 	uint8_t hdrtype;
4065 	int first_func;
4066 
4067 	/*
4068 	 * Try to detect a device at slot 0, function 0.  If it exists, try to
4069 	 * enable ARI.  We must enable ARI before detecting the rest of the
4070 	 * functions on this bus as ARI changes the set of slots and functions
4071 	 * that are legal on this bus.
4072 	 */
4073 	dinfo = pci_identify_function(pcib, dev, domain, busno, 0, 0);
4074 	if (dinfo != NULL && pci_enable_ari)
4075 		PCIB_TRY_ENABLE_ARI(pcib, dinfo->cfg.dev);
4076 
4077 	/*
4078 	 * Start looking for new devices on slot 0 at function 1 because we
4079 	 * just identified the device at slot 0, function 0.
4080 	 */
4081 	first_func = 1;
4082 
4083 	maxslots = PCIB_MAXSLOTS(pcib);
4084 	for (s = 0; s <= maxslots; s++, first_func = 0) {
4085 		pcifunchigh = 0;
4086 		f = 0;
4087 		DELAY(1);
4088 		hdrtype = REG(PCIR_HDRTYPE, 1);
4089 		if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
4090 			continue;
4091 		if (hdrtype & PCIM_MFDEV)
4092 			pcifunchigh = PCIB_MAXFUNCS(pcib);
4093 		for (f = first_func; f <= pcifunchigh; f++)
4094 			pci_identify_function(pcib, dev, domain, busno, s, f);
4095 	}
4096 #undef REG
4097 }
4098 
4099 int
pci_rescan_method(device_t dev)4100 pci_rescan_method(device_t dev)
4101 {
4102 #define	REG(n, w)	PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
4103 	device_t pcib = device_get_parent(dev);
4104 	device_t child, *devlist, *unchanged;
4105 	int devcount, error, i, j, maxslots, oldcount;
4106 	int busno, domain, s, f, pcifunchigh;
4107 	uint8_t hdrtype;
4108 
4109 	/* No need to check for ARI on a rescan. */
4110 	error = device_get_children(dev, &devlist, &devcount);
4111 	if (error)
4112 		return (error);
4113 	if (devcount != 0) {
4114 		unchanged = malloc(devcount * sizeof(device_t), M_TEMP,
4115 		    M_NOWAIT | M_ZERO);
4116 		if (unchanged == NULL) {
4117 			free(devlist, M_TEMP);
4118 			return (ENOMEM);
4119 		}
4120 	} else
4121 		unchanged = NULL;
4122 
4123 	domain = pcib_get_domain(dev);
4124 	busno = pcib_get_bus(dev);
4125 	maxslots = PCIB_MAXSLOTS(pcib);
4126 	for (s = 0; s <= maxslots; s++) {
4127 		/* If function 0 is not present, skip to the next slot. */
4128 		f = 0;
4129 		if (REG(PCIR_VENDOR, 2) == 0xffff)
4130 			continue;
4131 		pcifunchigh = 0;
4132 		hdrtype = REG(PCIR_HDRTYPE, 1);
4133 		if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
4134 			continue;
4135 		if (hdrtype & PCIM_MFDEV)
4136 			pcifunchigh = PCIB_MAXFUNCS(pcib);
4137 		for (f = 0; f <= pcifunchigh; f++) {
4138 			if (REG(PCIR_VENDOR, 2) == 0xffff)
4139 				continue;
4140 
4141 			/*
4142 			 * Found a valid function.  Check if a
4143 			 * device_t for this device already exists.
4144 			 */
4145 			for (i = 0; i < devcount; i++) {
4146 				child = devlist[i];
4147 				if (child == NULL)
4148 					continue;
4149 				if (pci_get_slot(child) == s &&
4150 				    pci_get_function(child) == f) {
4151 					unchanged[i] = child;
4152 					goto next_func;
4153 				}
4154 			}
4155 
4156 			pci_identify_function(pcib, dev, domain, busno, s, f);
4157 		next_func:;
4158 		}
4159 	}
4160 
4161 	/* Remove devices that are no longer present. */
4162 	for (i = 0; i < devcount; i++) {
4163 		if (unchanged[i] != NULL)
4164 			continue;
4165 		device_delete_child(dev, devlist[i]);
4166 	}
4167 
4168 	free(devlist, M_TEMP);
4169 	oldcount = devcount;
4170 
4171 	/* Try to attach the devices just added. */
4172 	error = device_get_children(dev, &devlist, &devcount);
4173 	if (error) {
4174 		free(unchanged, M_TEMP);
4175 		return (error);
4176 	}
4177 
4178 	for (i = 0; i < devcount; i++) {
4179 		for (j = 0; j < oldcount; j++) {
4180 			if (devlist[i] == unchanged[j])
4181 				goto next_device;
4182 		}
4183 
4184 		device_probe_and_attach(devlist[i]);
4185 	next_device:;
4186 	}
4187 
4188 	free(unchanged, M_TEMP);
4189 	free(devlist, M_TEMP);
4190 	return (0);
4191 #undef REG
4192 }
4193 
4194 #ifdef PCI_IOV
4195 device_t
pci_add_iov_child(device_t bus,device_t pf,uint16_t rid,uint16_t vid,uint16_t did)4196 pci_add_iov_child(device_t bus, device_t pf, uint16_t rid, uint16_t vid,
4197     uint16_t did)
4198 {
4199 	struct pci_devinfo *vf_dinfo;
4200 	device_t pcib;
4201 	int busno, slot, func;
4202 
4203 	pcib = device_get_parent(bus);
4204 
4205 	PCIB_DECODE_RID(pcib, rid, &busno, &slot, &func);
4206 
4207 	vf_dinfo = pci_fill_devinfo(pcib, bus, pci_get_domain(pcib), busno,
4208 	    slot, func, vid, did);
4209 
4210 	vf_dinfo->cfg.flags |= PCICFG_VF;
4211 	pci_add_child(bus, vf_dinfo);
4212 
4213 	return (vf_dinfo->cfg.dev);
4214 }
4215 
4216 device_t
pci_create_iov_child_method(device_t bus,device_t pf,uint16_t rid,uint16_t vid,uint16_t did)4217 pci_create_iov_child_method(device_t bus, device_t pf, uint16_t rid,
4218     uint16_t vid, uint16_t did)
4219 {
4220 
4221 	return (pci_add_iov_child(bus, pf, rid, vid, did));
4222 }
4223 #endif
4224 
4225 static void
pci_add_child_clear_aer(device_t dev,struct pci_devinfo * dinfo)4226 pci_add_child_clear_aer(device_t dev, struct pci_devinfo *dinfo)
4227 {
4228 	int aer;
4229 	uint32_t r;
4230 	uint16_t r2;
4231 
4232 	if (dinfo->cfg.pcie.pcie_location != 0 &&
4233 	    dinfo->cfg.pcie.pcie_type == PCIEM_TYPE_ROOT_PORT) {
4234 		r2 = pci_read_config(dev, dinfo->cfg.pcie.pcie_location +
4235 		    PCIER_ROOT_CTL, 2);
4236 		r2 &= ~(PCIEM_ROOT_CTL_SERR_CORR |
4237 		    PCIEM_ROOT_CTL_SERR_NONFATAL | PCIEM_ROOT_CTL_SERR_FATAL);
4238 		pci_write_config(dev, dinfo->cfg.pcie.pcie_location +
4239 		    PCIER_ROOT_CTL, r2, 2);
4240 	}
4241 	if (pci_find_extcap(dev, PCIZ_AER, &aer) == 0) {
4242 		r = pci_read_config(dev, aer + PCIR_AER_UC_STATUS, 4);
4243 		pci_write_config(dev, aer + PCIR_AER_UC_STATUS, r, 4);
4244 		if (r != 0 && bootverbose) {
4245 			pci_printf(&dinfo->cfg,
4246 			    "clearing AER UC 0x%08x -> 0x%08x\n",
4247 			    r, pci_read_config(dev, aer + PCIR_AER_UC_STATUS,
4248 			    4));
4249 		}
4250 
4251 		r = pci_read_config(dev, aer + PCIR_AER_UC_MASK, 4);
4252 		r &= ~(PCIM_AER_UC_TRAINING_ERROR |
4253 		    PCIM_AER_UC_DL_PROTOCOL_ERROR |
4254 		    PCIM_AER_UC_SURPRISE_LINK_DOWN |
4255 		    PCIM_AER_UC_POISONED_TLP |
4256 		    PCIM_AER_UC_FC_PROTOCOL_ERROR |
4257 		    PCIM_AER_UC_COMPLETION_TIMEOUT |
4258 		    PCIM_AER_UC_COMPLETER_ABORT |
4259 		    PCIM_AER_UC_UNEXPECTED_COMPLETION |
4260 		    PCIM_AER_UC_RECEIVER_OVERFLOW |
4261 		    PCIM_AER_UC_MALFORMED_TLP |
4262 		    PCIM_AER_UC_ECRC_ERROR |
4263 		    PCIM_AER_UC_UNSUPPORTED_REQUEST |
4264 		    PCIM_AER_UC_ACS_VIOLATION |
4265 		    PCIM_AER_UC_INTERNAL_ERROR |
4266 		    PCIM_AER_UC_MC_BLOCKED_TLP |
4267 		    PCIM_AER_UC_ATOMIC_EGRESS_BLK |
4268 		    PCIM_AER_UC_TLP_PREFIX_BLOCKED);
4269 		pci_write_config(dev, aer + PCIR_AER_UC_MASK, r, 4);
4270 
4271 		r = pci_read_config(dev, aer + PCIR_AER_COR_STATUS, 4);
4272 		pci_write_config(dev, aer + PCIR_AER_COR_STATUS, r, 4);
4273 		if (r != 0 && bootverbose) {
4274 			pci_printf(&dinfo->cfg,
4275 			    "clearing AER COR 0x%08x -> 0x%08x\n",
4276 			    r, pci_read_config(dev, aer + PCIR_AER_COR_STATUS,
4277 			    4));
4278 		}
4279 
4280 		r = pci_read_config(dev, aer + PCIR_AER_COR_MASK, 4);
4281 		r &= ~(PCIM_AER_COR_RECEIVER_ERROR |
4282 		    PCIM_AER_COR_BAD_TLP |
4283 		    PCIM_AER_COR_BAD_DLLP |
4284 		    PCIM_AER_COR_REPLAY_ROLLOVER |
4285 		    PCIM_AER_COR_REPLAY_TIMEOUT |
4286 		    PCIM_AER_COR_ADVISORY_NF_ERROR |
4287 		    PCIM_AER_COR_INTERNAL_ERROR |
4288 		    PCIM_AER_COR_HEADER_LOG_OVFLOW);
4289 		pci_write_config(dev, aer + PCIR_AER_COR_MASK, r, 4);
4290 
4291 		r = pci_read_config(dev, dinfo->cfg.pcie.pcie_location +
4292 		    PCIER_DEVICE_CTL, 2);
4293 		r |=  PCIEM_CTL_COR_ENABLE | PCIEM_CTL_NFER_ENABLE |
4294 		    PCIEM_CTL_FER_ENABLE | PCIEM_CTL_URR_ENABLE;
4295 		pci_write_config(dev, dinfo->cfg.pcie.pcie_location +
4296 		    PCIER_DEVICE_CTL, r, 2);
4297 	}
4298 }
4299 
4300 void
pci_add_child(device_t bus,struct pci_devinfo * dinfo)4301 pci_add_child(device_t bus, struct pci_devinfo *dinfo)
4302 {
4303 	device_t dev;
4304 
4305 	dinfo->cfg.dev = dev = device_add_child(bus, NULL, -1);
4306 	device_set_ivars(dev, dinfo);
4307 	resource_list_init(&dinfo->resources);
4308 	pci_cfg_save(dev, dinfo, 0);
4309 	pci_cfg_restore(dev, dinfo);
4310 	pci_print_verbose(dinfo);
4311 	pci_add_resources(bus, dev, 0, 0);
4312 	pci_child_added(dinfo->cfg.dev);
4313 
4314 	if (pci_clear_aer_on_attach)
4315 		pci_add_child_clear_aer(dev, dinfo);
4316 
4317 	EVENTHANDLER_INVOKE(pci_add_device, dinfo->cfg.dev);
4318 }
4319 
4320 void
pci_child_added_method(device_t dev,device_t child)4321 pci_child_added_method(device_t dev, device_t child)
4322 {
4323 
4324 }
4325 
4326 static int
pci_probe(device_t dev)4327 pci_probe(device_t dev)
4328 {
4329 
4330 	device_set_desc(dev, "PCI bus");
4331 
4332 	/* Allow other subclasses to override this driver. */
4333 	return (BUS_PROBE_GENERIC);
4334 }
4335 
4336 int
pci_attach_common(device_t dev)4337 pci_attach_common(device_t dev)
4338 {
4339 	struct pci_softc *sc;
4340 	int busno, domain;
4341 #ifdef PCI_DMA_BOUNDARY
4342 	int error, tag_valid;
4343 #endif
4344 #ifdef PCI_RES_BUS
4345 	int rid;
4346 #endif
4347 
4348 	sc = device_get_softc(dev);
4349 	domain = pcib_get_domain(dev);
4350 	busno = pcib_get_bus(dev);
4351 #ifdef PCI_RES_BUS
4352 	rid = 0;
4353 	sc->sc_bus = bus_alloc_resource(dev, PCI_RES_BUS, &rid, busno, busno,
4354 	    1, 0);
4355 	if (sc->sc_bus == NULL) {
4356 		device_printf(dev, "failed to allocate bus number\n");
4357 		return (ENXIO);
4358 	}
4359 #endif
4360 	if (bootverbose)
4361 		device_printf(dev, "domain=%d, physical bus=%d\n",
4362 		    domain, busno);
4363 #ifdef PCI_DMA_BOUNDARY
4364 	tag_valid = 0;
4365 	if (device_get_devclass(device_get_parent(device_get_parent(dev))) !=
4366 	    devclass_find("pci")) {
4367 		error = bus_dma_tag_create(bus_get_dma_tag(dev), 1,
4368 		    PCI_DMA_BOUNDARY, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
4369 		    NULL, NULL, BUS_SPACE_MAXSIZE, BUS_SPACE_UNRESTRICTED,
4370 		    BUS_SPACE_MAXSIZE, 0, NULL, NULL, &sc->sc_dma_tag);
4371 		if (error)
4372 			device_printf(dev, "Failed to create DMA tag: %d\n",
4373 			    error);
4374 		else
4375 			tag_valid = 1;
4376 	}
4377 	if (!tag_valid)
4378 #endif
4379 		sc->sc_dma_tag = bus_get_dma_tag(dev);
4380 	return (0);
4381 }
4382 
4383 static int
pci_attach(device_t dev)4384 pci_attach(device_t dev)
4385 {
4386 	int busno, domain, error;
4387 
4388 	error = pci_attach_common(dev);
4389 	if (error)
4390 		return (error);
4391 
4392 	/*
4393 	 * Since there can be multiple independently numbered PCI
4394 	 * buses on systems with multiple PCI domains, we can't use
4395 	 * the unit number to decide which bus we are probing. We ask
4396 	 * the parent pcib what our domain and bus numbers are.
4397 	 */
4398 	domain = pcib_get_domain(dev);
4399 	busno = pcib_get_bus(dev);
4400 	pci_add_children(dev, domain, busno);
4401 	return (bus_generic_attach(dev));
4402 }
4403 
4404 static int
pci_detach(device_t dev)4405 pci_detach(device_t dev)
4406 {
4407 #ifdef PCI_RES_BUS
4408 	struct pci_softc *sc;
4409 #endif
4410 	int error;
4411 
4412 	error = bus_generic_detach(dev);
4413 	if (error)
4414 		return (error);
4415 #ifdef PCI_RES_BUS
4416 	sc = device_get_softc(dev);
4417 	error = bus_release_resource(dev, PCI_RES_BUS, 0, sc->sc_bus);
4418 	if (error)
4419 		return (error);
4420 #endif
4421 	return (device_delete_children(dev));
4422 }
4423 
4424 static void
pci_hint_device_unit(device_t dev,device_t child,const char * name,int * unitp)4425 pci_hint_device_unit(device_t dev, device_t child, const char *name, int *unitp)
4426 {
4427 	int line, unit;
4428 	const char *at;
4429 	char me1[24], me2[32];
4430 	uint8_t b, s, f;
4431 	uint32_t d;
4432 
4433 	d = pci_get_domain(child);
4434 	b = pci_get_bus(child);
4435 	s = pci_get_slot(child);
4436 	f = pci_get_function(child);
4437 	snprintf(me1, sizeof(me1), "pci%u:%u:%u", b, s, f);
4438 	snprintf(me2, sizeof(me2), "pci%u:%u:%u:%u", d, b, s, f);
4439 	line = 0;
4440 	while (resource_find_dev(&line, name, &unit, "at", NULL) == 0) {
4441 		resource_string_value(name, unit, "at", &at);
4442 		if (strcmp(at, me1) != 0 && strcmp(at, me2) != 0)
4443 			continue; /* No match, try next candidate */
4444 		*unitp = unit;
4445 		return;
4446 	}
4447 }
4448 
4449 static void
pci_set_power_child(device_t dev,device_t child,int state)4450 pci_set_power_child(device_t dev, device_t child, int state)
4451 {
4452 	device_t pcib;
4453 	int dstate;
4454 
4455 	/*
4456 	 * Set the device to the given state.  If the firmware suggests
4457 	 * a different power state, use it instead.  If power management
4458 	 * is not present, the firmware is responsible for managing
4459 	 * device power.  Skip children who aren't attached since they
4460 	 * are handled separately.
4461 	 */
4462 	pcib = device_get_parent(dev);
4463 	dstate = state;
4464 	if (device_is_attached(child) &&
4465 	    PCIB_POWER_FOR_SLEEP(pcib, child, &dstate) == 0)
4466 		pci_set_powerstate(child, dstate);
4467 }
4468 
4469 int
pci_suspend_child(device_t dev,device_t child)4470 pci_suspend_child(device_t dev, device_t child)
4471 {
4472 	struct pci_devinfo *dinfo;
4473 	struct resource_list_entry *rle;
4474 	int error;
4475 
4476 	dinfo = device_get_ivars(child);
4477 
4478 	/*
4479 	 * Save the PCI configuration space for the child and set the
4480 	 * device in the appropriate power state for this sleep state.
4481 	 */
4482 	pci_cfg_save(child, dinfo, 0);
4483 
4484 	/* Suspend devices before potentially powering them down. */
4485 	error = bus_generic_suspend_child(dev, child);
4486 
4487 	if (error)
4488 		return (error);
4489 
4490 	if (pci_do_power_suspend) {
4491 		/*
4492 		 * Make sure this device's interrupt handler is not invoked
4493 		 * in the case the device uses a shared interrupt that can
4494 		 * be raised by some other device.
4495 		 * This is applicable only to regular (legacy) PCI interrupts
4496 		 * as MSI/MSI-X interrupts are never shared.
4497 		 */
4498 		rle = resource_list_find(&dinfo->resources,
4499 		    SYS_RES_IRQ, 0);
4500 		if (rle != NULL && rle->res != NULL)
4501 			(void)bus_suspend_intr(child, rle->res);
4502 		pci_set_power_child(dev, child, PCI_POWERSTATE_D3);
4503 	}
4504 
4505 	return (0);
4506 }
4507 
4508 int
pci_resume_child(device_t dev,device_t child)4509 pci_resume_child(device_t dev, device_t child)
4510 {
4511 	struct pci_devinfo *dinfo;
4512 	struct resource_list_entry *rle;
4513 
4514 	if (pci_do_power_resume)
4515 		pci_set_power_child(dev, child, PCI_POWERSTATE_D0);
4516 
4517 	dinfo = device_get_ivars(child);
4518 	pci_cfg_restore(child, dinfo);
4519 	if (!device_is_attached(child))
4520 		pci_cfg_save(child, dinfo, 1);
4521 
4522 	bus_generic_resume_child(dev, child);
4523 
4524 	/*
4525 	 * Allow interrupts only after fully resuming the driver and hardware.
4526 	 */
4527 	if (pci_do_power_suspend) {
4528 		/* See pci_suspend_child for details. */
4529 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, 0);
4530 		if (rle != NULL && rle->res != NULL)
4531 			(void)bus_resume_intr(child, rle->res);
4532 	}
4533 
4534 	return (0);
4535 }
4536 
4537 int
pci_resume(device_t dev)4538 pci_resume(device_t dev)
4539 {
4540 	device_t child, *devlist;
4541 	int error, i, numdevs;
4542 
4543 	if ((error = device_get_children(dev, &devlist, &numdevs)) != 0)
4544 		return (error);
4545 
4546 	/*
4547 	 * Resume critical devices first, then everything else later.
4548 	 */
4549 	for (i = 0; i < numdevs; i++) {
4550 		child = devlist[i];
4551 		switch (pci_get_class(child)) {
4552 		case PCIC_DISPLAY:
4553 		case PCIC_MEMORY:
4554 		case PCIC_BRIDGE:
4555 		case PCIC_BASEPERIPH:
4556 			BUS_RESUME_CHILD(dev, child);
4557 			break;
4558 		}
4559 	}
4560 	for (i = 0; i < numdevs; i++) {
4561 		child = devlist[i];
4562 		switch (pci_get_class(child)) {
4563 		case PCIC_DISPLAY:
4564 		case PCIC_MEMORY:
4565 		case PCIC_BRIDGE:
4566 		case PCIC_BASEPERIPH:
4567 			break;
4568 		default:
4569 			BUS_RESUME_CHILD(dev, child);
4570 		}
4571 	}
4572 	free(devlist, M_TEMP);
4573 	return (0);
4574 }
4575 
4576 static void
pci_load_vendor_data(void)4577 pci_load_vendor_data(void)
4578 {
4579 	caddr_t data;
4580 	void *ptr;
4581 	size_t sz;
4582 
4583 	data = preload_search_by_type("pci_vendor_data");
4584 	if (data != NULL) {
4585 		ptr = preload_fetch_addr(data);
4586 		sz = preload_fetch_size(data);
4587 		if (ptr != NULL && sz != 0) {
4588 			pci_vendordata = ptr;
4589 			pci_vendordata_size = sz;
4590 			/* terminate the database */
4591 			pci_vendordata[pci_vendordata_size] = '\n';
4592 		}
4593 	}
4594 }
4595 
4596 void
pci_driver_added(device_t dev,driver_t * driver)4597 pci_driver_added(device_t dev, driver_t *driver)
4598 {
4599 	int numdevs;
4600 	device_t *devlist;
4601 	device_t child;
4602 	struct pci_devinfo *dinfo;
4603 	int i;
4604 
4605 	if (bootverbose)
4606 		device_printf(dev, "driver added\n");
4607 	DEVICE_IDENTIFY(driver, dev);
4608 	if (device_get_children(dev, &devlist, &numdevs) != 0)
4609 		return;
4610 	for (i = 0; i < numdevs; i++) {
4611 		child = devlist[i];
4612 		if (device_get_state(child) != DS_NOTPRESENT)
4613 			continue;
4614 		dinfo = device_get_ivars(child);
4615 		pci_print_verbose(dinfo);
4616 		if (bootverbose)
4617 			pci_printf(&dinfo->cfg, "reprobing on driver added\n");
4618 		pci_cfg_restore(child, dinfo);
4619 		if (device_probe_and_attach(child) != 0)
4620 			pci_child_detached(dev, child);
4621 	}
4622 	free(devlist, M_TEMP);
4623 }
4624 
4625 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)4626 pci_setup_intr(device_t dev, device_t child, struct resource *irq, int flags,
4627     driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep)
4628 {
4629 	struct pci_devinfo *dinfo;
4630 	struct msix_table_entry *mte;
4631 	struct msix_vector *mv;
4632 	uint64_t addr;
4633 	uint32_t data;
4634 	void *cookie;
4635 	int error, rid;
4636 
4637 	error = bus_generic_setup_intr(dev, child, irq, flags, filter, intr,
4638 	    arg, &cookie);
4639 	if (error)
4640 		return (error);
4641 
4642 	/* If this is not a direct child, just bail out. */
4643 	if (device_get_parent(child) != dev) {
4644 		*cookiep = cookie;
4645 		return(0);
4646 	}
4647 
4648 	rid = rman_get_rid(irq);
4649 	if (rid == 0) {
4650 		/* Make sure that INTx is enabled */
4651 		pci_clear_command_bit(dev, child, PCIM_CMD_INTxDIS);
4652 	} else {
4653 		/*
4654 		 * Check to see if the interrupt is MSI or MSI-X.
4655 		 * Ask our parent to map the MSI and give
4656 		 * us the address and data register values.
4657 		 * If we fail for some reason, teardown the
4658 		 * interrupt handler.
4659 		 */
4660 		dinfo = device_get_ivars(child);
4661 		if (dinfo->cfg.msi.msi_alloc > 0) {
4662 			if (dinfo->cfg.msi.msi_addr == 0) {
4663 				KASSERT(dinfo->cfg.msi.msi_handlers == 0,
4664 			    ("MSI has handlers, but vectors not mapped"));
4665 				error = PCIB_MAP_MSI(device_get_parent(dev),
4666 				    child, rman_get_start(irq), &addr, &data);
4667 				if (error)
4668 					goto bad;
4669 				dinfo->cfg.msi.msi_addr = addr;
4670 				dinfo->cfg.msi.msi_data = data;
4671 			}
4672 			if (dinfo->cfg.msi.msi_handlers == 0)
4673 				pci_enable_msi(child, dinfo->cfg.msi.msi_addr,
4674 				    dinfo->cfg.msi.msi_data);
4675 			dinfo->cfg.msi.msi_handlers++;
4676 		} else {
4677 			KASSERT(dinfo->cfg.msix.msix_alloc > 0,
4678 			    ("No MSI or MSI-X interrupts allocated"));
4679 			KASSERT(rid <= dinfo->cfg.msix.msix_table_len,
4680 			    ("MSI-X index too high"));
4681 			mte = &dinfo->cfg.msix.msix_table[rid - 1];
4682 			KASSERT(mte->mte_vector != 0, ("no message vector"));
4683 			mv = &dinfo->cfg.msix.msix_vectors[mte->mte_vector - 1];
4684 			KASSERT(mv->mv_irq == rman_get_start(irq),
4685 			    ("IRQ mismatch"));
4686 			if (mv->mv_address == 0) {
4687 				KASSERT(mte->mte_handlers == 0,
4688 		    ("MSI-X table entry has handlers, but vector not mapped"));
4689 				error = PCIB_MAP_MSI(device_get_parent(dev),
4690 				    child, rman_get_start(irq), &addr, &data);
4691 				if (error)
4692 					goto bad;
4693 				mv->mv_address = addr;
4694 				mv->mv_data = data;
4695 			}
4696 
4697 			/*
4698 			 * The MSIX table entry must be made valid by
4699 			 * incrementing the mte_handlers before
4700 			 * calling pci_enable_msix() and
4701 			 * pci_resume_msix(). Else the MSIX rewrite
4702 			 * table quirk will not work as expected.
4703 			 */
4704 			mte->mte_handlers++;
4705 			if (mte->mte_handlers == 1) {
4706 				pci_enable_msix(child, rid - 1, mv->mv_address,
4707 				    mv->mv_data);
4708 				pci_unmask_msix(child, rid - 1);
4709 			}
4710 		}
4711 
4712 		/*
4713 		 * Make sure that INTx is disabled if we are using MSI/MSI-X,
4714 		 * unless the device is affected by PCI_QUIRK_MSI_INTX_BUG,
4715 		 * in which case we "enable" INTx so MSI/MSI-X actually works.
4716 		 */
4717 		if (!pci_has_quirk(pci_get_devid(child),
4718 		    PCI_QUIRK_MSI_INTX_BUG))
4719 			pci_set_command_bit(dev, child, PCIM_CMD_INTxDIS);
4720 		else
4721 			pci_clear_command_bit(dev, child, PCIM_CMD_INTxDIS);
4722 	bad:
4723 		if (error) {
4724 			(void)bus_generic_teardown_intr(dev, child, irq,
4725 			    cookie);
4726 			return (error);
4727 		}
4728 	}
4729 	*cookiep = cookie;
4730 	return (0);
4731 }
4732 
4733 int
pci_teardown_intr(device_t dev,device_t child,struct resource * irq,void * cookie)4734 pci_teardown_intr(device_t dev, device_t child, struct resource *irq,
4735     void *cookie)
4736 {
4737 	struct msix_table_entry *mte;
4738 	struct resource_list_entry *rle;
4739 	struct pci_devinfo *dinfo;
4740 	int error, rid;
4741 
4742 	if (irq == NULL || !(rman_get_flags(irq) & RF_ACTIVE))
4743 		return (EINVAL);
4744 
4745 	/* If this isn't a direct child, just bail out */
4746 	if (device_get_parent(child) != dev)
4747 		return(bus_generic_teardown_intr(dev, child, irq, cookie));
4748 
4749 	rid = rman_get_rid(irq);
4750 	if (rid == 0) {
4751 		/* Mask INTx */
4752 		pci_set_command_bit(dev, child, PCIM_CMD_INTxDIS);
4753 	} else {
4754 		/*
4755 		 * Check to see if the interrupt is MSI or MSI-X.  If so,
4756 		 * decrement the appropriate handlers count and mask the
4757 		 * MSI-X message, or disable MSI messages if the count
4758 		 * drops to 0.
4759 		 */
4760 		dinfo = device_get_ivars(child);
4761 		rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, rid);
4762 		if (rle->res != irq)
4763 			return (EINVAL);
4764 		if (dinfo->cfg.msi.msi_alloc > 0) {
4765 			KASSERT(rid <= dinfo->cfg.msi.msi_alloc,
4766 			    ("MSI-X index too high"));
4767 			if (dinfo->cfg.msi.msi_handlers == 0)
4768 				return (EINVAL);
4769 			dinfo->cfg.msi.msi_handlers--;
4770 			if (dinfo->cfg.msi.msi_handlers == 0)
4771 				pci_disable_msi(child);
4772 		} else {
4773 			KASSERT(dinfo->cfg.msix.msix_alloc > 0,
4774 			    ("No MSI or MSI-X interrupts allocated"));
4775 			KASSERT(rid <= dinfo->cfg.msix.msix_table_len,
4776 			    ("MSI-X index too high"));
4777 			mte = &dinfo->cfg.msix.msix_table[rid - 1];
4778 			if (mte->mte_handlers == 0)
4779 				return (EINVAL);
4780 			mte->mte_handlers--;
4781 			if (mte->mte_handlers == 0)
4782 				pci_mask_msix(child, rid - 1);
4783 		}
4784 	}
4785 	error = bus_generic_teardown_intr(dev, child, irq, cookie);
4786 	if (rid > 0)
4787 		KASSERT(error == 0,
4788 		    ("%s: generic teardown failed for MSI/MSI-X", __func__));
4789 	return (error);
4790 }
4791 
4792 int
pci_print_child(device_t dev,device_t child)4793 pci_print_child(device_t dev, device_t child)
4794 {
4795 	struct pci_devinfo *dinfo;
4796 	struct resource_list *rl;
4797 	int retval = 0;
4798 
4799 	dinfo = device_get_ivars(child);
4800 	rl = &dinfo->resources;
4801 
4802 	retval += bus_print_child_header(dev, child);
4803 
4804 	retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#jx");
4805 	retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY, "%#jx");
4806 	retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%jd");
4807 	if (device_get_flags(dev))
4808 		retval += printf(" flags %#x", device_get_flags(dev));
4809 
4810 	retval += printf(" at device %d.%d", pci_get_slot(child),
4811 	    pci_get_function(child));
4812 
4813 	retval += bus_print_child_domain(dev, child);
4814 	retval += bus_print_child_footer(dev, child);
4815 
4816 	return (retval);
4817 }
4818 
4819 static const struct
4820 {
4821 	int		class;
4822 	int		subclass;
4823 	int		report; /* 0 = bootverbose, 1 = always */
4824 	const char	*desc;
4825 } pci_nomatch_tab[] = {
4826 	{PCIC_OLD,		-1,			1, "old"},
4827 	{PCIC_OLD,		PCIS_OLD_NONVGA,	1, "non-VGA display device"},
4828 	{PCIC_OLD,		PCIS_OLD_VGA,		1, "VGA-compatible display device"},
4829 	{PCIC_STORAGE,		-1,			1, "mass storage"},
4830 	{PCIC_STORAGE,		PCIS_STORAGE_SCSI,	1, "SCSI"},
4831 	{PCIC_STORAGE,		PCIS_STORAGE_IDE,	1, "ATA"},
4832 	{PCIC_STORAGE,		PCIS_STORAGE_FLOPPY,	1, "floppy disk"},
4833 	{PCIC_STORAGE,		PCIS_STORAGE_IPI,	1, "IPI"},
4834 	{PCIC_STORAGE,		PCIS_STORAGE_RAID,	1, "RAID"},
4835 	{PCIC_STORAGE,		PCIS_STORAGE_ATA_ADMA,	1, "ATA (ADMA)"},
4836 	{PCIC_STORAGE,		PCIS_STORAGE_SATA,	1, "SATA"},
4837 	{PCIC_STORAGE,		PCIS_STORAGE_SAS,	1, "SAS"},
4838 	{PCIC_STORAGE,		PCIS_STORAGE_NVM,	1, "NVM"},
4839 	{PCIC_NETWORK,		-1,			1, "network"},
4840 	{PCIC_NETWORK,		PCIS_NETWORK_ETHERNET,	1, "ethernet"},
4841 	{PCIC_NETWORK,		PCIS_NETWORK_TOKENRING,	1, "token ring"},
4842 	{PCIC_NETWORK,		PCIS_NETWORK_FDDI,	1, "fddi"},
4843 	{PCIC_NETWORK,		PCIS_NETWORK_ATM,	1, "ATM"},
4844 	{PCIC_NETWORK,		PCIS_NETWORK_ISDN,	1, "ISDN"},
4845 	{PCIC_DISPLAY,		-1,			1, "display"},
4846 	{PCIC_DISPLAY,		PCIS_DISPLAY_VGA,	1, "VGA"},
4847 	{PCIC_DISPLAY,		PCIS_DISPLAY_XGA,	1, "XGA"},
4848 	{PCIC_DISPLAY,		PCIS_DISPLAY_3D,	1, "3D"},
4849 	{PCIC_MULTIMEDIA,	-1,			1, "multimedia"},
4850 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_VIDEO,	1, "video"},
4851 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_AUDIO,	1, "audio"},
4852 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_TELE,	1, "telephony"},
4853 	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_HDA,	1, "HDA"},
4854 	{PCIC_MEMORY,		-1,			1, "memory"},
4855 	{PCIC_MEMORY,		PCIS_MEMORY_RAM,	1, "RAM"},
4856 	{PCIC_MEMORY,		PCIS_MEMORY_FLASH,	1, "flash"},
4857 	{PCIC_BRIDGE,		-1,			1, "bridge"},
4858 	{PCIC_BRIDGE,		PCIS_BRIDGE_HOST,	1, "HOST-PCI"},
4859 	{PCIC_BRIDGE,		PCIS_BRIDGE_ISA,	1, "PCI-ISA"},
4860 	{PCIC_BRIDGE,		PCIS_BRIDGE_EISA,	1, "PCI-EISA"},
4861 	{PCIC_BRIDGE,		PCIS_BRIDGE_MCA,	1, "PCI-MCA"},
4862 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI,	1, "PCI-PCI"},
4863 	{PCIC_BRIDGE,		PCIS_BRIDGE_PCMCIA,	1, "PCI-PCMCIA"},
4864 	{PCIC_BRIDGE,		PCIS_BRIDGE_NUBUS,	1, "PCI-NuBus"},
4865 	{PCIC_BRIDGE,		PCIS_BRIDGE_CARDBUS,	1, "PCI-CardBus"},
4866 	{PCIC_BRIDGE,		PCIS_BRIDGE_RACEWAY,	1, "PCI-RACEway"},
4867 	{PCIC_SIMPLECOMM,	-1,			1, "simple comms"},
4868 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_UART,	1, "UART"},	/* could detect 16550 */
4869 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_PAR,	1, "parallel port"},
4870 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MULSER,	1, "multiport serial"},
4871 	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_MODEM,	1, "generic modem"},
4872 	{PCIC_BASEPERIPH,	-1,			0, "base peripheral"},
4873 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PIC,	1, "interrupt controller"},
4874 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_DMA,	1, "DMA controller"},
4875 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_TIMER,	1, "timer"},
4876 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RTC,	1, "realtime clock"},
4877 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PCIHOT,	1, "PCI hot-plug controller"},
4878 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_SDHC,	1, "SD host controller"},
4879 	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_IOMMU,	1, "IOMMU"},
4880 	{PCIC_INPUTDEV,		-1,			1, "input device"},
4881 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_KEYBOARD,	1, "keyboard"},
4882 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_DIGITIZER,1, "digitizer"},
4883 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_MOUSE,	1, "mouse"},
4884 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_SCANNER,	1, "scanner"},
4885 	{PCIC_INPUTDEV,		PCIS_INPUTDEV_GAMEPORT,	1, "gameport"},
4886 	{PCIC_DOCKING,		-1,			1, "docking station"},
4887 	{PCIC_PROCESSOR,	-1,			1, "processor"},
4888 	{PCIC_SERIALBUS,	-1,			1, "serial bus"},
4889 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FW,	1, "FireWire"},
4890 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_ACCESS,	1, "AccessBus"},
4891 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SSA,	1, "SSA"},
4892 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_USB,	1, "USB"},
4893 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FC,	1, "Fibre Channel"},
4894 	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SMBUS,	0, "SMBus"},
4895 	{PCIC_WIRELESS,		-1,			1, "wireless controller"},
4896 	{PCIC_WIRELESS,		PCIS_WIRELESS_IRDA,	1, "iRDA"},
4897 	{PCIC_WIRELESS,		PCIS_WIRELESS_IR,	1, "IR"},
4898 	{PCIC_WIRELESS,		PCIS_WIRELESS_RF,	1, "RF"},
4899 	{PCIC_INTELLIIO,	-1,			1, "intelligent I/O controller"},
4900 	{PCIC_INTELLIIO,	PCIS_INTELLIIO_I2O,	1, "I2O"},
4901 	{PCIC_SATCOM,		-1,			1, "satellite communication"},
4902 	{PCIC_SATCOM,		PCIS_SATCOM_TV,		1, "sat TV"},
4903 	{PCIC_SATCOM,		PCIS_SATCOM_AUDIO,	1, "sat audio"},
4904 	{PCIC_SATCOM,		PCIS_SATCOM_VOICE,	1, "sat voice"},
4905 	{PCIC_SATCOM,		PCIS_SATCOM_DATA,	1, "sat data"},
4906 	{PCIC_CRYPTO,		-1,			1, "encrypt/decrypt"},
4907 	{PCIC_CRYPTO,		PCIS_CRYPTO_NETCOMP,	1, "network/computer crypto"},
4908 	{PCIC_CRYPTO,		PCIS_CRYPTO_ENTERTAIN,	1, "entertainment crypto"},
4909 	{PCIC_DASP,		-1,			0, "dasp"},
4910 	{PCIC_DASP,		PCIS_DASP_DPIO,		1, "DPIO module"},
4911 	{PCIC_DASP,		PCIS_DASP_PERFCNTRS,	1, "performance counters"},
4912 	{PCIC_DASP,		PCIS_DASP_COMM_SYNC,	1, "communication synchronizer"},
4913 	{PCIC_DASP,		PCIS_DASP_MGMT_CARD,	1, "signal processing management"},
4914 	{0, 0, 0,		NULL}
4915 };
4916 
4917 void
pci_probe_nomatch(device_t dev,device_t child)4918 pci_probe_nomatch(device_t dev, device_t child)
4919 {
4920 	int i, report;
4921 	const char *cp, *scp;
4922 	char *device;
4923 
4924 	/*
4925 	 * Look for a listing for this device in a loaded device database.
4926 	 */
4927 	report = 1;
4928 	if ((device = pci_describe_device(child)) != NULL) {
4929 		device_printf(dev, "<%s>", device);
4930 		free(device, M_DEVBUF);
4931 	} else {
4932 		/*
4933 		 * Scan the class/subclass descriptions for a general
4934 		 * description.
4935 		 */
4936 		cp = "unknown";
4937 		scp = NULL;
4938 		for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
4939 			if (pci_nomatch_tab[i].class == pci_get_class(child)) {
4940 				if (pci_nomatch_tab[i].subclass == -1) {
4941 					cp = pci_nomatch_tab[i].desc;
4942 					report = pci_nomatch_tab[i].report;
4943 				} else if (pci_nomatch_tab[i].subclass ==
4944 				    pci_get_subclass(child)) {
4945 					scp = pci_nomatch_tab[i].desc;
4946 					report = pci_nomatch_tab[i].report;
4947 				}
4948 			}
4949 		}
4950 		if (report || bootverbose) {
4951 			device_printf(dev, "<%s%s%s>",
4952 			    cp ? cp : "",
4953 			    ((cp != NULL) && (scp != NULL)) ? ", " : "",
4954 			    scp ? scp : "");
4955 		}
4956 	}
4957 	if (report || bootverbose) {
4958 		printf(" at device %d.%d (no driver attached)\n",
4959 		    pci_get_slot(child), pci_get_function(child));
4960 	}
4961 	pci_cfg_save(child, device_get_ivars(child), 1);
4962 }
4963 
4964 void
pci_child_detached(device_t dev,device_t child)4965 pci_child_detached(device_t dev, device_t child)
4966 {
4967 	struct pci_devinfo *dinfo;
4968 	struct resource_list *rl;
4969 
4970 	dinfo = device_get_ivars(child);
4971 	rl = &dinfo->resources;
4972 
4973 	/*
4974 	 * Have to deallocate IRQs before releasing any MSI messages and
4975 	 * have to release MSI messages before deallocating any memory
4976 	 * BARs.
4977 	 */
4978 	if (resource_list_release_active(rl, dev, child, SYS_RES_IRQ) != 0)
4979 		pci_printf(&dinfo->cfg, "Device leaked IRQ resources\n");
4980 	if (dinfo->cfg.msi.msi_alloc != 0 || dinfo->cfg.msix.msix_alloc != 0) {
4981 		pci_printf(&dinfo->cfg, "Device leaked MSI vectors\n");
4982 		(void)pci_release_msi(child);
4983 	}
4984 	if (resource_list_release_active(rl, dev, child, SYS_RES_MEMORY) != 0)
4985 		pci_printf(&dinfo->cfg, "Device leaked memory resources\n");
4986 	if (resource_list_release_active(rl, dev, child, SYS_RES_IOPORT) != 0)
4987 		pci_printf(&dinfo->cfg, "Device leaked I/O resources\n");
4988 #ifdef PCI_RES_BUS
4989 	if (resource_list_release_active(rl, dev, child, PCI_RES_BUS) != 0)
4990 		pci_printf(&dinfo->cfg, "Device leaked PCI bus numbers\n");
4991 #endif
4992 
4993 	pci_cfg_save(child, dinfo, 1);
4994 }
4995 
4996 /*
4997  * Parse the PCI device database, if loaded, and return a pointer to a
4998  * description of the device.
4999  *
5000  * The database is flat text formatted as follows:
5001  *
5002  * Any line not in a valid format is ignored.
5003  * Lines are terminated with newline '\n' characters.
5004  *
5005  * A VENDOR line consists of the 4 digit (hex) vendor code, a TAB, then
5006  * the vendor name.
5007  *
5008  * A DEVICE line is entered immediately below the corresponding VENDOR ID.
5009  * - devices cannot be listed without a corresponding VENDOR line.
5010  * A DEVICE line consists of a TAB, the 4 digit (hex) device code,
5011  * another TAB, then the device name.
5012  */
5013 
5014 /*
5015  * Assuming (ptr) points to the beginning of a line in the database,
5016  * return the vendor or device and description of the next entry.
5017  * The value of (vendor) or (device) inappropriate for the entry type
5018  * is set to -1.  Returns nonzero at the end of the database.
5019  *
5020  * Note that this is slightly unrobust in the face of corrupt data;
5021  * we attempt to safeguard against this by spamming the end of the
5022  * database with a newline when we initialise.
5023  */
5024 static int
pci_describe_parse_line(char ** ptr,int * vendor,int * device,char ** desc)5025 pci_describe_parse_line(char **ptr, int *vendor, int *device, char **desc)
5026 {
5027 	char	*cp = *ptr;
5028 	int	left;
5029 
5030 	*device = -1;
5031 	*vendor = -1;
5032 	**desc = '\0';
5033 	for (;;) {
5034 		left = pci_vendordata_size - (cp - pci_vendordata);
5035 		if (left <= 0) {
5036 			*ptr = cp;
5037 			return(1);
5038 		}
5039 
5040 		/* vendor entry? */
5041 		if (*cp != '\t' &&
5042 		    sscanf(cp, "%x\t%80[^\n]", vendor, *desc) == 2)
5043 			break;
5044 		/* device entry? */
5045 		if (*cp == '\t' &&
5046 		    sscanf(cp, "%x\t%80[^\n]", device, *desc) == 2)
5047 			break;
5048 
5049 		/* skip to next line */
5050 		while (*cp != '\n' && left > 0) {
5051 			cp++;
5052 			left--;
5053 		}
5054 		if (*cp == '\n') {
5055 			cp++;
5056 			left--;
5057 		}
5058 	}
5059 	/* skip to next line */
5060 	while (*cp != '\n' && left > 0) {
5061 		cp++;
5062 		left--;
5063 	}
5064 	if (*cp == '\n' && left > 0)
5065 		cp++;
5066 	*ptr = cp;
5067 	return(0);
5068 }
5069 
5070 static char *
pci_describe_device(device_t dev)5071 pci_describe_device(device_t dev)
5072 {
5073 	int	vendor, device;
5074 	char	*desc, *vp, *dp, *line;
5075 
5076 	desc = vp = dp = NULL;
5077 
5078 	/*
5079 	 * If we have no vendor data, we can't do anything.
5080 	 */
5081 	if (pci_vendordata == NULL)
5082 		goto out;
5083 
5084 	/*
5085 	 * Scan the vendor data looking for this device
5086 	 */
5087 	line = pci_vendordata;
5088 	if ((vp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
5089 		goto out;
5090 	for (;;) {
5091 		if (pci_describe_parse_line(&line, &vendor, &device, &vp))
5092 			goto out;
5093 		if (vendor == pci_get_vendor(dev))
5094 			break;
5095 	}
5096 	if ((dp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
5097 		goto out;
5098 	for (;;) {
5099 		if (pci_describe_parse_line(&line, &vendor, &device, &dp)) {
5100 			*dp = 0;
5101 			break;
5102 		}
5103 		if (vendor != -1) {
5104 			*dp = 0;
5105 			break;
5106 		}
5107 		if (device == pci_get_device(dev))
5108 			break;
5109 	}
5110 	if (dp[0] == '\0')
5111 		snprintf(dp, 80, "0x%x", pci_get_device(dev));
5112 	if ((desc = malloc(strlen(vp) + strlen(dp) + 3, M_DEVBUF, M_NOWAIT)) !=
5113 	    NULL)
5114 		sprintf(desc, "%s, %s", vp, dp);
5115 out:
5116 	if (vp != NULL)
5117 		free(vp, M_DEVBUF);
5118 	if (dp != NULL)
5119 		free(dp, M_DEVBUF);
5120 	return(desc);
5121 }
5122 
5123 int
pci_read_ivar(device_t dev,device_t child,int which,uintptr_t * result)5124 pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
5125 {
5126 	struct pci_devinfo *dinfo;
5127 	pcicfgregs *cfg;
5128 
5129 	dinfo = device_get_ivars(child);
5130 	cfg = &dinfo->cfg;
5131 
5132 	switch (which) {
5133 	case PCI_IVAR_ETHADDR:
5134 		/*
5135 		 * The generic accessor doesn't deal with failure, so
5136 		 * we set the return value, then return an error.
5137 		 */
5138 		*((uint8_t **) result) = NULL;
5139 		return (EINVAL);
5140 	case PCI_IVAR_SUBVENDOR:
5141 		*result = cfg->subvendor;
5142 		break;
5143 	case PCI_IVAR_SUBDEVICE:
5144 		*result = cfg->subdevice;
5145 		break;
5146 	case PCI_IVAR_VENDOR:
5147 		*result = cfg->vendor;
5148 		break;
5149 	case PCI_IVAR_DEVICE:
5150 		*result = cfg->device;
5151 		break;
5152 	case PCI_IVAR_DEVID:
5153 		*result = (cfg->device << 16) | cfg->vendor;
5154 		break;
5155 	case PCI_IVAR_CLASS:
5156 		*result = cfg->baseclass;
5157 		break;
5158 	case PCI_IVAR_SUBCLASS:
5159 		*result = cfg->subclass;
5160 		break;
5161 	case PCI_IVAR_PROGIF:
5162 		*result = cfg->progif;
5163 		break;
5164 	case PCI_IVAR_REVID:
5165 		*result = cfg->revid;
5166 		break;
5167 	case PCI_IVAR_INTPIN:
5168 		*result = cfg->intpin;
5169 		break;
5170 	case PCI_IVAR_IRQ:
5171 		*result = cfg->intline;
5172 		break;
5173 	case PCI_IVAR_DOMAIN:
5174 		*result = cfg->domain;
5175 		break;
5176 	case PCI_IVAR_BUS:
5177 		*result = cfg->bus;
5178 		break;
5179 	case PCI_IVAR_SLOT:
5180 		*result = cfg->slot;
5181 		break;
5182 	case PCI_IVAR_FUNCTION:
5183 		*result = cfg->func;
5184 		break;
5185 	case PCI_IVAR_CMDREG:
5186 		*result = cfg->cmdreg;
5187 		break;
5188 	case PCI_IVAR_CACHELNSZ:
5189 		*result = cfg->cachelnsz;
5190 		break;
5191 	case PCI_IVAR_MINGNT:
5192 		if (cfg->hdrtype != PCIM_HDRTYPE_NORMAL) {
5193 			*result = -1;
5194 			return (EINVAL);
5195 		}
5196 		*result = cfg->mingnt;
5197 		break;
5198 	case PCI_IVAR_MAXLAT:
5199 		if (cfg->hdrtype != PCIM_HDRTYPE_NORMAL) {
5200 			*result = -1;
5201 			return (EINVAL);
5202 		}
5203 		*result = cfg->maxlat;
5204 		break;
5205 	case PCI_IVAR_LATTIMER:
5206 		*result = cfg->lattimer;
5207 		break;
5208 	default:
5209 		return (ENOENT);
5210 	}
5211 	return (0);
5212 }
5213 
5214 int
pci_write_ivar(device_t dev,device_t child,int which,uintptr_t value)5215 pci_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
5216 {
5217 	struct pci_devinfo *dinfo;
5218 
5219 	dinfo = device_get_ivars(child);
5220 
5221 	switch (which) {
5222 	case PCI_IVAR_INTPIN:
5223 		dinfo->cfg.intpin = value;
5224 		return (0);
5225 	case PCI_IVAR_ETHADDR:
5226 	case PCI_IVAR_SUBVENDOR:
5227 	case PCI_IVAR_SUBDEVICE:
5228 	case PCI_IVAR_VENDOR:
5229 	case PCI_IVAR_DEVICE:
5230 	case PCI_IVAR_DEVID:
5231 	case PCI_IVAR_CLASS:
5232 	case PCI_IVAR_SUBCLASS:
5233 	case PCI_IVAR_PROGIF:
5234 	case PCI_IVAR_REVID:
5235 	case PCI_IVAR_IRQ:
5236 	case PCI_IVAR_DOMAIN:
5237 	case PCI_IVAR_BUS:
5238 	case PCI_IVAR_SLOT:
5239 	case PCI_IVAR_FUNCTION:
5240 		return (EINVAL);	/* disallow for now */
5241 
5242 	default:
5243 		return (ENOENT);
5244 	}
5245 }
5246 
5247 #include "opt_ddb.h"
5248 #ifdef DDB
5249 #include <ddb/ddb.h>
5250 #include <sys/cons.h>
5251 
5252 /*
5253  * List resources based on pci map registers, used for within ddb
5254  */
5255 
DB_SHOW_COMMAND(pciregs,db_pci_dump)5256 DB_SHOW_COMMAND(pciregs, db_pci_dump)
5257 {
5258 	struct pci_devinfo *dinfo;
5259 	struct devlist *devlist_head;
5260 	struct pci_conf *p;
5261 	const char *name;
5262 	int i, error, none_count;
5263 
5264 	none_count = 0;
5265 	/* get the head of the device queue */
5266 	devlist_head = &pci_devq;
5267 
5268 	/*
5269 	 * Go through the list of devices and print out devices
5270 	 */
5271 	for (error = 0, i = 0,
5272 	     dinfo = STAILQ_FIRST(devlist_head);
5273 	     (dinfo != NULL) && (error == 0) && (i < pci_numdevs) && !db_pager_quit;
5274 	     dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {
5275 
5276 		/* Populate pd_name and pd_unit */
5277 		name = NULL;
5278 		if (dinfo->cfg.dev)
5279 			name = device_get_name(dinfo->cfg.dev);
5280 
5281 		p = &dinfo->conf;
5282 		db_printf("%s%d@pci%d:%d:%d:%d:\tclass=0x%06x card=0x%08x "
5283 			"chip=0x%08x rev=0x%02x hdr=0x%02x\n",
5284 			(name && *name) ? name : "none",
5285 			(name && *name) ? (int)device_get_unit(dinfo->cfg.dev) :
5286 			none_count++,
5287 			p->pc_sel.pc_domain, p->pc_sel.pc_bus, p->pc_sel.pc_dev,
5288 			p->pc_sel.pc_func, (p->pc_class << 16) |
5289 			(p->pc_subclass << 8) | p->pc_progif,
5290 			(p->pc_subdevice << 16) | p->pc_subvendor,
5291 			(p->pc_device << 16) | p->pc_vendor,
5292 			p->pc_revid, p->pc_hdr);
5293 	}
5294 }
5295 #endif /* DDB */
5296 
5297 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)5298 pci_reserve_map(device_t dev, device_t child, int type, int *rid,
5299     rman_res_t start, rman_res_t end, rman_res_t count, u_int num,
5300     u_int flags)
5301 {
5302 	struct pci_devinfo *dinfo = device_get_ivars(child);
5303 	struct resource_list *rl = &dinfo->resources;
5304 	struct resource *res;
5305 	struct pci_map *pm;
5306 	uint16_t cmd;
5307 	pci_addr_t map, testval;
5308 	int mapsize;
5309 
5310 	res = NULL;
5311 
5312 	/* If rid is managed by EA, ignore it */
5313 	if (pci_ea_is_enabled(child, *rid))
5314 		goto out;
5315 
5316 	pm = pci_find_bar(child, *rid);
5317 	if (pm != NULL) {
5318 		/* This is a BAR that we failed to allocate earlier. */
5319 		mapsize = pm->pm_size;
5320 		map = pm->pm_value;
5321 	} else {
5322 		/*
5323 		 * Weed out the bogons, and figure out how large the
5324 		 * BAR/map is.  BARs that read back 0 here are bogus
5325 		 * and unimplemented.  Note: atapci in legacy mode are
5326 		 * special and handled elsewhere in the code.  If you
5327 		 * have a atapci device in legacy mode and it fails
5328 		 * here, that other code is broken.
5329 		 */
5330 		pci_read_bar(child, *rid, &map, &testval, NULL);
5331 
5332 		/*
5333 		 * Determine the size of the BAR and ignore BARs with a size
5334 		 * of 0.  Device ROM BARs use a different mask value.
5335 		 */
5336 		if (PCIR_IS_BIOS(&dinfo->cfg, *rid))
5337 			mapsize = pci_romsize(testval);
5338 		else
5339 			mapsize = pci_mapsize(testval);
5340 		if (mapsize == 0)
5341 			goto out;
5342 		pm = pci_add_bar(child, *rid, map, mapsize);
5343 	}
5344 
5345 	if (PCI_BAR_MEM(map) || PCIR_IS_BIOS(&dinfo->cfg, *rid)) {
5346 		if (type != SYS_RES_MEMORY) {
5347 			if (bootverbose)
5348 				device_printf(dev,
5349 				    "child %s requested type %d for rid %#x,"
5350 				    " but the BAR says it is an memio\n",
5351 				    device_get_nameunit(child), type, *rid);
5352 			goto out;
5353 		}
5354 	} else {
5355 		if (type != SYS_RES_IOPORT) {
5356 			if (bootverbose)
5357 				device_printf(dev,
5358 				    "child %s requested type %d for rid %#x,"
5359 				    " but the BAR says it is an ioport\n",
5360 				    device_get_nameunit(child), type, *rid);
5361 			goto out;
5362 		}
5363 	}
5364 
5365 	/*
5366 	 * For real BARs, we need to override the size that
5367 	 * the driver requests, because that's what the BAR
5368 	 * actually uses and we would otherwise have a
5369 	 * situation where we might allocate the excess to
5370 	 * another driver, which won't work.
5371 	 */
5372 	count = ((pci_addr_t)1 << mapsize) * num;
5373 	if (RF_ALIGNMENT(flags) < mapsize)
5374 		flags = (flags & ~RF_ALIGNMENT_MASK) | RF_ALIGNMENT_LOG2(mapsize);
5375 	if (PCI_BAR_MEM(map) && (map & PCIM_BAR_MEM_PREFETCH))
5376 		flags |= RF_PREFETCHABLE;
5377 
5378 	/*
5379 	 * Allocate enough resource, and then write back the
5380 	 * appropriate BAR for that resource.
5381 	 */
5382 	resource_list_add(rl, type, *rid, start, end, count);
5383 	res = resource_list_reserve(rl, dev, child, type, rid, start, end,
5384 	    count, flags & ~RF_ACTIVE);
5385 	if (res == NULL) {
5386 		resource_list_delete(rl, type, *rid);
5387 		device_printf(child,
5388 		    "%#jx bytes of rid %#x res %d failed (%#jx, %#jx).\n",
5389 		    count, *rid, type, start, end);
5390 		goto out;
5391 	}
5392 	if (bootverbose)
5393 		device_printf(child,
5394 		    "Lazy allocation of %#jx bytes rid %#x type %d at %#jx\n",
5395 		    count, *rid, type, rman_get_start(res));
5396 
5397 	/* Disable decoding via the CMD register before updating the BAR */
5398 	cmd = pci_read_config(child, PCIR_COMMAND, 2);
5399 	pci_write_config(child, PCIR_COMMAND,
5400 	    cmd & ~(PCI_BAR_MEM(map) ? PCIM_CMD_MEMEN : PCIM_CMD_PORTEN), 2);
5401 
5402 	map = rman_get_start(res);
5403 	pci_write_bar(child, pm, map);
5404 
5405 	/* Restore the original value of the CMD register */
5406 	pci_write_config(child, PCIR_COMMAND, cmd, 2);
5407 out:
5408 	return (res);
5409 }
5410 
5411 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)5412 pci_alloc_multi_resource(device_t dev, device_t child, int type, int *rid,
5413     rman_res_t start, rman_res_t end, rman_res_t count, u_long num,
5414     u_int flags)
5415 {
5416 	struct pci_devinfo *dinfo;
5417 	struct resource_list *rl;
5418 	struct resource_list_entry *rle;
5419 	struct resource *res;
5420 	pcicfgregs *cfg;
5421 
5422 	/*
5423 	 * Perform lazy resource allocation
5424 	 */
5425 	dinfo = device_get_ivars(child);
5426 	rl = &dinfo->resources;
5427 	cfg = &dinfo->cfg;
5428 	switch (type) {
5429 #if defined(NEW_PCIB) && defined(PCI_RES_BUS)
5430 	case PCI_RES_BUS:
5431 		return (pci_alloc_secbus(dev, child, rid, start, end, count,
5432 		    flags));
5433 #endif
5434 	case SYS_RES_IRQ:
5435 		/*
5436 		 * Can't alloc legacy interrupt once MSI messages have
5437 		 * been allocated.
5438 		 */
5439 		if (*rid == 0 && (cfg->msi.msi_alloc > 0 ||
5440 		    cfg->msix.msix_alloc > 0))
5441 			return (NULL);
5442 
5443 		/*
5444 		 * If the child device doesn't have an interrupt
5445 		 * routed and is deserving of an interrupt, try to
5446 		 * assign it one.
5447 		 */
5448 		if (*rid == 0 && !PCI_INTERRUPT_VALID(cfg->intline) &&
5449 		    (cfg->intpin != 0))
5450 			pci_assign_interrupt(dev, child, 0);
5451 		break;
5452 	case SYS_RES_IOPORT:
5453 	case SYS_RES_MEMORY:
5454 #ifdef NEW_PCIB
5455 		/*
5456 		 * PCI-PCI bridge I/O window resources are not BARs.
5457 		 * For those allocations just pass the request up the
5458 		 * tree.
5459 		 */
5460 		if (cfg->hdrtype == PCIM_HDRTYPE_BRIDGE) {
5461 			switch (*rid) {
5462 			case PCIR_IOBASEL_1:
5463 			case PCIR_MEMBASE_1:
5464 			case PCIR_PMBASEL_1:
5465 				/*
5466 				 * XXX: Should we bother creating a resource
5467 				 * list entry?
5468 				 */
5469 				return (bus_generic_alloc_resource(dev, child,
5470 				    type, rid, start, end, count, flags));
5471 			}
5472 		}
5473 #endif
5474 		/* Reserve resources for this BAR if needed. */
5475 		rle = resource_list_find(rl, type, *rid);
5476 		if (rle == NULL) {
5477 			res = pci_reserve_map(dev, child, type, rid, start, end,
5478 			    count, num, flags);
5479 			if (res == NULL)
5480 				return (NULL);
5481 		}
5482 	}
5483 	return (resource_list_alloc(rl, dev, child, type, rid,
5484 	    start, end, count, flags));
5485 }
5486 
5487 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)5488 pci_alloc_resource(device_t dev, device_t child, int type, int *rid,
5489     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
5490 {
5491 #ifdef PCI_IOV
5492 	struct pci_devinfo *dinfo;
5493 #endif
5494 
5495 	if (device_get_parent(child) != dev)
5496 		return (BUS_ALLOC_RESOURCE(device_get_parent(dev), child,
5497 		    type, rid, start, end, count, flags));
5498 
5499 #ifdef PCI_IOV
5500 	dinfo = device_get_ivars(child);
5501 	if (dinfo->cfg.flags & PCICFG_VF) {
5502 		switch (type) {
5503 		/* VFs can't have I/O BARs. */
5504 		case SYS_RES_IOPORT:
5505 			return (NULL);
5506 		case SYS_RES_MEMORY:
5507 			return (pci_vf_alloc_mem_resource(dev, child, rid,
5508 			    start, end, count, flags));
5509 		}
5510 
5511 		/* Fall through for other types of resource allocations. */
5512 	}
5513 #endif
5514 
5515 	return (pci_alloc_multi_resource(dev, child, type, rid, start, end,
5516 	    count, 1, flags));
5517 }
5518 
5519 int
pci_release_resource(device_t dev,device_t child,int type,int rid,struct resource * r)5520 pci_release_resource(device_t dev, device_t child, int type, int rid,
5521     struct resource *r)
5522 {
5523 	struct pci_devinfo *dinfo;
5524 	struct resource_list *rl;
5525 	pcicfgregs *cfg;
5526 
5527 	if (device_get_parent(child) != dev)
5528 		return (BUS_RELEASE_RESOURCE(device_get_parent(dev), child,
5529 		    type, rid, r));
5530 
5531 	dinfo = device_get_ivars(child);
5532 	cfg = &dinfo->cfg;
5533 
5534 #ifdef PCI_IOV
5535 	if (dinfo->cfg.flags & PCICFG_VF) {
5536 		switch (type) {
5537 		/* VFs can't have I/O BARs. */
5538 		case SYS_RES_IOPORT:
5539 			return (EDOOFUS);
5540 		case SYS_RES_MEMORY:
5541 			return (pci_vf_release_mem_resource(dev, child, rid,
5542 			    r));
5543 		}
5544 
5545 		/* Fall through for other types of resource allocations. */
5546 	}
5547 #endif
5548 
5549 #ifdef NEW_PCIB
5550 	/*
5551 	 * PCI-PCI bridge I/O window resources are not BARs.  For
5552 	 * those allocations just pass the request up the tree.
5553 	 */
5554 	if (cfg->hdrtype == PCIM_HDRTYPE_BRIDGE &&
5555 	    (type == SYS_RES_IOPORT || type == SYS_RES_MEMORY)) {
5556 		switch (rid) {
5557 		case PCIR_IOBASEL_1:
5558 		case PCIR_MEMBASE_1:
5559 		case PCIR_PMBASEL_1:
5560 			return (bus_generic_release_resource(dev, child, type,
5561 			    rid, r));
5562 		}
5563 	}
5564 #endif
5565 
5566 	rl = &dinfo->resources;
5567 	return (resource_list_release(rl, dev, child, type, rid, r));
5568 }
5569 
5570 int
pci_activate_resource(device_t dev,device_t child,int type,int rid,struct resource * r)5571 pci_activate_resource(device_t dev, device_t child, int type, int rid,
5572     struct resource *r)
5573 {
5574 	struct pci_devinfo *dinfo;
5575 	int error;
5576 
5577 	error = bus_generic_activate_resource(dev, child, type, rid, r);
5578 	if (error)
5579 		return (error);
5580 
5581 	/* Enable decoding in the command register when activating BARs. */
5582 	if (device_get_parent(child) == dev) {
5583 		/* Device ROMs need their decoding explicitly enabled. */
5584 		dinfo = device_get_ivars(child);
5585 		if (type == SYS_RES_MEMORY && PCIR_IS_BIOS(&dinfo->cfg, rid))
5586 			pci_write_bar(child, pci_find_bar(child, rid),
5587 			    rman_get_start(r) | PCIM_BIOS_ENABLE);
5588 		switch (type) {
5589 		case SYS_RES_IOPORT:
5590 		case SYS_RES_MEMORY:
5591 			error = PCI_ENABLE_IO(dev, child, type);
5592 			break;
5593 		}
5594 	}
5595 	return (error);
5596 }
5597 
5598 int
pci_deactivate_resource(device_t dev,device_t child,int type,int rid,struct resource * r)5599 pci_deactivate_resource(device_t dev, device_t child, int type,
5600     int rid, struct resource *r)
5601 {
5602 	struct pci_devinfo *dinfo;
5603 	int error;
5604 
5605 	error = bus_generic_deactivate_resource(dev, child, type, rid, r);
5606 	if (error)
5607 		return (error);
5608 
5609 	/* Disable decoding for device ROMs. */
5610 	if (device_get_parent(child) == dev) {
5611 		dinfo = device_get_ivars(child);
5612 		if (type == SYS_RES_MEMORY && PCIR_IS_BIOS(&dinfo->cfg, rid))
5613 			pci_write_bar(child, pci_find_bar(child, rid),
5614 			    rman_get_start(r));
5615 	}
5616 	return (0);
5617 }
5618 
5619 void
pci_child_deleted(device_t dev,device_t child)5620 pci_child_deleted(device_t dev, device_t child)
5621 {
5622 	struct resource_list_entry *rle;
5623 	struct resource_list *rl;
5624 	struct pci_devinfo *dinfo;
5625 
5626 	dinfo = device_get_ivars(child);
5627 	rl = &dinfo->resources;
5628 
5629 	EVENTHANDLER_INVOKE(pci_delete_device, child);
5630 
5631 	/* Turn off access to resources we're about to free */
5632 	if (bus_child_present(child) != 0) {
5633 		pci_write_config(child, PCIR_COMMAND, pci_read_config(child,
5634 		    PCIR_COMMAND, 2) & ~(PCIM_CMD_MEMEN | PCIM_CMD_PORTEN), 2);
5635 
5636 		pci_disable_busmaster(child);
5637 	}
5638 
5639 	/* Free all allocated resources */
5640 	STAILQ_FOREACH(rle, rl, link) {
5641 		if (rle->res) {
5642 			if (rman_get_flags(rle->res) & RF_ACTIVE ||
5643 			    resource_list_busy(rl, rle->type, rle->rid)) {
5644 				pci_printf(&dinfo->cfg,
5645 				    "Resource still owned, oops. "
5646 				    "(type=%d, rid=%d, addr=%lx)\n",
5647 				    rle->type, rle->rid,
5648 				    rman_get_start(rle->res));
5649 				bus_release_resource(child, rle->type, rle->rid,
5650 				    rle->res);
5651 			}
5652 			resource_list_unreserve(rl, dev, child, rle->type,
5653 			    rle->rid);
5654 		}
5655 	}
5656 	resource_list_free(rl);
5657 
5658 	pci_freecfg(dinfo);
5659 }
5660 
5661 void
pci_delete_resource(device_t dev,device_t child,int type,int rid)5662 pci_delete_resource(device_t dev, device_t child, int type, int rid)
5663 {
5664 	struct pci_devinfo *dinfo;
5665 	struct resource_list *rl;
5666 	struct resource_list_entry *rle;
5667 
5668 	if (device_get_parent(child) != dev)
5669 		return;
5670 
5671 	dinfo = device_get_ivars(child);
5672 	rl = &dinfo->resources;
5673 	rle = resource_list_find(rl, type, rid);
5674 	if (rle == NULL)
5675 		return;
5676 
5677 	if (rle->res) {
5678 		if (rman_get_flags(rle->res) & RF_ACTIVE ||
5679 		    resource_list_busy(rl, type, rid)) {
5680 			device_printf(dev, "delete_resource: "
5681 			    "Resource still owned by child, oops. "
5682 			    "(type=%d, rid=%d, addr=%jx)\n",
5683 			    type, rid, rman_get_start(rle->res));
5684 			return;
5685 		}
5686 		resource_list_unreserve(rl, dev, child, type, rid);
5687 	}
5688 	resource_list_delete(rl, type, rid);
5689 }
5690 
5691 struct resource_list *
pci_get_resource_list(device_t dev,device_t child)5692 pci_get_resource_list (device_t dev, device_t child)
5693 {
5694 	struct pci_devinfo *dinfo = device_get_ivars(child);
5695 
5696 	return (&dinfo->resources);
5697 }
5698 
5699 bus_dma_tag_t
pci_get_dma_tag(device_t bus,device_t dev)5700 pci_get_dma_tag(device_t bus, device_t dev)
5701 {
5702 	struct pci_softc *sc = device_get_softc(bus);
5703 
5704 	return (sc->sc_dma_tag);
5705 }
5706 
5707 uint32_t
pci_read_config_method(device_t dev,device_t child,int reg,int width)5708 pci_read_config_method(device_t dev, device_t child, int reg, int width)
5709 {
5710 	struct pci_devinfo *dinfo = device_get_ivars(child);
5711 	pcicfgregs *cfg = &dinfo->cfg;
5712 
5713 #ifdef PCI_IOV
5714 	/*
5715 	 * SR-IOV VFs don't implement the VID or DID registers, so we have to
5716 	 * emulate them here.
5717 	 */
5718 	if (cfg->flags & PCICFG_VF) {
5719 		if (reg == PCIR_VENDOR) {
5720 			switch (width) {
5721 			case 4:
5722 				return (cfg->device << 16 | cfg->vendor);
5723 			case 2:
5724 				return (cfg->vendor);
5725 			case 1:
5726 				return (cfg->vendor & 0xff);
5727 			default:
5728 				return (0xffffffff);
5729 			}
5730 		} else if (reg == PCIR_DEVICE) {
5731 			switch (width) {
5732 			/* Note that an unaligned 4-byte read is an error. */
5733 			case 2:
5734 				return (cfg->device);
5735 			case 1:
5736 				return (cfg->device & 0xff);
5737 			default:
5738 				return (0xffffffff);
5739 			}
5740 		}
5741 	}
5742 #endif
5743 
5744 	return (PCIB_READ_CONFIG(device_get_parent(dev),
5745 	    cfg->bus, cfg->slot, cfg->func, reg, width));
5746 }
5747 
5748 void
pci_write_config_method(device_t dev,device_t child,int reg,uint32_t val,int width)5749 pci_write_config_method(device_t dev, device_t child, int reg,
5750     uint32_t val, int width)
5751 {
5752 	struct pci_devinfo *dinfo = device_get_ivars(child);
5753 	pcicfgregs *cfg = &dinfo->cfg;
5754 
5755 	PCIB_WRITE_CONFIG(device_get_parent(dev),
5756 	    cfg->bus, cfg->slot, cfg->func, reg, val, width);
5757 }
5758 
5759 int
pci_child_location_str_method(device_t dev,device_t child,char * buf,size_t buflen)5760 pci_child_location_str_method(device_t dev, device_t child, char *buf,
5761     size_t buflen)
5762 {
5763 
5764 	snprintf(buf, buflen, "slot=%d function=%d dbsf=pci%d:%d:%d:%d",
5765 	    pci_get_slot(child), pci_get_function(child), pci_get_domain(child),
5766 	    pci_get_bus(child), pci_get_slot(child), pci_get_function(child));
5767 	return (0);
5768 }
5769 
5770 int
pci_child_pnpinfo_str_method(device_t dev,device_t child,char * buf,size_t buflen)5771 pci_child_pnpinfo_str_method(device_t dev, device_t child, char *buf,
5772     size_t buflen)
5773 {
5774 	struct pci_devinfo *dinfo;
5775 	pcicfgregs *cfg;
5776 
5777 	dinfo = device_get_ivars(child);
5778 	cfg = &dinfo->cfg;
5779 	snprintf(buf, buflen, "vendor=0x%04x device=0x%04x subvendor=0x%04x "
5780 	    "subdevice=0x%04x class=0x%02x%02x%02x", cfg->vendor, cfg->device,
5781 	    cfg->subvendor, cfg->subdevice, cfg->baseclass, cfg->subclass,
5782 	    cfg->progif);
5783 	return (0);
5784 }
5785 
5786 int
pci_assign_interrupt_method(device_t dev,device_t child)5787 pci_assign_interrupt_method(device_t dev, device_t child)
5788 {
5789 	struct pci_devinfo *dinfo = device_get_ivars(child);
5790 	pcicfgregs *cfg = &dinfo->cfg;
5791 
5792 	return (PCIB_ROUTE_INTERRUPT(device_get_parent(dev), child,
5793 	    cfg->intpin));
5794 }
5795 
5796 static void
pci_lookup(void * arg,const char * name,device_t * dev)5797 pci_lookup(void *arg, const char *name, device_t *dev)
5798 {
5799 	long val;
5800 	char *end;
5801 	int domain, bus, slot, func;
5802 
5803 	if (*dev != NULL)
5804 		return;
5805 
5806 	/*
5807 	 * Accept pciconf-style selectors of either pciD:B:S:F or
5808 	 * pciB:S:F.  In the latter case, the domain is assumed to
5809 	 * be zero.
5810 	 */
5811 	if (strncmp(name, "pci", 3) != 0)
5812 		return;
5813 	val = strtol(name + 3, &end, 10);
5814 	if (val < 0 || val > INT_MAX || *end != ':')
5815 		return;
5816 	domain = val;
5817 	val = strtol(end + 1, &end, 10);
5818 	if (val < 0 || val > INT_MAX || *end != ':')
5819 		return;
5820 	bus = val;
5821 	val = strtol(end + 1, &end, 10);
5822 	if (val < 0 || val > INT_MAX)
5823 		return;
5824 	slot = val;
5825 	if (*end == ':') {
5826 		val = strtol(end + 1, &end, 10);
5827 		if (val < 0 || val > INT_MAX || *end != '\0')
5828 			return;
5829 		func = val;
5830 	} else if (*end == '\0') {
5831 		func = slot;
5832 		slot = bus;
5833 		bus = domain;
5834 		domain = 0;
5835 	} else
5836 		return;
5837 
5838 	if (domain > PCI_DOMAINMAX || bus > PCI_BUSMAX || slot > PCI_SLOTMAX ||
5839 	    func > PCIE_ARI_FUNCMAX || (slot != 0 && func > PCI_FUNCMAX))
5840 		return;
5841 
5842 	*dev = pci_find_dbsf(domain, bus, slot, func);
5843 }
5844 
5845 static int
pci_modevent(module_t mod,int what,void * arg)5846 pci_modevent(module_t mod, int what, void *arg)
5847 {
5848 	static struct cdev *pci_cdev;
5849 	static eventhandler_tag tag;
5850 
5851 	switch (what) {
5852 	case MOD_LOAD:
5853 		STAILQ_INIT(&pci_devq);
5854 		pci_generation = 0;
5855 		pci_cdev = make_dev(&pcicdev, 0, UID_ROOT, GID_WHEEL, 0644,
5856 		    "pci");
5857 		pci_load_vendor_data();
5858 		tag = EVENTHANDLER_REGISTER(dev_lookup, pci_lookup, NULL,
5859 		    1000);
5860 		break;
5861 
5862 	case MOD_UNLOAD:
5863 		if (tag != NULL)
5864 			EVENTHANDLER_DEREGISTER(dev_lookup, tag);
5865 		destroy_dev(pci_cdev);
5866 		break;
5867 	}
5868 
5869 	return (0);
5870 }
5871 
5872 static void
pci_cfg_restore_pcie(device_t dev,struct pci_devinfo * dinfo)5873 pci_cfg_restore_pcie(device_t dev, struct pci_devinfo *dinfo)
5874 {
5875 #define	WREG(n, v)	pci_write_config(dev, pos + (n), (v), 2)
5876 	struct pcicfg_pcie *cfg;
5877 	int version, pos;
5878 
5879 	cfg = &dinfo->cfg.pcie;
5880 	pos = cfg->pcie_location;
5881 
5882 	version = cfg->pcie_flags & PCIEM_FLAGS_VERSION;
5883 
5884 	WREG(PCIER_DEVICE_CTL, cfg->pcie_device_ctl);
5885 
5886 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
5887 	    cfg->pcie_type == PCIEM_TYPE_ENDPOINT ||
5888 	    cfg->pcie_type == PCIEM_TYPE_LEGACY_ENDPOINT)
5889 		WREG(PCIER_LINK_CTL, cfg->pcie_link_ctl);
5890 
5891 	if (version > 1 || (cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
5892 	    (cfg->pcie_type == PCIEM_TYPE_DOWNSTREAM_PORT &&
5893 	     (cfg->pcie_flags & PCIEM_FLAGS_SLOT))))
5894 		WREG(PCIER_SLOT_CTL, cfg->pcie_slot_ctl);
5895 
5896 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
5897 	    cfg->pcie_type == PCIEM_TYPE_ROOT_EC)
5898 		WREG(PCIER_ROOT_CTL, cfg->pcie_root_ctl);
5899 
5900 	if (version > 1) {
5901 		WREG(PCIER_DEVICE_CTL2, cfg->pcie_device_ctl2);
5902 		WREG(PCIER_LINK_CTL2, cfg->pcie_link_ctl2);
5903 		WREG(PCIER_SLOT_CTL2, cfg->pcie_slot_ctl2);
5904 	}
5905 #undef WREG
5906 }
5907 
5908 static void
pci_cfg_restore_pcix(device_t dev,struct pci_devinfo * dinfo)5909 pci_cfg_restore_pcix(device_t dev, struct pci_devinfo *dinfo)
5910 {
5911 	pci_write_config(dev, dinfo->cfg.pcix.pcix_location + PCIXR_COMMAND,
5912 	    dinfo->cfg.pcix.pcix_command,  2);
5913 }
5914 
5915 void
pci_cfg_restore(device_t dev,struct pci_devinfo * dinfo)5916 pci_cfg_restore(device_t dev, struct pci_devinfo *dinfo)
5917 {
5918 
5919 	/*
5920 	 * Restore the device to full power mode.  We must do this
5921 	 * before we restore the registers because moving from D3 to
5922 	 * D0 will cause the chip's BARs and some other registers to
5923 	 * be reset to some unknown power on reset values.  Cut down
5924 	 * the noise on boot by doing nothing if we are already in
5925 	 * state D0.
5926 	 */
5927 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0)
5928 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
5929 	pci_write_config(dev, PCIR_COMMAND, dinfo->cfg.cmdreg, 2);
5930 	pci_write_config(dev, PCIR_INTLINE, dinfo->cfg.intline, 1);
5931 	pci_write_config(dev, PCIR_INTPIN, dinfo->cfg.intpin, 1);
5932 	pci_write_config(dev, PCIR_CACHELNSZ, dinfo->cfg.cachelnsz, 1);
5933 	pci_write_config(dev, PCIR_LATTIMER, dinfo->cfg.lattimer, 1);
5934 	pci_write_config(dev, PCIR_PROGIF, dinfo->cfg.progif, 1);
5935 	pci_write_config(dev, PCIR_REVID, dinfo->cfg.revid, 1);
5936 	switch (dinfo->cfg.hdrtype & PCIM_HDRTYPE) {
5937 	case PCIM_HDRTYPE_NORMAL:
5938 		pci_write_config(dev, PCIR_MINGNT, dinfo->cfg.mingnt, 1);
5939 		pci_write_config(dev, PCIR_MAXLAT, dinfo->cfg.maxlat, 1);
5940 		break;
5941 	case PCIM_HDRTYPE_BRIDGE:
5942 		pci_write_config(dev, PCIR_SECLAT_1,
5943 		    dinfo->cfg.bridge.br_seclat, 1);
5944 		pci_write_config(dev, PCIR_SUBBUS_1,
5945 		    dinfo->cfg.bridge.br_subbus, 1);
5946 		pci_write_config(dev, PCIR_SECBUS_1,
5947 		    dinfo->cfg.bridge.br_secbus, 1);
5948 		pci_write_config(dev, PCIR_PRIBUS_1,
5949 		    dinfo->cfg.bridge.br_pribus, 1);
5950 		pci_write_config(dev, PCIR_BRIDGECTL_1,
5951 		    dinfo->cfg.bridge.br_control, 2);
5952 		break;
5953 	case PCIM_HDRTYPE_CARDBUS:
5954 		pci_write_config(dev, PCIR_SECLAT_2,
5955 		    dinfo->cfg.bridge.br_seclat, 1);
5956 		pci_write_config(dev, PCIR_SUBBUS_2,
5957 		    dinfo->cfg.bridge.br_subbus, 1);
5958 		pci_write_config(dev, PCIR_SECBUS_2,
5959 		    dinfo->cfg.bridge.br_secbus, 1);
5960 		pci_write_config(dev, PCIR_PRIBUS_2,
5961 		    dinfo->cfg.bridge.br_pribus, 1);
5962 		pci_write_config(dev, PCIR_BRIDGECTL_2,
5963 		    dinfo->cfg.bridge.br_control, 2);
5964 		break;
5965 	}
5966 	pci_restore_bars(dev);
5967 
5968 	/*
5969 	 * Restore extended capabilities for PCI-Express and PCI-X
5970 	 */
5971 	if (dinfo->cfg.pcie.pcie_location != 0)
5972 		pci_cfg_restore_pcie(dev, dinfo);
5973 	if (dinfo->cfg.pcix.pcix_location != 0)
5974 		pci_cfg_restore_pcix(dev, dinfo);
5975 
5976 	/* Restore MSI and MSI-X configurations if they are present. */
5977 	if (dinfo->cfg.msi.msi_location != 0)
5978 		pci_resume_msi(dev);
5979 	if (dinfo->cfg.msix.msix_location != 0)
5980 		pci_resume_msix(dev);
5981 
5982 #ifdef PCI_IOV
5983 	if (dinfo->cfg.iov != NULL)
5984 		pci_iov_cfg_restore(dev, dinfo);
5985 #endif
5986 }
5987 
5988 static void
pci_cfg_save_pcie(device_t dev,struct pci_devinfo * dinfo)5989 pci_cfg_save_pcie(device_t dev, struct pci_devinfo *dinfo)
5990 {
5991 #define	RREG(n)	pci_read_config(dev, pos + (n), 2)
5992 	struct pcicfg_pcie *cfg;
5993 	int version, pos;
5994 
5995 	cfg = &dinfo->cfg.pcie;
5996 	pos = cfg->pcie_location;
5997 
5998 	cfg->pcie_flags = RREG(PCIER_FLAGS);
5999 
6000 	version = cfg->pcie_flags & PCIEM_FLAGS_VERSION;
6001 
6002 	cfg->pcie_device_ctl = RREG(PCIER_DEVICE_CTL);
6003 
6004 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
6005 	    cfg->pcie_type == PCIEM_TYPE_ENDPOINT ||
6006 	    cfg->pcie_type == PCIEM_TYPE_LEGACY_ENDPOINT)
6007 		cfg->pcie_link_ctl = RREG(PCIER_LINK_CTL);
6008 
6009 	if (version > 1 || (cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
6010 	    (cfg->pcie_type == PCIEM_TYPE_DOWNSTREAM_PORT &&
6011 	     (cfg->pcie_flags & PCIEM_FLAGS_SLOT))))
6012 		cfg->pcie_slot_ctl = RREG(PCIER_SLOT_CTL);
6013 
6014 	if (version > 1 || cfg->pcie_type == PCIEM_TYPE_ROOT_PORT ||
6015 	    cfg->pcie_type == PCIEM_TYPE_ROOT_EC)
6016 		cfg->pcie_root_ctl = RREG(PCIER_ROOT_CTL);
6017 
6018 	if (version > 1) {
6019 		cfg->pcie_device_ctl2 = RREG(PCIER_DEVICE_CTL2);
6020 		cfg->pcie_link_ctl2 = RREG(PCIER_LINK_CTL2);
6021 		cfg->pcie_slot_ctl2 = RREG(PCIER_SLOT_CTL2);
6022 	}
6023 #undef RREG
6024 }
6025 
6026 static void
pci_cfg_save_pcix(device_t dev,struct pci_devinfo * dinfo)6027 pci_cfg_save_pcix(device_t dev, struct pci_devinfo *dinfo)
6028 {
6029 	dinfo->cfg.pcix.pcix_command = pci_read_config(dev,
6030 	    dinfo->cfg.pcix.pcix_location + PCIXR_COMMAND, 2);
6031 }
6032 
6033 void
pci_cfg_save(device_t dev,struct pci_devinfo * dinfo,int setstate)6034 pci_cfg_save(device_t dev, struct pci_devinfo *dinfo, int setstate)
6035 {
6036 	uint32_t cls;
6037 	int ps;
6038 
6039 	/*
6040 	 * Some drivers apparently write to these registers w/o updating our
6041 	 * cached copy.  No harm happens if we update the copy, so do so here
6042 	 * so we can restore them.  The COMMAND register is modified by the
6043 	 * bus w/o updating the cache.  This should represent the normally
6044 	 * writable portion of the 'defined' part of type 0/1/2 headers.
6045 	 */
6046 	dinfo->cfg.vendor = pci_read_config(dev, PCIR_VENDOR, 2);
6047 	dinfo->cfg.device = pci_read_config(dev, PCIR_DEVICE, 2);
6048 	dinfo->cfg.cmdreg = pci_read_config(dev, PCIR_COMMAND, 2);
6049 	dinfo->cfg.intline = pci_read_config(dev, PCIR_INTLINE, 1);
6050 	dinfo->cfg.intpin = pci_read_config(dev, PCIR_INTPIN, 1);
6051 	dinfo->cfg.cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
6052 	dinfo->cfg.lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
6053 	dinfo->cfg.baseclass = pci_read_config(dev, PCIR_CLASS, 1);
6054 	dinfo->cfg.subclass = pci_read_config(dev, PCIR_SUBCLASS, 1);
6055 	dinfo->cfg.progif = pci_read_config(dev, PCIR_PROGIF, 1);
6056 	dinfo->cfg.revid = pci_read_config(dev, PCIR_REVID, 1);
6057 	switch (dinfo->cfg.hdrtype & PCIM_HDRTYPE) {
6058 	case PCIM_HDRTYPE_NORMAL:
6059 		dinfo->cfg.subvendor = pci_read_config(dev, PCIR_SUBVEND_0, 2);
6060 		dinfo->cfg.subdevice = pci_read_config(dev, PCIR_SUBDEV_0, 2);
6061 		dinfo->cfg.mingnt = pci_read_config(dev, PCIR_MINGNT, 1);
6062 		dinfo->cfg.maxlat = pci_read_config(dev, PCIR_MAXLAT, 1);
6063 		break;
6064 	case PCIM_HDRTYPE_BRIDGE:
6065 		dinfo->cfg.bridge.br_seclat = pci_read_config(dev,
6066 		    PCIR_SECLAT_1, 1);
6067 		dinfo->cfg.bridge.br_subbus = pci_read_config(dev,
6068 		    PCIR_SUBBUS_1, 1);
6069 		dinfo->cfg.bridge.br_secbus = pci_read_config(dev,
6070 		    PCIR_SECBUS_1, 1);
6071 		dinfo->cfg.bridge.br_pribus = pci_read_config(dev,
6072 		    PCIR_PRIBUS_1, 1);
6073 		dinfo->cfg.bridge.br_control = pci_read_config(dev,
6074 		    PCIR_BRIDGECTL_1, 2);
6075 		break;
6076 	case PCIM_HDRTYPE_CARDBUS:
6077 		dinfo->cfg.bridge.br_seclat = pci_read_config(dev,
6078 		    PCIR_SECLAT_2, 1);
6079 		dinfo->cfg.bridge.br_subbus = pci_read_config(dev,
6080 		    PCIR_SUBBUS_2, 1);
6081 		dinfo->cfg.bridge.br_secbus = pci_read_config(dev,
6082 		    PCIR_SECBUS_2, 1);
6083 		dinfo->cfg.bridge.br_pribus = pci_read_config(dev,
6084 		    PCIR_PRIBUS_2, 1);
6085 		dinfo->cfg.bridge.br_control = pci_read_config(dev,
6086 		    PCIR_BRIDGECTL_2, 2);
6087 		dinfo->cfg.subvendor = pci_read_config(dev, PCIR_SUBVEND_2, 2);
6088 		dinfo->cfg.subdevice = pci_read_config(dev, PCIR_SUBDEV_2, 2);
6089 		break;
6090 	}
6091 
6092 	if (dinfo->cfg.pcie.pcie_location != 0)
6093 		pci_cfg_save_pcie(dev, dinfo);
6094 
6095 	if (dinfo->cfg.pcix.pcix_location != 0)
6096 		pci_cfg_save_pcix(dev, dinfo);
6097 
6098 #ifdef PCI_IOV
6099 	if (dinfo->cfg.iov != NULL)
6100 		pci_iov_cfg_save(dev, dinfo);
6101 #endif
6102 
6103 	/*
6104 	 * don't set the state for display devices, base peripherals and
6105 	 * memory devices since bad things happen when they are powered down.
6106 	 * We should (a) have drivers that can easily detach and (b) use
6107 	 * generic drivers for these devices so that some device actually
6108 	 * attaches.  We need to make sure that when we implement (a) we don't
6109 	 * power the device down on a reattach.
6110 	 */
6111 	cls = pci_get_class(dev);
6112 	if (!setstate)
6113 		return;
6114 	switch (pci_do_power_nodriver)
6115 	{
6116 		case 0:		/* NO powerdown at all */
6117 			return;
6118 		case 1:		/* Conservative about what to power down */
6119 			if (cls == PCIC_STORAGE)
6120 				return;
6121 			/*FALLTHROUGH*/
6122 		case 2:		/* Aggressive about what to power down */
6123 			if (cls == PCIC_DISPLAY || cls == PCIC_MEMORY ||
6124 			    cls == PCIC_BASEPERIPH)
6125 				return;
6126 			/*FALLTHROUGH*/
6127 		case 3:		/* Power down everything */
6128 			break;
6129 	}
6130 	/*
6131 	 * PCI spec says we can only go into D3 state from D0 state.
6132 	 * Transition from D[12] into D0 before going to D3 state.
6133 	 */
6134 	ps = pci_get_powerstate(dev);
6135 	if (ps != PCI_POWERSTATE_D0 && ps != PCI_POWERSTATE_D3)
6136 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
6137 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D3)
6138 		pci_set_powerstate(dev, PCI_POWERSTATE_D3);
6139 }
6140 
6141 /* Wrapper APIs suitable for device driver use. */
6142 void
pci_save_state(device_t dev)6143 pci_save_state(device_t dev)
6144 {
6145 	struct pci_devinfo *dinfo;
6146 
6147 	dinfo = device_get_ivars(dev);
6148 	pci_cfg_save(dev, dinfo, 0);
6149 }
6150 
6151 void
pci_restore_state(device_t dev)6152 pci_restore_state(device_t dev)
6153 {
6154 	struct pci_devinfo *dinfo;
6155 
6156 	dinfo = device_get_ivars(dev);
6157 	pci_cfg_restore(dev, dinfo);
6158 }
6159 
6160 static int
pci_get_id_method(device_t dev,device_t child,enum pci_id_type type,uintptr_t * id)6161 pci_get_id_method(device_t dev, device_t child, enum pci_id_type type,
6162     uintptr_t *id)
6163 {
6164 
6165 	return (PCIB_GET_ID(device_get_parent(dev), child, type, id));
6166 }
6167 
6168 /* Find the upstream port of a given PCI device in a root complex. */
6169 device_t
pci_find_pcie_root_port(device_t dev)6170 pci_find_pcie_root_port(device_t dev)
6171 {
6172 	struct pci_devinfo *dinfo;
6173 	devclass_t pci_class;
6174 	device_t pcib, bus;
6175 
6176 	pci_class = devclass_find("pci");
6177 	KASSERT(device_get_devclass(device_get_parent(dev)) == pci_class,
6178 	    ("%s: non-pci device %s", __func__, device_get_nameunit(dev)));
6179 
6180 	/*
6181 	 * Walk the bridge hierarchy until we find a PCI-e root
6182 	 * port or a non-PCI device.
6183 	 */
6184 	for (;;) {
6185 		bus = device_get_parent(dev);
6186 		KASSERT(bus != NULL, ("%s: null parent of %s", __func__,
6187 		    device_get_nameunit(dev)));
6188 
6189 		pcib = device_get_parent(bus);
6190 		KASSERT(pcib != NULL, ("%s: null bridge of %s", __func__,
6191 		    device_get_nameunit(bus)));
6192 
6193 		/*
6194 		 * pcib's parent must be a PCI bus for this to be a
6195 		 * PCI-PCI bridge.
6196 		 */
6197 		if (device_get_devclass(device_get_parent(pcib)) != pci_class)
6198 			return (NULL);
6199 
6200 		dinfo = device_get_ivars(pcib);
6201 		if (dinfo->cfg.pcie.pcie_location != 0 &&
6202 		    dinfo->cfg.pcie.pcie_type == PCIEM_TYPE_ROOT_PORT)
6203 			return (pcib);
6204 
6205 		dev = pcib;
6206 	}
6207 }
6208 
6209 /*
6210  * Wait for pending transactions to complete on a PCI-express function.
6211  *
6212  * The maximum delay is specified in milliseconds in max_delay.  Note
6213  * that this function may sleep.
6214  *
6215  * Returns true if the function is idle and false if the timeout is
6216  * exceeded.  If dev is not a PCI-express function, this returns true.
6217  */
6218 bool
pcie_wait_for_pending_transactions(device_t dev,u_int max_delay)6219 pcie_wait_for_pending_transactions(device_t dev, u_int max_delay)
6220 {
6221 	struct pci_devinfo *dinfo = device_get_ivars(dev);
6222 	uint16_t sta;
6223 	int cap;
6224 
6225 	cap = dinfo->cfg.pcie.pcie_location;
6226 	if (cap == 0)
6227 		return (true);
6228 
6229 	sta = pci_read_config(dev, cap + PCIER_DEVICE_STA, 2);
6230 	while (sta & PCIEM_STA_TRANSACTION_PND) {
6231 		if (max_delay == 0)
6232 			return (false);
6233 
6234 		/* Poll once every 100 milliseconds up to the timeout. */
6235 		if (max_delay > 100) {
6236 			pause_sbt("pcietp", 100 * SBT_1MS, 0, C_HARDCLOCK);
6237 			max_delay -= 100;
6238 		} else {
6239 			pause_sbt("pcietp", max_delay * SBT_1MS, 0,
6240 			    C_HARDCLOCK);
6241 			max_delay = 0;
6242 		}
6243 		sta = pci_read_config(dev, cap + PCIER_DEVICE_STA, 2);
6244 	}
6245 
6246 	return (true);
6247 }
6248 
6249 /*
6250  * Determine the maximum Completion Timeout in microseconds.
6251  *
6252  * For non-PCI-express functions this returns 0.
6253  */
6254 int
pcie_get_max_completion_timeout(device_t dev)6255 pcie_get_max_completion_timeout(device_t dev)
6256 {
6257 	struct pci_devinfo *dinfo = device_get_ivars(dev);
6258 	int cap;
6259 
6260 	cap = dinfo->cfg.pcie.pcie_location;
6261 	if (cap == 0)
6262 		return (0);
6263 
6264 	/*
6265 	 * Functions using the 1.x spec use the default timeout range of
6266 	 * 50 microseconds to 50 milliseconds.  Functions that do not
6267 	 * support programmable timeouts also use this range.
6268 	 */
6269 	if ((dinfo->cfg.pcie.pcie_flags & PCIEM_FLAGS_VERSION) < 2 ||
6270 	    (pci_read_config(dev, cap + PCIER_DEVICE_CAP2, 4) &
6271 	    PCIEM_CAP2_COMP_TIMO_RANGES) == 0)
6272 		return (50 * 1000);
6273 
6274 	switch (pci_read_config(dev, cap + PCIER_DEVICE_CTL2, 2) &
6275 	    PCIEM_CTL2_COMP_TIMO_VAL) {
6276 	case PCIEM_CTL2_COMP_TIMO_100US:
6277 		return (100);
6278 	case PCIEM_CTL2_COMP_TIMO_10MS:
6279 		return (10 * 1000);
6280 	case PCIEM_CTL2_COMP_TIMO_55MS:
6281 		return (55 * 1000);
6282 	case PCIEM_CTL2_COMP_TIMO_210MS:
6283 		return (210 * 1000);
6284 	case PCIEM_CTL2_COMP_TIMO_900MS:
6285 		return (900 * 1000);
6286 	case PCIEM_CTL2_COMP_TIMO_3500MS:
6287 		return (3500 * 1000);
6288 	case PCIEM_CTL2_COMP_TIMO_13S:
6289 		return (13 * 1000 * 1000);
6290 	case PCIEM_CTL2_COMP_TIMO_64S:
6291 		return (64 * 1000 * 1000);
6292 	default:
6293 		return (50 * 1000);
6294 	}
6295 }
6296 
6297 /*
6298  * Perform a Function Level Reset (FLR) on a device.
6299  *
6300  * This function first waits for any pending transactions to complete
6301  * within the timeout specified by max_delay.  If transactions are
6302  * still pending, the function will return false without attempting a
6303  * reset.
6304  *
6305  * If dev is not a PCI-express function or does not support FLR, this
6306  * function returns false.
6307  *
6308  * Note that no registers are saved or restored.  The caller is
6309  * responsible for saving and restoring any registers including
6310  * PCI-standard registers via pci_save_state() and
6311  * pci_restore_state().
6312  */
6313 bool
pcie_flr(device_t dev,u_int max_delay,bool force)6314 pcie_flr(device_t dev, u_int max_delay, bool force)
6315 {
6316 	struct pci_devinfo *dinfo = device_get_ivars(dev);
6317 	uint16_t cmd, ctl;
6318 	int compl_delay;
6319 	int cap;
6320 
6321 	cap = dinfo->cfg.pcie.pcie_location;
6322 	if (cap == 0)
6323 		return (false);
6324 
6325 	if (!(pci_read_config(dev, cap + PCIER_DEVICE_CAP, 4) & PCIEM_CAP_FLR))
6326 		return (false);
6327 
6328 	/*
6329 	 * Disable busmastering to prevent generation of new
6330 	 * transactions while waiting for the device to go idle.  If
6331 	 * the idle timeout fails, the command register is restored
6332 	 * which will re-enable busmastering.
6333 	 */
6334 	cmd = pci_read_config(dev, PCIR_COMMAND, 2);
6335 	pci_write_config(dev, PCIR_COMMAND, cmd & ~(PCIM_CMD_BUSMASTEREN), 2);
6336 	if (!pcie_wait_for_pending_transactions(dev, max_delay)) {
6337 		if (!force) {
6338 			pci_write_config(dev, PCIR_COMMAND, cmd, 2);
6339 			return (false);
6340 		}
6341 		pci_printf(&dinfo->cfg,
6342 		    "Resetting with transactions pending after %d ms\n",
6343 		    max_delay);
6344 
6345 		/*
6346 		 * Extend the post-FLR delay to cover the maximum
6347 		 * Completion Timeout delay of anything in flight
6348 		 * during the FLR delay.  Enforce a minimum delay of
6349 		 * at least 10ms.
6350 		 */
6351 		compl_delay = pcie_get_max_completion_timeout(dev) / 1000;
6352 		if (compl_delay < 10)
6353 			compl_delay = 10;
6354 	} else
6355 		compl_delay = 0;
6356 
6357 	/* Initiate the reset. */
6358 	ctl = pci_read_config(dev, cap + PCIER_DEVICE_CTL, 2);
6359 	pci_write_config(dev, cap + PCIER_DEVICE_CTL, ctl |
6360 	    PCIEM_CTL_INITIATE_FLR, 2);
6361 
6362 	/* Wait for 100ms. */
6363 	pause_sbt("pcieflr", (100 + compl_delay) * SBT_1MS, 0, C_HARDCLOCK);
6364 
6365 	if (pci_read_config(dev, cap + PCIER_DEVICE_STA, 2) &
6366 	    PCIEM_STA_TRANSACTION_PND)
6367 		pci_printf(&dinfo->cfg, "Transactions pending after FLR!\n");
6368 	return (true);
6369 }
6370 
6371 /*
6372  * Attempt a power-management reset by cycling the device in/out of D3
6373  * state.  PCI spec says we can only go into D3 state from D0 state.
6374  * Transition from D[12] into D0 before going to D3 state.
6375  */
6376 int
pci_power_reset(device_t dev)6377 pci_power_reset(device_t dev)
6378 {
6379 	int ps;
6380 
6381 	ps = pci_get_powerstate(dev);
6382 	if (ps != PCI_POWERSTATE_D0 && ps != PCI_POWERSTATE_D3)
6383 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
6384 	pci_set_powerstate(dev, PCI_POWERSTATE_D3);
6385 	pci_set_powerstate(dev, ps);
6386 	return (0);
6387 }
6388 
6389 /*
6390  * Try link drop and retrain of the downstream port of upstream
6391  * switch, for PCIe.  According to the PCIe 3.0 spec 6.6.1, this must
6392  * cause Conventional Hot reset of the device in the slot.
6393  * Alternative, for PCIe, could be the secondary bus reset initiatied
6394  * on the upstream switch PCIR_BRIDGECTL_1, bit 6.
6395  */
6396 int
pcie_link_reset(device_t port,int pcie_location)6397 pcie_link_reset(device_t port, int pcie_location)
6398 {
6399 	uint16_t v;
6400 
6401 	v = pci_read_config(port, pcie_location + PCIER_LINK_CTL, 2);
6402 	v |= PCIEM_LINK_CTL_LINK_DIS;
6403 	pci_write_config(port, pcie_location + PCIER_LINK_CTL, v, 2);
6404 	pause_sbt("pcier1", mstosbt(20), 0, 0);
6405 	v &= ~PCIEM_LINK_CTL_LINK_DIS;
6406 	v |= PCIEM_LINK_CTL_RETRAIN_LINK;
6407 	pci_write_config(port, pcie_location + PCIER_LINK_CTL, v, 2);
6408 	pause_sbt("pcier2", mstosbt(100), 0, 0); /* 100 ms */
6409 	v = pci_read_config(port, pcie_location + PCIER_LINK_STA, 2);
6410 	return ((v & PCIEM_LINK_STA_TRAINING) != 0 ? ETIMEDOUT : 0);
6411 }
6412 
6413 static int
pci_reset_post(device_t dev,device_t child)6414 pci_reset_post(device_t dev, device_t child)
6415 {
6416 
6417 	if (dev == device_get_parent(child))
6418 		pci_restore_state(child);
6419 	return (0);
6420 }
6421 
6422 static int
pci_reset_prepare(device_t dev,device_t child)6423 pci_reset_prepare(device_t dev, device_t child)
6424 {
6425 
6426 	if (dev == device_get_parent(child))
6427 		pci_save_state(child);
6428 	return (0);
6429 }
6430 
6431 static int
pci_reset_child(device_t dev,device_t child,int flags)6432 pci_reset_child(device_t dev, device_t child, int flags)
6433 {
6434 	int error;
6435 
6436 	if (dev == NULL || device_get_parent(child) != dev)
6437 		return (0);
6438 	if ((flags & DEVF_RESET_DETACH) != 0) {
6439 		error = device_get_state(child) == DS_ATTACHED ?
6440 		    device_detach(child) : 0;
6441 	} else {
6442 		error = BUS_SUSPEND_CHILD(dev, child);
6443 	}
6444 	if (error == 0) {
6445 		if (!pcie_flr(child, 1000, false)) {
6446 			error = BUS_RESET_PREPARE(dev, child);
6447 			if (error == 0)
6448 				pci_power_reset(child);
6449 			BUS_RESET_POST(dev, child);
6450 		}
6451 		if ((flags & DEVF_RESET_DETACH) != 0)
6452 			device_probe_and_attach(child);
6453 		else
6454 			BUS_RESUME_CHILD(dev, child);
6455 	}
6456 	return (error);
6457 }
6458 
6459 const struct pci_device_table *
pci_match_device(device_t child,const struct pci_device_table * id,size_t nelt)6460 pci_match_device(device_t child, const struct pci_device_table *id, size_t nelt)
6461 {
6462 	bool match;
6463 	uint16_t vendor, device, subvendor, subdevice, class, subclass, revid;
6464 
6465 	vendor = pci_get_vendor(child);
6466 	device = pci_get_device(child);
6467 	subvendor = pci_get_subvendor(child);
6468 	subdevice = pci_get_subdevice(child);
6469 	class = pci_get_class(child);
6470 	subclass = pci_get_subclass(child);
6471 	revid = pci_get_revid(child);
6472 	while (nelt-- > 0) {
6473 		match = true;
6474 		if (id->match_flag_vendor)
6475 			match &= vendor == id->vendor;
6476 		if (id->match_flag_device)
6477 			match &= device == id->device;
6478 		if (id->match_flag_subvendor)
6479 			match &= subvendor == id->subvendor;
6480 		if (id->match_flag_subdevice)
6481 			match &= subdevice == id->subdevice;
6482 		if (id->match_flag_class)
6483 			match &= class == id->class_id;
6484 		if (id->match_flag_subclass)
6485 			match &= subclass == id->subclass;
6486 		if (id->match_flag_revid)
6487 			match &= revid == id->revid;
6488 		if (match)
6489 			return (id);
6490 		id++;
6491 	}
6492 	return (NULL);
6493 }
6494 
6495 static void
pci_print_faulted_dev_name(const struct pci_devinfo * dinfo)6496 pci_print_faulted_dev_name(const struct pci_devinfo *dinfo)
6497 {
6498 	const char *dev_name;
6499 	device_t dev;
6500 
6501 	dev = dinfo->cfg.dev;
6502 	printf("pci%d:%d:%d:%d", dinfo->cfg.domain, dinfo->cfg.bus,
6503 	    dinfo->cfg.slot, dinfo->cfg.func);
6504 	dev_name = device_get_name(dev);
6505 	if (dev_name != NULL)
6506 		printf(" (%s%d)", dev_name, device_get_unit(dev));
6507 }
6508 
6509 void
pci_print_faulted_dev(void)6510 pci_print_faulted_dev(void)
6511 {
6512 	struct pci_devinfo *dinfo;
6513 	device_t dev;
6514 	int aer, i;
6515 	uint32_t r1, r2;
6516 	uint16_t status;
6517 
6518 	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
6519 		dev = dinfo->cfg.dev;
6520 		status = pci_read_config(dev, PCIR_STATUS, 2);
6521 		status &= PCIM_STATUS_MDPERR | PCIM_STATUS_STABORT |
6522 		    PCIM_STATUS_RTABORT | PCIM_STATUS_RMABORT |
6523 		    PCIM_STATUS_SERR | PCIM_STATUS_PERR;
6524 		if (status != 0) {
6525 			pci_print_faulted_dev_name(dinfo);
6526 			printf(" error 0x%04x\n", status);
6527 		}
6528 		if (dinfo->cfg.pcie.pcie_location != 0) {
6529 			status = pci_read_config(dev,
6530 			    dinfo->cfg.pcie.pcie_location +
6531 			    PCIER_DEVICE_STA, 2);
6532 			if ((status & (PCIEM_STA_CORRECTABLE_ERROR |
6533 			    PCIEM_STA_NON_FATAL_ERROR | PCIEM_STA_FATAL_ERROR |
6534 			    PCIEM_STA_UNSUPPORTED_REQ)) != 0) {
6535 				pci_print_faulted_dev_name(dinfo);
6536 				printf(" PCIe DEVCTL 0x%04x DEVSTA 0x%04x\n",
6537 				    pci_read_config(dev,
6538 				    dinfo->cfg.pcie.pcie_location +
6539 				    PCIER_DEVICE_CTL, 2),
6540 				    status);
6541 			}
6542 		}
6543 		if (pci_find_extcap(dev, PCIZ_AER, &aer) == 0) {
6544 			r1 = pci_read_config(dev, aer + PCIR_AER_UC_STATUS, 4);
6545 			r2 = pci_read_config(dev, aer + PCIR_AER_COR_STATUS, 4);
6546 			if (r1 != 0 || r2 != 0) {
6547 				pci_print_faulted_dev_name(dinfo);
6548 				printf(" AER UC 0x%08x Mask 0x%08x Svr 0x%08x\n"
6549 				    "  COR 0x%08x Mask 0x%08x Ctl 0x%08x\n",
6550 				    r1, pci_read_config(dev, aer +
6551 				    PCIR_AER_UC_MASK, 4),
6552 				    pci_read_config(dev, aer +
6553 				    PCIR_AER_UC_SEVERITY, 4),
6554 				    r2, pci_read_config(dev, aer +
6555 				    PCIR_AER_COR_MASK, 4),
6556 				    pci_read_config(dev, aer +
6557 				    PCIR_AER_CAP_CONTROL, 4));
6558 				for (i = 0; i < 4; i++) {
6559 					r1 = pci_read_config(dev, aer +
6560 					    PCIR_AER_HEADER_LOG + i * 4, 4);
6561 					printf("    HL%d: 0x%08x\n", i, r1);
6562 				}
6563 			}
6564 		}
6565 	}
6566 }
6567 
6568 #ifdef DDB
DB_SHOW_COMMAND(pcierr,pci_print_faulted_dev_db)6569 DB_SHOW_COMMAND(pcierr, pci_print_faulted_dev_db)
6570 {
6571 
6572 	pci_print_faulted_dev();
6573 }
6574 
6575 static void
db_clear_pcie_errors(const struct pci_devinfo * dinfo)6576 db_clear_pcie_errors(const struct pci_devinfo *dinfo)
6577 {
6578 	device_t dev;
6579 	int aer;
6580 	uint32_t r;
6581 
6582 	dev = dinfo->cfg.dev;
6583 	r = pci_read_config(dev, dinfo->cfg.pcie.pcie_location +
6584 	    PCIER_DEVICE_STA, 2);
6585 	pci_write_config(dev, dinfo->cfg.pcie.pcie_location +
6586 	    PCIER_DEVICE_STA, r, 2);
6587 
6588 	if (pci_find_extcap(dev, PCIZ_AER, &aer) != 0)
6589 		return;
6590 	r = pci_read_config(dev, aer + PCIR_AER_UC_STATUS, 4);
6591 	if (r != 0)
6592 		pci_write_config(dev, aer + PCIR_AER_UC_STATUS, r, 4);
6593 	r = pci_read_config(dev, aer + PCIR_AER_COR_STATUS, 4);
6594 	if (r != 0)
6595 		pci_write_config(dev, aer + PCIR_AER_COR_STATUS, r, 4);
6596 }
6597 
DB_COMMAND(pci_clearerr,db_pci_clearerr)6598 DB_COMMAND(pci_clearerr, db_pci_clearerr)
6599 {
6600 	struct pci_devinfo *dinfo;
6601 	device_t dev;
6602 	uint16_t status, status1;
6603 
6604 	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
6605 		dev = dinfo->cfg.dev;
6606 		status1 = status = pci_read_config(dev, PCIR_STATUS, 2);
6607 		status1 &= PCIM_STATUS_MDPERR | PCIM_STATUS_STABORT |
6608 		    PCIM_STATUS_RTABORT | PCIM_STATUS_RMABORT |
6609 		    PCIM_STATUS_SERR | PCIM_STATUS_PERR;
6610 		if (status1 != 0) {
6611 			status &= ~status1;
6612 			pci_write_config(dev, PCIR_STATUS, status, 2);
6613 		}
6614 		if (dinfo->cfg.pcie.pcie_location != 0)
6615 			db_clear_pcie_errors(dinfo);
6616 	}
6617 }
6618 #endif
6619