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