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