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