]> CyberLeo.Net >> Repos - FreeBSD/releng/9.3.git/blob - sys/dev/pci/pci.c
[SA-14:25] Fix kernel stack disclosure in setlogin(2) / getlogin(2).
[FreeBSD/releng/9.3.git] / sys / dev / pci / pci.c
1 /*-
2  * Copyright (c) 1997, Stefan Esser <se@freebsd.org>
3  * Copyright (c) 2000, Michael Smith <msmith@freebsd.org>
4  * Copyright (c) 2000, BSDi
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include "opt_bus.h"
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/malloc.h>
37 #include <sys/module.h>
38 #include <sys/linker.h>
39 #include <sys/fcntl.h>
40 #include <sys/conf.h>
41 #include <sys/kernel.h>
42 #include <sys/queue.h>
43 #include <sys/sysctl.h>
44 #include <sys/endian.h>
45
46 #include <vm/vm.h>
47 #include <vm/pmap.h>
48 #include <vm/vm_extern.h>
49
50 #include <sys/bus.h>
51 #include <machine/bus.h>
52 #include <sys/rman.h>
53 #include <machine/resource.h>
54 #include <machine/stdarg.h>
55
56 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
57 #include <machine/intr_machdep.h>
58 #endif
59
60 #include <sys/pciio.h>
61 #include <dev/pci/pcireg.h>
62 #include <dev/pci/pcivar.h>
63 #include <dev/pci/pci_private.h>
64
65 #include <dev/usb/controller/xhcireg.h>
66 #include <dev/usb/controller/ehcireg.h>
67 #include <dev/usb/controller/ohcireg.h>
68 #include <dev/usb/controller/uhcireg.h>
69
70 #include "pcib_if.h"
71 #include "pci_if.h"
72
73 /*
74  * XXX: Due to a limitation of the bus_dma_tag_create() API, we cannot
75  * specify a 4GB boundary on 32-bit targets.  Usually this does not
76  * matter as it is ok to use a boundary of 0 on these systems.
77  * However, in the case of PAE, DMA addresses can cross a 4GB
78  * boundary, so as a workaround use a 2GB boundary.
79  */
80 #if (BUS_SPACE_MAXADDR > 0xFFFFFFFF)
81 #ifdef PAE
82 #define PCI_DMA_BOUNDARY        0x80000000
83 #else
84 #define PCI_DMA_BOUNDARY        0x100000000
85 #endif
86 #endif
87
88 #define PCIR_IS_BIOS(cfg, reg)                                          \
89         (((cfg)->hdrtype == PCIM_HDRTYPE_NORMAL && reg == PCIR_BIOS) || \
90          ((cfg)->hdrtype == PCIM_HDRTYPE_BRIDGE && reg == PCIR_BIOS_1))
91
92 static int              pci_has_quirk(uint32_t devid, int quirk);
93 static pci_addr_t       pci_mapbase(uint64_t mapreg);
94 static const char       *pci_maptype(uint64_t mapreg);
95 static int              pci_mapsize(uint64_t testval);
96 static int              pci_maprange(uint64_t mapreg);
97 static pci_addr_t       pci_rombase(uint64_t mapreg);
98 static int              pci_romsize(uint64_t testval);
99 static void             pci_fixancient(pcicfgregs *cfg);
100 static int              pci_printf(pcicfgregs *cfg, const char *fmt, ...);
101
102 static int              pci_porten(device_t dev);
103 static int              pci_memen(device_t dev);
104 static void             pci_assign_interrupt(device_t bus, device_t dev,
105                             int force_route);
106 static int              pci_add_map(device_t bus, device_t dev, int reg,
107                             struct resource_list *rl, int force, int prefetch);
108 static int              pci_probe(device_t dev);
109 static int              pci_attach(device_t dev);
110 static void             pci_load_vendor_data(void);
111 static int              pci_describe_parse_line(char **ptr, int *vendor,
112                             int *device, char **desc);
113 static char             *pci_describe_device(device_t dev);
114 static bus_dma_tag_t    pci_get_dma_tag(device_t bus, device_t dev);
115 static int              pci_modevent(module_t mod, int what, void *arg);
116 static void             pci_hdrtypedata(device_t pcib, int b, int s, int f,
117                             pcicfgregs *cfg);
118 static void             pci_read_cap(device_t pcib, pcicfgregs *cfg);
119 static int              pci_read_vpd_reg(device_t pcib, pcicfgregs *cfg,
120                             int reg, uint32_t *data);
121 #if 0
122 static int              pci_write_vpd_reg(device_t pcib, pcicfgregs *cfg,
123                             int reg, uint32_t data);
124 #endif
125 static void             pci_read_vpd(device_t pcib, pcicfgregs *cfg);
126 static void             pci_disable_msi(device_t dev);
127 static void             pci_enable_msi(device_t dev, uint64_t address,
128                             uint16_t data);
129 static void             pci_enable_msix(device_t dev, u_int index,
130                             uint64_t address, uint32_t data);
131 static void             pci_mask_msix(device_t dev, u_int index);
132 static void             pci_unmask_msix(device_t dev, u_int index);
133 static int              pci_msi_blacklisted(void);
134 static int              pci_msix_blacklisted(void);
135 static void             pci_resume_msi(device_t dev);
136 static void             pci_resume_msix(device_t dev);
137 static int              pci_remap_intr_method(device_t bus, device_t dev,
138                             u_int irq);
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,        bus_generic_detach),
145         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
146         DEVMETHOD(device_suspend,       pci_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
158         DEVMETHOD(bus_get_dma_tag,      pci_get_dma_tag),
159         DEVMETHOD(bus_get_resource_list,pci_get_resource_list),
160         DEVMETHOD(bus_set_resource,     bus_generic_rl_set_resource),
161         DEVMETHOD(bus_get_resource,     bus_generic_rl_get_resource),
162         DEVMETHOD(bus_delete_resource,  pci_delete_resource),
163         DEVMETHOD(bus_alloc_resource,   pci_alloc_resource),
164         DEVMETHOD(bus_adjust_resource,  bus_generic_adjust_resource),
165         DEVMETHOD(bus_release_resource, pci_release_resource),
166         DEVMETHOD(bus_activate_resource, pci_activate_resource),
167         DEVMETHOD(bus_deactivate_resource, pci_deactivate_resource),
168         DEVMETHOD(bus_child_pnpinfo_str, pci_child_pnpinfo_str_method),
169         DEVMETHOD(bus_child_location_str, pci_child_location_str_method),
170         DEVMETHOD(bus_remap_intr,       pci_remap_intr_method),
171
172         /* PCI interface */
173         DEVMETHOD(pci_read_config,      pci_read_config_method),
174         DEVMETHOD(pci_write_config,     pci_write_config_method),
175         DEVMETHOD(pci_enable_busmaster, pci_enable_busmaster_method),
176         DEVMETHOD(pci_disable_busmaster, pci_disable_busmaster_method),
177         DEVMETHOD(pci_enable_io,        pci_enable_io_method),
178         DEVMETHOD(pci_disable_io,       pci_disable_io_method),
179         DEVMETHOD(pci_get_vpd_ident,    pci_get_vpd_ident_method),
180         DEVMETHOD(pci_get_vpd_readonly, pci_get_vpd_readonly_method),
181         DEVMETHOD(pci_get_powerstate,   pci_get_powerstate_method),
182         DEVMETHOD(pci_set_powerstate,   pci_set_powerstate_method),
183         DEVMETHOD(pci_assign_interrupt, pci_assign_interrupt_method),
184         DEVMETHOD(pci_find_extcap,      pci_find_extcap_method),
185         DEVMETHOD(pci_alloc_msi,        pci_alloc_msi_method),
186         DEVMETHOD(pci_alloc_msix,       pci_alloc_msix_method),
187         DEVMETHOD(pci_remap_msix,       pci_remap_msix_method),
188         DEVMETHOD(pci_release_msi,      pci_release_msi_method),
189         DEVMETHOD(pci_msi_count,        pci_msi_count_method),
190         DEVMETHOD(pci_msix_count,       pci_msix_count_method),
191
192         DEVMETHOD_END
193 };
194
195 DEFINE_CLASS_0(pci, pci_driver, pci_methods, sizeof(struct pci_softc));
196
197 static devclass_t pci_devclass;
198 DRIVER_MODULE(pci, pcib, pci_driver, pci_devclass, pci_modevent, NULL);
199 MODULE_VERSION(pci, 1);
200
201 static char     *pci_vendordata;
202 static size_t   pci_vendordata_size;
203
204 struct pci_quirk {
205         uint32_t devid; /* Vendor/device of the card */
206         int     type;
207 #define PCI_QUIRK_MAP_REG       1 /* PCI map register in weird place */
208 #define PCI_QUIRK_DISABLE_MSI   2 /* Neither MSI nor MSI-X work */
209 #define PCI_QUIRK_ENABLE_MSI_VM 3 /* Older chipset in VM where MSI works */
210 #define PCI_QUIRK_UNMAP_REG     4 /* Ignore PCI map register */
211 #define PCI_QUIRK_DISABLE_MSIX  5 /* MSI-X doesn't work */
212         int     arg1;
213         int     arg2;
214 };
215
216 static const struct pci_quirk pci_quirks[] = {
217         /* The Intel 82371AB and 82443MX have a map register at offset 0x90. */
218         { 0x71138086, PCI_QUIRK_MAP_REG,        0x90,    0 },
219         { 0x719b8086, PCI_QUIRK_MAP_REG,        0x90,    0 },
220         /* As does the Serverworks OSB4 (the SMBus mapping register) */
221         { 0x02001166, PCI_QUIRK_MAP_REG,        0x90,    0 },
222
223         /*
224          * MSI doesn't work with the ServerWorks CNB20-HE Host Bridge
225          * or the CMIC-SL (AKA ServerWorks GC_LE).
226          */
227         { 0x00141166, PCI_QUIRK_DISABLE_MSI,    0,      0 },
228         { 0x00171166, PCI_QUIRK_DISABLE_MSI,    0,      0 },
229
230         /*
231          * MSI doesn't work on earlier Intel chipsets including
232          * E7500, E7501, E7505, 845, 865, 875/E7210, and 855.
233          */
234         { 0x25408086, PCI_QUIRK_DISABLE_MSI,    0,      0 },
235         { 0x254c8086, PCI_QUIRK_DISABLE_MSI,    0,      0 },
236         { 0x25508086, PCI_QUIRK_DISABLE_MSI,    0,      0 },
237         { 0x25608086, PCI_QUIRK_DISABLE_MSI,    0,      0 },
238         { 0x25708086, PCI_QUIRK_DISABLE_MSI,    0,      0 },
239         { 0x25788086, PCI_QUIRK_DISABLE_MSI,    0,      0 },
240         { 0x35808086, PCI_QUIRK_DISABLE_MSI,    0,      0 },
241
242         /*
243          * MSI doesn't work with devices behind the AMD 8131 HT-PCIX
244          * bridge.
245          */
246         { 0x74501022, PCI_QUIRK_DISABLE_MSI,    0,      0 },
247
248         /*
249          * MSI-X allocation doesn't work properly for devices passed through
250          * by VMware up to at least ESXi 5.1.
251          */
252         { 0x079015ad, PCI_QUIRK_DISABLE_MSIX,   0,      0 }, /* PCI/PCI-X */
253         { 0x07a015ad, PCI_QUIRK_DISABLE_MSIX,   0,      0 }, /* PCIe */
254
255         /*
256          * Some virtualization environments emulate an older chipset
257          * but support MSI just fine.  QEMU uses the Intel 82440.
258          */
259         { 0x12378086, PCI_QUIRK_ENABLE_MSI_VM,  0,      0 },
260
261         /*
262          * HPET MMIO base address may appear in Bar1 for AMD SB600 SMBus
263          * controller depending on SoftPciRst register (PM_IO 0x55 [7]).
264          * It prevents us from attaching hpet(4) when the bit is unset.
265          * Note this quirk only affects SB600 revision A13 and earlier.
266          * For SB600 A21 and later, firmware must set the bit to hide it.
267          * For SB700 and later, it is unused and hardcoded to zero.
268          */
269         { 0x43851002, PCI_QUIRK_UNMAP_REG,      0x14,   0 },
270
271         { 0 }
272 };
273
274 /* map register information */
275 #define PCI_MAPMEM      0x01    /* memory map */
276 #define PCI_MAPMEMP     0x02    /* prefetchable memory map */
277 #define PCI_MAPPORT     0x04    /* port map */
278
279 struct devlist pci_devq;
280 uint32_t pci_generation;
281 uint32_t pci_numdevs = 0;
282 static int pcie_chipset, pcix_chipset;
283
284 /* sysctl vars */
285 SYSCTL_NODE(_hw, OID_AUTO, pci, CTLFLAG_RD, 0, "PCI bus tuning parameters");
286
287 static int pci_enable_io_modes = 1;
288 TUNABLE_INT("hw.pci.enable_io_modes", &pci_enable_io_modes);
289 SYSCTL_INT(_hw_pci, OID_AUTO, enable_io_modes, CTLFLAG_RW,
290     &pci_enable_io_modes, 1,
291     "Enable I/O and memory bits in the config register.  Some BIOSes do not\n\
292 enable these bits correctly.  We'd like to do this all the time, but there\n\
293 are some peripherals that this causes problems with.");
294
295 static int pci_do_realloc_bars = 0;
296 TUNABLE_INT("hw.pci.realloc_bars", &pci_do_realloc_bars);
297 SYSCTL_INT(_hw_pci, OID_AUTO, realloc_bars, CTLFLAG_RW,
298     &pci_do_realloc_bars, 0,
299     "Attempt to allocate a new range for any BARs whose original firmware-assigned ranges fail to allocate during the initial device scan.");
300
301 static int pci_do_power_nodriver = 0;
302 TUNABLE_INT("hw.pci.do_power_nodriver", &pci_do_power_nodriver);
303 SYSCTL_INT(_hw_pci, OID_AUTO, do_power_nodriver, CTLFLAG_RW,
304     &pci_do_power_nodriver, 0,
305   "Place a function into D3 state when no driver attaches to it.  0 means\n\
306 disable.  1 means conservatively place devices into D3 state.  2 means\n\
307 agressively place devices into D3 state.  3 means put absolutely everything\n\
308 in D3 state.");
309
310 int pci_do_power_resume = 1;
311 TUNABLE_INT("hw.pci.do_power_resume", &pci_do_power_resume);
312 SYSCTL_INT(_hw_pci, OID_AUTO, do_power_resume, CTLFLAG_RW,
313     &pci_do_power_resume, 1,
314   "Transition from D3 -> D0 on resume.");
315
316 int pci_do_power_suspend = 1;
317 TUNABLE_INT("hw.pci.do_power_suspend", &pci_do_power_suspend);
318 SYSCTL_INT(_hw_pci, OID_AUTO, do_power_suspend, CTLFLAG_RW,
319     &pci_do_power_suspend, 1,
320   "Transition from D0 -> D3 on suspend.");
321
322 static int pci_do_msi = 1;
323 TUNABLE_INT("hw.pci.enable_msi", &pci_do_msi);
324 SYSCTL_INT(_hw_pci, OID_AUTO, enable_msi, CTLFLAG_RW, &pci_do_msi, 1,
325     "Enable support for MSI interrupts");
326
327 static int pci_do_msix = 1;
328 TUNABLE_INT("hw.pci.enable_msix", &pci_do_msix);
329 SYSCTL_INT(_hw_pci, OID_AUTO, enable_msix, CTLFLAG_RW, &pci_do_msix, 1,
330     "Enable support for MSI-X interrupts");
331
332 static int pci_honor_msi_blacklist = 1;
333 TUNABLE_INT("hw.pci.honor_msi_blacklist", &pci_honor_msi_blacklist);
334 SYSCTL_INT(_hw_pci, OID_AUTO, honor_msi_blacklist, CTLFLAG_RD,
335     &pci_honor_msi_blacklist, 1, "Honor chipset blacklist for MSI/MSI-X");
336
337 #if defined(__i386__) || defined(__amd64__)
338 static int pci_usb_takeover = 1;
339 #else
340 static int pci_usb_takeover = 0;
341 #endif
342 TUNABLE_INT("hw.pci.usb_early_takeover", &pci_usb_takeover);
343 SYSCTL_INT(_hw_pci, OID_AUTO, usb_early_takeover, CTLFLAG_RDTUN,
344     &pci_usb_takeover, 1, "Enable early takeover of USB controllers.\n\
345 Disable this if you depend on BIOS emulation of USB devices, that is\n\
346 you use USB devices (like keyboard or mouse) but do not load USB drivers");
347
348 static int pci_clear_bars;
349 TUNABLE_INT("hw.pci.clear_bars", &pci_clear_bars);
350 SYSCTL_INT(_hw_pci, OID_AUTO, clear_bars, CTLFLAG_RDTUN, &pci_clear_bars, 0,
351     "Ignore firmware-assigned resources for BARs.");
352
353 static int
354 pci_has_quirk(uint32_t devid, int quirk)
355 {
356         const struct pci_quirk *q;
357
358         for (q = &pci_quirks[0]; q->devid; q++) {
359                 if (q->devid == devid && q->type == quirk)
360                         return (1);
361         }
362         return (0);
363 }
364
365 /* Find a device_t by bus/slot/function in domain 0 */
366
367 device_t
368 pci_find_bsf(uint8_t bus, uint8_t slot, uint8_t func)
369 {
370
371         return (pci_find_dbsf(0, bus, slot, func));
372 }
373
374 /* Find a device_t by domain/bus/slot/function */
375
376 device_t
377 pci_find_dbsf(uint32_t domain, uint8_t bus, uint8_t slot, uint8_t func)
378 {
379         struct pci_devinfo *dinfo;
380
381         STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
382                 if ((dinfo->cfg.domain == domain) &&
383                     (dinfo->cfg.bus == bus) &&
384                     (dinfo->cfg.slot == slot) &&
385                     (dinfo->cfg.func == func)) {
386                         return (dinfo->cfg.dev);
387                 }
388         }
389
390         return (NULL);
391 }
392
393 /* Find a device_t by vendor/device ID */
394
395 device_t
396 pci_find_device(uint16_t vendor, uint16_t device)
397 {
398         struct pci_devinfo *dinfo;
399
400         STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
401                 if ((dinfo->cfg.vendor == vendor) &&
402                     (dinfo->cfg.device == device)) {
403                         return (dinfo->cfg.dev);
404                 }
405         }
406
407         return (NULL);
408 }
409
410 device_t
411 pci_find_class(uint8_t class, uint8_t subclass)
412 {
413         struct pci_devinfo *dinfo;
414
415         STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
416                 if (dinfo->cfg.baseclass == class &&
417                     dinfo->cfg.subclass == subclass) {
418                         return (dinfo->cfg.dev);
419                 }
420         }
421
422         return (NULL);
423 }
424
425 static int
426 pci_printf(pcicfgregs *cfg, const char *fmt, ...)
427 {
428         va_list ap;
429         int retval;
430
431         retval = printf("pci%d:%d:%d:%d: ", cfg->domain, cfg->bus, cfg->slot,
432             cfg->func);
433         va_start(ap, fmt);
434         retval += vprintf(fmt, ap);
435         va_end(ap);
436         return (retval);
437 }
438
439 /* return base address of memory or port map */
440
441 static pci_addr_t
442 pci_mapbase(uint64_t mapreg)
443 {
444
445         if (PCI_BAR_MEM(mapreg))
446                 return (mapreg & PCIM_BAR_MEM_BASE);
447         else
448                 return (mapreg & PCIM_BAR_IO_BASE);
449 }
450
451 /* return map type of memory or port map */
452
453 static const char *
454 pci_maptype(uint64_t mapreg)
455 {
456
457         if (PCI_BAR_IO(mapreg))
458                 return ("I/O Port");
459         if (mapreg & PCIM_BAR_MEM_PREFETCH)
460                 return ("Prefetchable Memory");
461         return ("Memory");
462 }
463
464 /* return log2 of map size decoded for memory or port map */
465
466 static int
467 pci_mapsize(uint64_t testval)
468 {
469         int ln2size;
470
471         testval = pci_mapbase(testval);
472         ln2size = 0;
473         if (testval != 0) {
474                 while ((testval & 1) == 0)
475                 {
476                         ln2size++;
477                         testval >>= 1;
478                 }
479         }
480         return (ln2size);
481 }
482
483 /* return base address of device ROM */
484
485 static pci_addr_t
486 pci_rombase(uint64_t mapreg)
487 {
488
489         return (mapreg & PCIM_BIOS_ADDR_MASK);
490 }
491
492 /* return log2 of map size decided for device ROM */
493
494 static int
495 pci_romsize(uint64_t testval)
496 {
497         int ln2size;
498
499         testval = pci_rombase(testval);
500         ln2size = 0;
501         if (testval != 0) {
502                 while ((testval & 1) == 0)
503                 {
504                         ln2size++;
505                         testval >>= 1;
506                 }
507         }
508         return (ln2size);
509 }
510         
511 /* return log2 of address range supported by map register */
512
513 static int
514 pci_maprange(uint64_t mapreg)
515 {
516         int ln2range = 0;
517
518         if (PCI_BAR_IO(mapreg))
519                 ln2range = 32;
520         else
521                 switch (mapreg & PCIM_BAR_MEM_TYPE) {
522                 case PCIM_BAR_MEM_32:
523                         ln2range = 32;
524                         break;
525                 case PCIM_BAR_MEM_1MB:
526                         ln2range = 20;
527                         break;
528                 case PCIM_BAR_MEM_64:
529                         ln2range = 64;
530                         break;
531                 }
532         return (ln2range);
533 }
534
535 /* adjust some values from PCI 1.0 devices to match 2.0 standards ... */
536
537 static void
538 pci_fixancient(pcicfgregs *cfg)
539 {
540         if ((cfg->hdrtype & PCIM_HDRTYPE) != PCIM_HDRTYPE_NORMAL)
541                 return;
542
543         /* PCI to PCI bridges use header type 1 */
544         if (cfg->baseclass == PCIC_BRIDGE && cfg->subclass == PCIS_BRIDGE_PCI)
545                 cfg->hdrtype = PCIM_HDRTYPE_BRIDGE;
546 }
547
548 /* extract header type specific config data */
549
550 static void
551 pci_hdrtypedata(device_t pcib, int b, int s, int f, pcicfgregs *cfg)
552 {
553 #define REG(n, w)       PCIB_READ_CONFIG(pcib, b, s, f, n, w)
554         switch (cfg->hdrtype & PCIM_HDRTYPE) {
555         case PCIM_HDRTYPE_NORMAL:
556                 cfg->subvendor      = REG(PCIR_SUBVEND_0, 2);
557                 cfg->subdevice      = REG(PCIR_SUBDEV_0, 2);
558                 cfg->nummaps        = PCI_MAXMAPS_0;
559                 break;
560         case PCIM_HDRTYPE_BRIDGE:
561                 cfg->nummaps        = PCI_MAXMAPS_1;
562                 break;
563         case PCIM_HDRTYPE_CARDBUS:
564                 cfg->subvendor      = REG(PCIR_SUBVEND_2, 2);
565                 cfg->subdevice      = REG(PCIR_SUBDEV_2, 2);
566                 cfg->nummaps        = PCI_MAXMAPS_2;
567                 break;
568         }
569 #undef REG
570 }
571
572 /* read configuration header into pcicfgregs structure */
573 struct pci_devinfo *
574 pci_read_device(device_t pcib, int d, int b, int s, int f, size_t size)
575 {
576 #define REG(n, w)       PCIB_READ_CONFIG(pcib, b, s, f, n, w)
577         pcicfgregs *cfg = NULL;
578         struct pci_devinfo *devlist_entry;
579         struct devlist *devlist_head;
580
581         devlist_head = &pci_devq;
582
583         devlist_entry = NULL;
584
585         if (REG(PCIR_DEVVENDOR, 4) != 0xfffffffful) {
586                 devlist_entry = malloc(size, M_DEVBUF, M_WAITOK | M_ZERO);
587                 if (devlist_entry == NULL)
588                         return (NULL);
589
590                 cfg = &devlist_entry->cfg;
591
592                 cfg->domain             = d;
593                 cfg->bus                = b;
594                 cfg->slot               = s;
595                 cfg->func               = f;
596                 cfg->vendor             = REG(PCIR_VENDOR, 2);
597                 cfg->device             = REG(PCIR_DEVICE, 2);
598                 cfg->cmdreg             = REG(PCIR_COMMAND, 2);
599                 cfg->statreg            = REG(PCIR_STATUS, 2);
600                 cfg->baseclass          = REG(PCIR_CLASS, 1);
601                 cfg->subclass           = REG(PCIR_SUBCLASS, 1);
602                 cfg->progif             = REG(PCIR_PROGIF, 1);
603                 cfg->revid              = REG(PCIR_REVID, 1);
604                 cfg->hdrtype            = REG(PCIR_HDRTYPE, 1);
605                 cfg->cachelnsz          = REG(PCIR_CACHELNSZ, 1);
606                 cfg->lattimer           = REG(PCIR_LATTIMER, 1);
607                 cfg->intpin             = REG(PCIR_INTPIN, 1);
608                 cfg->intline            = REG(PCIR_INTLINE, 1);
609
610                 cfg->mingnt             = REG(PCIR_MINGNT, 1);
611                 cfg->maxlat             = REG(PCIR_MAXLAT, 1);
612
613                 cfg->mfdev              = (cfg->hdrtype & PCIM_MFDEV) != 0;
614                 cfg->hdrtype            &= ~PCIM_MFDEV;
615                 STAILQ_INIT(&cfg->maps);
616
617                 pci_fixancient(cfg);
618                 pci_hdrtypedata(pcib, b, s, f, cfg);
619
620                 if (REG(PCIR_STATUS, 2) & PCIM_STATUS_CAPPRESENT)
621                         pci_read_cap(pcib, cfg);
622
623                 STAILQ_INSERT_TAIL(devlist_head, devlist_entry, pci_links);
624
625                 devlist_entry->conf.pc_sel.pc_domain = cfg->domain;
626                 devlist_entry->conf.pc_sel.pc_bus = cfg->bus;
627                 devlist_entry->conf.pc_sel.pc_dev = cfg->slot;
628                 devlist_entry->conf.pc_sel.pc_func = cfg->func;
629                 devlist_entry->conf.pc_hdr = cfg->hdrtype;
630
631                 devlist_entry->conf.pc_subvendor = cfg->subvendor;
632                 devlist_entry->conf.pc_subdevice = cfg->subdevice;
633                 devlist_entry->conf.pc_vendor = cfg->vendor;
634                 devlist_entry->conf.pc_device = cfg->device;
635
636                 devlist_entry->conf.pc_class = cfg->baseclass;
637                 devlist_entry->conf.pc_subclass = cfg->subclass;
638                 devlist_entry->conf.pc_progif = cfg->progif;
639                 devlist_entry->conf.pc_revid = cfg->revid;
640
641                 pci_numdevs++;
642                 pci_generation++;
643         }
644         return (devlist_entry);
645 #undef REG
646 }
647
648 static void
649 pci_read_cap(device_t pcib, pcicfgregs *cfg)
650 {
651 #define REG(n, w)       PCIB_READ_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, n, w)
652 #define WREG(n, v, w)   PCIB_WRITE_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, n, v, w)
653 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
654         uint64_t addr;
655 #endif
656         uint32_t val;
657         int     ptr, nextptr, ptrptr;
658
659         switch (cfg->hdrtype & PCIM_HDRTYPE) {
660         case PCIM_HDRTYPE_NORMAL:
661         case PCIM_HDRTYPE_BRIDGE:
662                 ptrptr = PCIR_CAP_PTR;
663                 break;
664         case PCIM_HDRTYPE_CARDBUS:
665                 ptrptr = PCIR_CAP_PTR_2;        /* cardbus capabilities ptr */
666                 break;
667         default:
668                 return;         /* no extended capabilities support */
669         }
670         nextptr = REG(ptrptr, 1);       /* sanity check? */
671
672         /*
673          * Read capability entries.
674          */
675         while (nextptr != 0) {
676                 /* Sanity check */
677                 if (nextptr > 255) {
678                         printf("illegal PCI extended capability offset %d\n",
679                             nextptr);
680                         return;
681                 }
682                 /* Find the next entry */
683                 ptr = nextptr;
684                 nextptr = REG(ptr + PCICAP_NEXTPTR, 1);
685
686                 /* Process this entry */
687                 switch (REG(ptr + PCICAP_ID, 1)) {
688                 case PCIY_PMG:          /* PCI power management */
689                         if (cfg->pp.pp_cap == 0) {
690                                 cfg->pp.pp_cap = REG(ptr + PCIR_POWER_CAP, 2);
691                                 cfg->pp.pp_status = ptr + PCIR_POWER_STATUS;
692                                 cfg->pp.pp_bse = ptr + PCIR_POWER_BSE;
693                                 if ((nextptr - ptr) > PCIR_POWER_DATA)
694                                         cfg->pp.pp_data = ptr + PCIR_POWER_DATA;
695                         }
696                         break;
697                 case PCIY_HT:           /* HyperTransport */
698                         /* Determine HT-specific capability type. */
699                         val = REG(ptr + PCIR_HT_COMMAND, 2);
700
701                         if ((val & 0xe000) == PCIM_HTCAP_SLAVE)
702                                 cfg->ht.ht_slave = ptr;
703
704 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
705                         switch (val & PCIM_HTCMD_CAP_MASK) {
706                         case PCIM_HTCAP_MSI_MAPPING:
707                                 if (!(val & PCIM_HTCMD_MSI_FIXED)) {
708                                         /* Sanity check the mapping window. */
709                                         addr = REG(ptr + PCIR_HTMSI_ADDRESS_HI,
710                                             4);
711                                         addr <<= 32;
712                                         addr |= REG(ptr + PCIR_HTMSI_ADDRESS_LO,
713                                             4);
714                                         if (addr != MSI_INTEL_ADDR_BASE)
715                                                 device_printf(pcib,
716             "HT device at pci%d:%d:%d:%d has non-default MSI window 0x%llx\n",
717                                                     cfg->domain, cfg->bus,
718                                                     cfg->slot, cfg->func,
719                                                     (long long)addr);
720                                 } else
721                                         addr = MSI_INTEL_ADDR_BASE;
722
723                                 cfg->ht.ht_msimap = ptr;
724                                 cfg->ht.ht_msictrl = val;
725                                 cfg->ht.ht_msiaddr = addr;
726                                 break;
727                         }
728 #endif
729                         break;
730                 case PCIY_MSI:          /* PCI MSI */
731                         cfg->msi.msi_location = ptr;
732                         cfg->msi.msi_ctrl = REG(ptr + PCIR_MSI_CTRL, 2);
733                         cfg->msi.msi_msgnum = 1 << ((cfg->msi.msi_ctrl &
734                                                      PCIM_MSICTRL_MMC_MASK)>>1);
735                         break;
736                 case PCIY_MSIX:         /* PCI MSI-X */
737                         cfg->msix.msix_location = ptr;
738                         cfg->msix.msix_ctrl = REG(ptr + PCIR_MSIX_CTRL, 2);
739                         cfg->msix.msix_msgnum = (cfg->msix.msix_ctrl &
740                             PCIM_MSIXCTRL_TABLE_SIZE) + 1;
741                         val = REG(ptr + PCIR_MSIX_TABLE, 4);
742                         cfg->msix.msix_table_bar = PCIR_BAR(val &
743                             PCIM_MSIX_BIR_MASK);
744                         cfg->msix.msix_table_offset = val & ~PCIM_MSIX_BIR_MASK;
745                         val = REG(ptr + PCIR_MSIX_PBA, 4);
746                         cfg->msix.msix_pba_bar = PCIR_BAR(val &
747                             PCIM_MSIX_BIR_MASK);
748                         cfg->msix.msix_pba_offset = val & ~PCIM_MSIX_BIR_MASK;
749                         break;
750                 case PCIY_VPD:          /* PCI Vital Product Data */
751                         cfg->vpd.vpd_reg = ptr;
752                         break;
753                 case PCIY_SUBVENDOR:
754                         /* Should always be true. */
755                         if ((cfg->hdrtype & PCIM_HDRTYPE) ==
756                             PCIM_HDRTYPE_BRIDGE) {
757                                 val = REG(ptr + PCIR_SUBVENDCAP_ID, 4);
758                                 cfg->subvendor = val & 0xffff;
759                                 cfg->subdevice = val >> 16;
760                         }
761                         break;
762                 case PCIY_PCIX:         /* PCI-X */
763                         /*
764                          * Assume we have a PCI-X chipset if we have
765                          * at least one PCI-PCI bridge with a PCI-X
766                          * capability.  Note that some systems with
767                          * PCI-express or HT chipsets might match on
768                          * this check as well.
769                          */
770                         if ((cfg->hdrtype & PCIM_HDRTYPE) ==
771                             PCIM_HDRTYPE_BRIDGE)
772                                 pcix_chipset = 1;
773                         break;
774                 case PCIY_EXPRESS:      /* PCI-express */
775                         /*
776                          * Assume we have a PCI-express chipset if we have
777                          * at least one PCI-express device.
778                          */
779                         pcie_chipset = 1;
780                         break;
781                 default:
782                         break;
783                 }
784         }
785
786 #if defined(__powerpc__)
787         /*
788          * Enable the MSI mapping window for all HyperTransport
789          * slaves.  PCI-PCI bridges have their windows enabled via
790          * PCIB_MAP_MSI().
791          */
792         if (cfg->ht.ht_slave != 0 && cfg->ht.ht_msimap != 0 &&
793             !(cfg->ht.ht_msictrl & PCIM_HTCMD_MSI_ENABLE)) {
794                 device_printf(pcib,
795             "Enabling MSI window for HyperTransport slave at pci%d:%d:%d:%d\n",
796                     cfg->domain, cfg->bus, cfg->slot, cfg->func);
797                  cfg->ht.ht_msictrl |= PCIM_HTCMD_MSI_ENABLE;
798                  WREG(cfg->ht.ht_msimap + PCIR_HT_COMMAND, cfg->ht.ht_msictrl,
799                      2);
800         }
801 #endif
802 /* REG and WREG use carry through to next functions */
803 }
804
805 /*
806  * PCI Vital Product Data
807  */
808
809 #define PCI_VPD_TIMEOUT         1000000
810
811 static int
812 pci_read_vpd_reg(device_t pcib, pcicfgregs *cfg, int reg, uint32_t *data)
813 {
814         int count = PCI_VPD_TIMEOUT;
815
816         KASSERT((reg & 3) == 0, ("VPD register must by 4 byte aligned"));
817
818         WREG(cfg->vpd.vpd_reg + PCIR_VPD_ADDR, reg, 2);
819
820         while ((REG(cfg->vpd.vpd_reg + PCIR_VPD_ADDR, 2) & 0x8000) != 0x8000) {
821                 if (--count < 0)
822                         return (ENXIO);
823                 DELAY(1);       /* limit looping */
824         }
825         *data = (REG(cfg->vpd.vpd_reg + PCIR_VPD_DATA, 4));
826
827         return (0);
828 }
829
830 #if 0
831 static int
832 pci_write_vpd_reg(device_t pcib, pcicfgregs *cfg, int reg, uint32_t data)
833 {
834         int count = PCI_VPD_TIMEOUT;
835
836         KASSERT((reg & 3) == 0, ("VPD register must by 4 byte aligned"));
837
838         WREG(cfg->vpd.vpd_reg + PCIR_VPD_DATA, data, 4);
839         WREG(cfg->vpd.vpd_reg + PCIR_VPD_ADDR, reg | 0x8000, 2);
840         while ((REG(cfg->vpd.vpd_reg + PCIR_VPD_ADDR, 2) & 0x8000) == 0x8000) {
841                 if (--count < 0)
842                         return (ENXIO);
843                 DELAY(1);       /* limit looping */
844         }
845
846         return (0);
847 }
848 #endif
849
850 #undef PCI_VPD_TIMEOUT
851
852 struct vpd_readstate {
853         device_t        pcib;
854         pcicfgregs      *cfg;
855         uint32_t        val;
856         int             bytesinval;
857         int             off;
858         uint8_t         cksum;
859 };
860
861 static int
862 vpd_nextbyte(struct vpd_readstate *vrs, uint8_t *data)
863 {
864         uint32_t reg;
865         uint8_t byte;
866
867         if (vrs->bytesinval == 0) {
868                 if (pci_read_vpd_reg(vrs->pcib, vrs->cfg, vrs->off, &reg))
869                         return (ENXIO);
870                 vrs->val = le32toh(reg);
871                 vrs->off += 4;
872                 byte = vrs->val & 0xff;
873                 vrs->bytesinval = 3;
874         } else {
875                 vrs->val = vrs->val >> 8;
876                 byte = vrs->val & 0xff;
877                 vrs->bytesinval--;
878         }
879
880         vrs->cksum += byte;
881         *data = byte;
882         return (0);
883 }
884
885 static void
886 pci_read_vpd(device_t pcib, pcicfgregs *cfg)
887 {
888         struct vpd_readstate vrs;
889         int state;
890         int name;
891         int remain;
892         int i;
893         int alloc, off;         /* alloc/off for RO/W arrays */
894         int cksumvalid;
895         int dflen;
896         uint8_t byte;
897         uint8_t byte2;
898
899         /* init vpd reader */
900         vrs.bytesinval = 0;
901         vrs.off = 0;
902         vrs.pcib = pcib;
903         vrs.cfg = cfg;
904         vrs.cksum = 0;
905
906         state = 0;
907         name = remain = i = 0;  /* shut up stupid gcc */
908         alloc = off = 0;        /* shut up stupid gcc */
909         dflen = 0;              /* shut up stupid gcc */
910         cksumvalid = -1;
911         while (state >= 0) {
912                 if (vpd_nextbyte(&vrs, &byte)) {
913                         state = -2;
914                         break;
915                 }
916 #if 0
917                 printf("vpd: val: %#x, off: %d, bytesinval: %d, byte: %#hhx, " \
918                     "state: %d, remain: %d, name: %#x, i: %d\n", vrs.val,
919                     vrs.off, vrs.bytesinval, byte, state, remain, name, i);
920 #endif
921                 switch (state) {
922                 case 0:         /* item name */
923                         if (byte & 0x80) {
924                                 if (vpd_nextbyte(&vrs, &byte2)) {
925                                         state = -2;
926                                         break;
927                                 }
928                                 remain = byte2;
929                                 if (vpd_nextbyte(&vrs, &byte2)) {
930                                         state = -2;
931                                         break;
932                                 }
933                                 remain |= byte2 << 8;
934                                 if (remain > (0x7f*4 - vrs.off)) {
935                                         state = -1;
936                                         printf(
937                             "pci%d:%d:%d:%d: invalid VPD data, remain %#x\n",
938                                             cfg->domain, cfg->bus, cfg->slot,
939                                             cfg->func, remain);
940                                 }
941                                 name = byte & 0x7f;
942                         } else {
943                                 remain = byte & 0x7;
944                                 name = (byte >> 3) & 0xf;
945                         }
946                         switch (name) {
947                         case 0x2:       /* String */
948                                 cfg->vpd.vpd_ident = malloc(remain + 1,
949                                     M_DEVBUF, M_WAITOK);
950                                 i = 0;
951                                 state = 1;
952                                 break;
953                         case 0xf:       /* End */
954                                 state = -1;
955                                 break;
956                         case 0x10:      /* VPD-R */
957                                 alloc = 8;
958                                 off = 0;
959                                 cfg->vpd.vpd_ros = malloc(alloc *
960                                     sizeof(*cfg->vpd.vpd_ros), M_DEVBUF,
961                                     M_WAITOK | M_ZERO);
962                                 state = 2;
963                                 break;
964                         case 0x11:      /* VPD-W */
965                                 alloc = 8;
966                                 off = 0;
967                                 cfg->vpd.vpd_w = malloc(alloc *
968                                     sizeof(*cfg->vpd.vpd_w), M_DEVBUF,
969                                     M_WAITOK | M_ZERO);
970                                 state = 5;
971                                 break;
972                         default:        /* Invalid data, abort */
973                                 state = -1;
974                                 break;
975                         }
976                         break;
977
978                 case 1: /* Identifier String */
979                         cfg->vpd.vpd_ident[i++] = byte;
980                         remain--;
981                         if (remain == 0)  {
982                                 cfg->vpd.vpd_ident[i] = '\0';
983                                 state = 0;
984                         }
985                         break;
986
987                 case 2: /* VPD-R Keyword Header */
988                         if (off == alloc) {
989                                 cfg->vpd.vpd_ros = reallocf(cfg->vpd.vpd_ros,
990                                     (alloc *= 2) * sizeof(*cfg->vpd.vpd_ros),
991                                     M_DEVBUF, M_WAITOK | M_ZERO);
992                         }
993                         cfg->vpd.vpd_ros[off].keyword[0] = byte;
994                         if (vpd_nextbyte(&vrs, &byte2)) {
995                                 state = -2;
996                                 break;
997                         }
998                         cfg->vpd.vpd_ros[off].keyword[1] = byte2;
999                         if (vpd_nextbyte(&vrs, &byte2)) {
1000                                 state = -2;
1001                                 break;
1002                         }
1003                         cfg->vpd.vpd_ros[off].len = dflen = byte2;
1004                         if (dflen == 0 &&
1005                             strncmp(cfg->vpd.vpd_ros[off].keyword, "RV",
1006                             2) == 0) {
1007                                 /*
1008                                  * if this happens, we can't trust the rest
1009                                  * of the VPD.
1010                                  */
1011                                 printf(
1012                                     "pci%d:%d:%d:%d: bad keyword length: %d\n",
1013                                     cfg->domain, cfg->bus, cfg->slot,
1014                                     cfg->func, dflen);
1015                                 cksumvalid = 0;
1016                                 state = -1;
1017                                 break;
1018                         } else if (dflen == 0) {
1019                                 cfg->vpd.vpd_ros[off].value = malloc(1 *
1020                                     sizeof(*cfg->vpd.vpd_ros[off].value),
1021                                     M_DEVBUF, M_WAITOK);
1022                                 cfg->vpd.vpd_ros[off].value[0] = '\x00';
1023                         } else
1024                                 cfg->vpd.vpd_ros[off].value = malloc(
1025                                     (dflen + 1) *
1026                                     sizeof(*cfg->vpd.vpd_ros[off].value),
1027                                     M_DEVBUF, M_WAITOK);
1028                         remain -= 3;
1029                         i = 0;
1030                         /* keep in sync w/ state 3's transistions */
1031                         if (dflen == 0 && remain == 0)
1032                                 state = 0;
1033                         else if (dflen == 0)
1034                                 state = 2;
1035                         else
1036                                 state = 3;
1037                         break;
1038
1039                 case 3: /* VPD-R Keyword Value */
1040                         cfg->vpd.vpd_ros[off].value[i++] = byte;
1041                         if (strncmp(cfg->vpd.vpd_ros[off].keyword,
1042                             "RV", 2) == 0 && cksumvalid == -1) {
1043                                 if (vrs.cksum == 0)
1044                                         cksumvalid = 1;
1045                                 else {
1046                                         if (bootverbose)
1047                                                 printf(
1048                                 "pci%d:%d:%d:%d: bad VPD cksum, remain %hhu\n",
1049                                                     cfg->domain, cfg->bus,
1050                                                     cfg->slot, cfg->func,
1051                                                     vrs.cksum);
1052                                         cksumvalid = 0;
1053                                         state = -1;
1054                                         break;
1055                                 }
1056                         }
1057                         dflen--;
1058                         remain--;
1059                         /* keep in sync w/ state 2's transistions */
1060                         if (dflen == 0)
1061                                 cfg->vpd.vpd_ros[off++].value[i++] = '\0';
1062                         if (dflen == 0 && remain == 0) {
1063                                 cfg->vpd.vpd_rocnt = off;
1064                                 cfg->vpd.vpd_ros = reallocf(cfg->vpd.vpd_ros,
1065                                     off * sizeof(*cfg->vpd.vpd_ros),
1066                                     M_DEVBUF, M_WAITOK | M_ZERO);
1067                                 state = 0;
1068                         } else if (dflen == 0)
1069                                 state = 2;
1070                         break;
1071
1072                 case 4:
1073                         remain--;
1074                         if (remain == 0)
1075                                 state = 0;
1076                         break;
1077
1078                 case 5: /* VPD-W Keyword Header */
1079                         if (off == alloc) {
1080                                 cfg->vpd.vpd_w = reallocf(cfg->vpd.vpd_w,
1081                                     (alloc *= 2) * sizeof(*cfg->vpd.vpd_w),
1082                                     M_DEVBUF, M_WAITOK | M_ZERO);
1083                         }
1084                         cfg->vpd.vpd_w[off].keyword[0] = byte;
1085                         if (vpd_nextbyte(&vrs, &byte2)) {
1086                                 state = -2;
1087                                 break;
1088                         }
1089                         cfg->vpd.vpd_w[off].keyword[1] = byte2;
1090                         if (vpd_nextbyte(&vrs, &byte2)) {
1091                                 state = -2;
1092                                 break;
1093                         }
1094                         cfg->vpd.vpd_w[off].len = dflen = byte2;
1095                         cfg->vpd.vpd_w[off].start = vrs.off - vrs.bytesinval;
1096                         cfg->vpd.vpd_w[off].value = malloc((dflen + 1) *
1097                             sizeof(*cfg->vpd.vpd_w[off].value),
1098                             M_DEVBUF, M_WAITOK);
1099                         remain -= 3;
1100                         i = 0;
1101                         /* keep in sync w/ state 6's transistions */
1102                         if (dflen == 0 && remain == 0)
1103                                 state = 0;
1104                         else if (dflen == 0)
1105                                 state = 5;
1106                         else
1107                                 state = 6;
1108                         break;
1109
1110                 case 6: /* VPD-W Keyword Value */
1111                         cfg->vpd.vpd_w[off].value[i++] = byte;
1112                         dflen--;
1113                         remain--;
1114                         /* keep in sync w/ state 5's transistions */
1115                         if (dflen == 0)
1116                                 cfg->vpd.vpd_w[off++].value[i++] = '\0';
1117                         if (dflen == 0 && remain == 0) {
1118                                 cfg->vpd.vpd_wcnt = off;
1119                                 cfg->vpd.vpd_w = reallocf(cfg->vpd.vpd_w,
1120                                     off * sizeof(*cfg->vpd.vpd_w),
1121                                     M_DEVBUF, M_WAITOK | M_ZERO);
1122                                 state = 0;
1123                         } else if (dflen == 0)
1124                                 state = 5;
1125                         break;
1126
1127                 default:
1128                         printf("pci%d:%d:%d:%d: invalid state: %d\n",
1129                             cfg->domain, cfg->bus, cfg->slot, cfg->func,
1130                             state);
1131                         state = -1;
1132                         break;
1133                 }
1134         }
1135
1136         if (cksumvalid == 0 || state < -1) {
1137                 /* read-only data bad, clean up */
1138                 if (cfg->vpd.vpd_ros != NULL) {
1139                         for (off = 0; cfg->vpd.vpd_ros[off].value; off++)
1140                                 free(cfg->vpd.vpd_ros[off].value, M_DEVBUF);
1141                         free(cfg->vpd.vpd_ros, M_DEVBUF);
1142                         cfg->vpd.vpd_ros = NULL;
1143                 }
1144         }
1145         if (state < -1) {
1146                 /* I/O error, clean up */
1147                 printf("pci%d:%d:%d:%d: failed to read VPD data.\n",
1148                     cfg->domain, cfg->bus, cfg->slot, cfg->func);
1149                 if (cfg->vpd.vpd_ident != NULL) {
1150                         free(cfg->vpd.vpd_ident, M_DEVBUF);
1151                         cfg->vpd.vpd_ident = NULL;
1152                 }
1153                 if (cfg->vpd.vpd_w != NULL) {
1154                         for (off = 0; cfg->vpd.vpd_w[off].value; off++)
1155                                 free(cfg->vpd.vpd_w[off].value, M_DEVBUF);
1156                         free(cfg->vpd.vpd_w, M_DEVBUF);
1157                         cfg->vpd.vpd_w = NULL;
1158                 }
1159         }
1160         cfg->vpd.vpd_cached = 1;
1161 #undef REG
1162 #undef WREG
1163 }
1164
1165 int
1166 pci_get_vpd_ident_method(device_t dev, device_t child, const char **identptr)
1167 {
1168         struct pci_devinfo *dinfo = device_get_ivars(child);
1169         pcicfgregs *cfg = &dinfo->cfg;
1170
1171         if (!cfg->vpd.vpd_cached && cfg->vpd.vpd_reg != 0)
1172                 pci_read_vpd(device_get_parent(dev), cfg);
1173
1174         *identptr = cfg->vpd.vpd_ident;
1175
1176         if (*identptr == NULL)
1177                 return (ENXIO);
1178
1179         return (0);
1180 }
1181
1182 int
1183 pci_get_vpd_readonly_method(device_t dev, device_t child, const char *kw,
1184         const char **vptr)
1185 {
1186         struct pci_devinfo *dinfo = device_get_ivars(child);
1187         pcicfgregs *cfg = &dinfo->cfg;
1188         int i;
1189
1190         if (!cfg->vpd.vpd_cached && cfg->vpd.vpd_reg != 0)
1191                 pci_read_vpd(device_get_parent(dev), cfg);
1192
1193         for (i = 0; i < cfg->vpd.vpd_rocnt; i++)
1194                 if (memcmp(kw, cfg->vpd.vpd_ros[i].keyword,
1195                     sizeof(cfg->vpd.vpd_ros[i].keyword)) == 0) {
1196                         *vptr = cfg->vpd.vpd_ros[i].value;
1197                         return (0);
1198                 }
1199
1200         *vptr = NULL;
1201         return (ENXIO);
1202 }
1203
1204 struct pcicfg_vpd *
1205 pci_fetch_vpd_list(device_t dev)
1206 {
1207         struct pci_devinfo *dinfo = device_get_ivars(dev);
1208         pcicfgregs *cfg = &dinfo->cfg;
1209
1210         if (!cfg->vpd.vpd_cached && cfg->vpd.vpd_reg != 0)
1211                 pci_read_vpd(device_get_parent(device_get_parent(dev)), cfg);
1212         return (&cfg->vpd);
1213 }
1214
1215 /*
1216  * Find the requested extended capability and return the offset in
1217  * configuration space via the pointer provided. The function returns
1218  * 0 on success and error code otherwise.
1219  */
1220 int
1221 pci_find_extcap_method(device_t dev, device_t child, int capability,
1222     int *capreg)
1223 {
1224         struct pci_devinfo *dinfo = device_get_ivars(child);
1225         pcicfgregs *cfg = &dinfo->cfg;
1226         u_int32_t status;
1227         u_int8_t ptr;
1228
1229         /*
1230          * Check the CAP_LIST bit of the PCI status register first.
1231          */
1232         status = pci_read_config(child, PCIR_STATUS, 2);
1233         if (!(status & PCIM_STATUS_CAPPRESENT))
1234                 return (ENXIO);
1235
1236         /*
1237          * Determine the start pointer of the capabilities list.
1238          */
1239         switch (cfg->hdrtype & PCIM_HDRTYPE) {
1240         case PCIM_HDRTYPE_NORMAL:
1241         case PCIM_HDRTYPE_BRIDGE:
1242                 ptr = PCIR_CAP_PTR;
1243                 break;
1244         case PCIM_HDRTYPE_CARDBUS:
1245                 ptr = PCIR_CAP_PTR_2;
1246                 break;
1247         default:
1248                 /* XXX: panic? */
1249                 return (ENXIO);         /* no extended capabilities support */
1250         }
1251         ptr = pci_read_config(child, ptr, 1);
1252
1253         /*
1254          * Traverse the capabilities list.
1255          */
1256         while (ptr != 0) {
1257                 if (pci_read_config(child, ptr + PCICAP_ID, 1) == capability) {
1258                         if (capreg != NULL)
1259                                 *capreg = ptr;
1260                         return (0);
1261                 }
1262                 ptr = pci_read_config(child, ptr + PCICAP_NEXTPTR, 1);
1263         }
1264
1265         return (ENOENT);
1266 }
1267
1268 /*
1269  * Support for MSI-X message interrupts.
1270  */
1271 void
1272 pci_enable_msix(device_t dev, u_int index, uint64_t address, uint32_t data)
1273 {
1274         struct pci_devinfo *dinfo = device_get_ivars(dev);
1275         struct pcicfg_msix *msix = &dinfo->cfg.msix;
1276         uint32_t offset;
1277
1278         KASSERT(msix->msix_table_len > index, ("bogus index"));
1279         offset = msix->msix_table_offset + index * 16;
1280         bus_write_4(msix->msix_table_res, offset, address & 0xffffffff);
1281         bus_write_4(msix->msix_table_res, offset + 4, address >> 32);
1282         bus_write_4(msix->msix_table_res, offset + 8, data);
1283
1284         /* Enable MSI -> HT mapping. */
1285         pci_ht_map_msi(dev, address);
1286 }
1287
1288 void
1289 pci_mask_msix(device_t dev, u_int index)
1290 {
1291         struct pci_devinfo *dinfo = device_get_ivars(dev);
1292         struct pcicfg_msix *msix = &dinfo->cfg.msix;
1293         uint32_t offset, val;
1294
1295         KASSERT(msix->msix_msgnum > index, ("bogus index"));
1296         offset = msix->msix_table_offset + index * 16 + 12;
1297         val = bus_read_4(msix->msix_table_res, offset);
1298         if (!(val & PCIM_MSIX_VCTRL_MASK)) {
1299                 val |= PCIM_MSIX_VCTRL_MASK;
1300                 bus_write_4(msix->msix_table_res, offset, val);
1301         }
1302 }
1303
1304 void
1305 pci_unmask_msix(device_t dev, u_int index)
1306 {
1307         struct pci_devinfo *dinfo = device_get_ivars(dev);
1308         struct pcicfg_msix *msix = &dinfo->cfg.msix;
1309         uint32_t offset, val;
1310
1311         KASSERT(msix->msix_table_len > index, ("bogus index"));
1312         offset = msix->msix_table_offset + index * 16 + 12;
1313         val = bus_read_4(msix->msix_table_res, offset);
1314         if (val & PCIM_MSIX_VCTRL_MASK) {
1315                 val &= ~PCIM_MSIX_VCTRL_MASK;
1316                 bus_write_4(msix->msix_table_res, offset, val);
1317         }
1318 }
1319
1320 int
1321 pci_pending_msix(device_t dev, u_int index)
1322 {
1323         struct pci_devinfo *dinfo = device_get_ivars(dev);
1324         struct pcicfg_msix *msix = &dinfo->cfg.msix;
1325         uint32_t offset, bit;
1326
1327         KASSERT(msix->msix_table_len > index, ("bogus index"));
1328         offset = msix->msix_pba_offset + (index / 32) * 4;
1329         bit = 1 << index % 32;
1330         return (bus_read_4(msix->msix_pba_res, offset) & bit);
1331 }
1332
1333 /*
1334  * Restore MSI-X registers and table during resume.  If MSI-X is
1335  * enabled then walk the virtual table to restore the actual MSI-X
1336  * table.
1337  */
1338 static void
1339 pci_resume_msix(device_t dev)
1340 {
1341         struct pci_devinfo *dinfo = device_get_ivars(dev);
1342         struct pcicfg_msix *msix = &dinfo->cfg.msix;
1343         struct msix_table_entry *mte;
1344         struct msix_vector *mv;
1345         int i;
1346
1347         if (msix->msix_alloc > 0) {
1348                 /* First, mask all vectors. */
1349                 for (i = 0; i < msix->msix_msgnum; i++)
1350                         pci_mask_msix(dev, i);
1351
1352                 /* Second, program any messages with at least one handler. */
1353                 for (i = 0; i < msix->msix_table_len; i++) {
1354                         mte = &msix->msix_table[i];
1355                         if (mte->mte_vector == 0 || mte->mte_handlers == 0)
1356                                 continue;
1357                         mv = &msix->msix_vectors[mte->mte_vector - 1];
1358                         pci_enable_msix(dev, i, mv->mv_address, mv->mv_data);
1359                         pci_unmask_msix(dev, i);
1360                 }
1361         }
1362         pci_write_config(dev, msix->msix_location + PCIR_MSIX_CTRL,
1363             msix->msix_ctrl, 2);
1364 }
1365
1366 /*
1367  * Attempt to allocate *count MSI-X messages.  The actual number allocated is
1368  * returned in *count.  After this function returns, each message will be
1369  * available to the driver as SYS_RES_IRQ resources starting at rid 1.
1370  */
1371 int
1372 pci_alloc_msix_method(device_t dev, device_t child, int *count)
1373 {
1374         struct pci_devinfo *dinfo = device_get_ivars(child);
1375         pcicfgregs *cfg = &dinfo->cfg;
1376         struct resource_list_entry *rle;
1377         int actual, error, i, irq, max;
1378
1379         /* Don't let count == 0 get us into trouble. */
1380         if (*count == 0)
1381                 return (EINVAL);
1382
1383         /* If rid 0 is allocated, then fail. */
1384         rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, 0);
1385         if (rle != NULL && rle->res != NULL)
1386                 return (ENXIO);
1387
1388         /* Already have allocated messages? */
1389         if (cfg->msi.msi_alloc != 0 || cfg->msix.msix_alloc != 0)
1390                 return (ENXIO);
1391
1392         /* If MSI-X is blacklisted for this system, fail. */
1393         if (pci_msix_blacklisted())
1394                 return (ENXIO);
1395
1396         /* MSI-X capability present? */
1397         if (cfg->msix.msix_location == 0 || !pci_do_msix)
1398                 return (ENODEV);
1399
1400         /* Make sure the appropriate BARs are mapped. */
1401         rle = resource_list_find(&dinfo->resources, SYS_RES_MEMORY,
1402             cfg->msix.msix_table_bar);
1403         if (rle == NULL || rle->res == NULL ||
1404             !(rman_get_flags(rle->res) & RF_ACTIVE))
1405                 return (ENXIO);
1406         cfg->msix.msix_table_res = rle->res;
1407         if (cfg->msix.msix_pba_bar != cfg->msix.msix_table_bar) {
1408                 rle = resource_list_find(&dinfo->resources, SYS_RES_MEMORY,
1409                     cfg->msix.msix_pba_bar);
1410                 if (rle == NULL || rle->res == NULL ||
1411                     !(rman_get_flags(rle->res) & RF_ACTIVE))
1412                         return (ENXIO);
1413         }
1414         cfg->msix.msix_pba_res = rle->res;
1415
1416         if (bootverbose)
1417                 device_printf(child,
1418                     "attempting to allocate %d MSI-X vectors (%d supported)\n",
1419                     *count, cfg->msix.msix_msgnum);
1420         max = min(*count, cfg->msix.msix_msgnum);
1421         for (i = 0; i < max; i++) {
1422                 /* Allocate a message. */
1423                 error = PCIB_ALLOC_MSIX(device_get_parent(dev), child, &irq);
1424                 if (error) {
1425                         if (i == 0)
1426                                 return (error);
1427                         break;
1428                 }
1429                 resource_list_add(&dinfo->resources, SYS_RES_IRQ, i + 1, irq,
1430                     irq, 1);
1431         }
1432         actual = i;
1433
1434         if (bootverbose) {
1435                 rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, 1);
1436                 if (actual == 1)
1437                         device_printf(child, "using IRQ %lu for MSI-X\n",
1438                             rle->start);
1439                 else {
1440                         int run;
1441
1442                         /*
1443                          * Be fancy and try to print contiguous runs of
1444                          * IRQ values as ranges.  'irq' is the previous IRQ.
1445                          * 'run' is true if we are in a range.
1446                          */
1447                         device_printf(child, "using IRQs %lu", rle->start);
1448                         irq = rle->start;
1449                         run = 0;
1450                         for (i = 1; i < actual; i++) {
1451                                 rle = resource_list_find(&dinfo->resources,
1452                                     SYS_RES_IRQ, i + 1);
1453
1454                                 /* Still in a run? */
1455                                 if (rle->start == irq + 1) {
1456                                         run = 1;
1457                                         irq++;
1458                                         continue;
1459                                 }
1460
1461                                 /* Finish previous range. */
1462                                 if (run) {
1463                                         printf("-%d", irq);
1464                                         run = 0;
1465                                 }
1466
1467                                 /* Start new range. */
1468                                 printf(",%lu", rle->start);
1469                                 irq = rle->start;
1470                         }
1471
1472                         /* Unfinished range? */
1473                         if (run)
1474                                 printf("-%d", irq);
1475                         printf(" for MSI-X\n");
1476                 }
1477         }
1478
1479         /* Mask all vectors. */
1480         for (i = 0; i < cfg->msix.msix_msgnum; i++)
1481                 pci_mask_msix(child, i);
1482
1483         /* Allocate and initialize vector data and virtual table. */
1484         cfg->msix.msix_vectors = malloc(sizeof(struct msix_vector) * actual,
1485             M_DEVBUF, M_WAITOK | M_ZERO);
1486         cfg->msix.msix_table = malloc(sizeof(struct msix_table_entry) * actual,
1487             M_DEVBUF, M_WAITOK | M_ZERO);
1488         for (i = 0; i < actual; i++) {
1489                 rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, i + 1);
1490                 cfg->msix.msix_vectors[i].mv_irq = rle->start;
1491                 cfg->msix.msix_table[i].mte_vector = i + 1;
1492         }
1493
1494         /* Update control register to enable MSI-X. */
1495         cfg->msix.msix_ctrl |= PCIM_MSIXCTRL_MSIX_ENABLE;
1496         pci_write_config(child, cfg->msix.msix_location + PCIR_MSIX_CTRL,
1497             cfg->msix.msix_ctrl, 2);
1498
1499         /* Update counts of alloc'd messages. */
1500         cfg->msix.msix_alloc = actual;
1501         cfg->msix.msix_table_len = actual;
1502         *count = actual;
1503         return (0);
1504 }
1505
1506 /*
1507  * By default, pci_alloc_msix() will assign the allocated IRQ
1508  * resources consecutively to the first N messages in the MSI-X table.
1509  * However, device drivers may want to use different layouts if they
1510  * either receive fewer messages than they asked for, or they wish to
1511  * populate the MSI-X table sparsely.  This method allows the driver
1512  * to specify what layout it wants.  It must be called after a
1513  * successful pci_alloc_msix() but before any of the associated
1514  * SYS_RES_IRQ resources are allocated via bus_alloc_resource().
1515  *
1516  * The 'vectors' array contains 'count' message vectors.  The array
1517  * maps directly to the MSI-X table in that index 0 in the array
1518  * specifies the vector for the first message in the MSI-X table, etc.
1519  * The vector value in each array index can either be 0 to indicate
1520  * that no vector should be assigned to a message slot, or it can be a
1521  * number from 1 to N (where N is the count returned from a
1522  * succcessful call to pci_alloc_msix()) to indicate which message
1523  * vector (IRQ) to be used for the corresponding message.
1524  *
1525  * On successful return, each message with a non-zero vector will have
1526  * an associated SYS_RES_IRQ whose rid is equal to the array index +
1527  * 1.  Additionally, if any of the IRQs allocated via the previous
1528  * call to pci_alloc_msix() are not used in the mapping, those IRQs
1529  * will be freed back to the system automatically.
1530  *
1531  * For example, suppose a driver has a MSI-X table with 6 messages and
1532  * asks for 6 messages, but pci_alloc_msix() only returns a count of
1533  * 3.  Call the three vectors allocated by pci_alloc_msix() A, B, and
1534  * C.  After the call to pci_alloc_msix(), the device will be setup to
1535  * have an MSI-X table of ABC--- (where - means no vector assigned).
1536  * If the driver ten passes a vector array of { 1, 0, 1, 2, 0, 2 },
1537  * then the MSI-X table will look like A-AB-B, and the 'C' vector will
1538  * be freed back to the system.  This device will also have valid
1539  * SYS_RES_IRQ rids of 1, 3, 4, and 6.
1540  *
1541  * In any case, the SYS_RES_IRQ rid X will always map to the message
1542  * at MSI-X table index X - 1 and will only be valid if a vector is
1543  * assigned to that table entry.
1544  */
1545 int
1546 pci_remap_msix_method(device_t dev, device_t child, int count,
1547     const u_int *vectors)
1548 {
1549         struct pci_devinfo *dinfo = device_get_ivars(child);
1550         struct pcicfg_msix *msix = &dinfo->cfg.msix;
1551         struct resource_list_entry *rle;
1552         int i, irq, j, *used;
1553
1554         /*
1555          * Have to have at least one message in the table but the
1556          * table can't be bigger than the actual MSI-X table in the
1557          * device.
1558          */
1559         if (count == 0 || count > msix->msix_msgnum)
1560                 return (EINVAL);
1561
1562         /* Sanity check the vectors. */
1563         for (i = 0; i < count; i++)
1564                 if (vectors[i] > msix->msix_alloc)
1565                         return (EINVAL);
1566
1567         /*
1568          * Make sure there aren't any holes in the vectors to be used.
1569          * It's a big pain to support it, and it doesn't really make
1570          * sense anyway.  Also, at least one vector must be used.
1571          */
1572         used = malloc(sizeof(int) * msix->msix_alloc, M_DEVBUF, M_WAITOK |
1573             M_ZERO);
1574         for (i = 0; i < count; i++)
1575                 if (vectors[i] != 0)
1576                         used[vectors[i] - 1] = 1;
1577         for (i = 0; i < msix->msix_alloc - 1; i++)
1578                 if (used[i] == 0 && used[i + 1] == 1) {
1579                         free(used, M_DEVBUF);
1580                         return (EINVAL);
1581                 }
1582         if (used[0] != 1) {
1583                 free(used, M_DEVBUF);
1584                 return (EINVAL);
1585         }
1586         
1587         /* Make sure none of the resources are allocated. */
1588         for (i = 0; i < msix->msix_table_len; i++) {
1589                 if (msix->msix_table[i].mte_vector == 0)
1590                         continue;
1591                 if (msix->msix_table[i].mte_handlers > 0)
1592                         return (EBUSY);
1593                 rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, i + 1);
1594                 KASSERT(rle != NULL, ("missing resource"));
1595                 if (rle->res != NULL)
1596                         return (EBUSY);
1597         }
1598
1599         /* Free the existing resource list entries. */
1600         for (i = 0; i < msix->msix_table_len; i++) {
1601                 if (msix->msix_table[i].mte_vector == 0)
1602                         continue;
1603                 resource_list_delete(&dinfo->resources, SYS_RES_IRQ, i + 1);
1604         }
1605
1606         /*
1607          * Build the new virtual table keeping track of which vectors are
1608          * used.
1609          */
1610         free(msix->msix_table, M_DEVBUF);
1611         msix->msix_table = malloc(sizeof(struct msix_table_entry) * count,
1612             M_DEVBUF, M_WAITOK | M_ZERO);
1613         for (i = 0; i < count; i++)
1614                 msix->msix_table[i].mte_vector = vectors[i];
1615         msix->msix_table_len = count;
1616
1617         /* Free any unused IRQs and resize the vectors array if necessary. */
1618         j = msix->msix_alloc - 1;
1619         if (used[j] == 0) {
1620                 struct msix_vector *vec;
1621
1622                 while (used[j] == 0) {
1623                         PCIB_RELEASE_MSIX(device_get_parent(dev), child,
1624                             msix->msix_vectors[j].mv_irq);
1625                         j--;
1626                 }
1627                 vec = malloc(sizeof(struct msix_vector) * (j + 1), M_DEVBUF,
1628                     M_WAITOK);
1629                 bcopy(msix->msix_vectors, vec, sizeof(struct msix_vector) *
1630                     (j + 1));
1631                 free(msix->msix_vectors, M_DEVBUF);
1632                 msix->msix_vectors = vec;
1633                 msix->msix_alloc = j + 1;
1634         }
1635         free(used, M_DEVBUF);
1636
1637         /* Map the IRQs onto the rids. */
1638         for (i = 0; i < count; i++) {
1639                 if (vectors[i] == 0)
1640                         continue;
1641                 irq = msix->msix_vectors[vectors[i]].mv_irq;
1642                 resource_list_add(&dinfo->resources, SYS_RES_IRQ, i + 1, irq,
1643                     irq, 1);
1644         }
1645
1646         if (bootverbose) {
1647                 device_printf(child, "Remapped MSI-X IRQs as: ");
1648                 for (i = 0; i < count; i++) {
1649                         if (i != 0)
1650                                 printf(", ");
1651                         if (vectors[i] == 0)
1652                                 printf("---");
1653                         else
1654                                 printf("%d",
1655                                     msix->msix_vectors[vectors[i]].mv_irq);
1656                 }
1657                 printf("\n");
1658         }
1659
1660         return (0);
1661 }
1662
1663 static int
1664 pci_release_msix(device_t dev, device_t child)
1665 {
1666         struct pci_devinfo *dinfo = device_get_ivars(child);
1667         struct pcicfg_msix *msix = &dinfo->cfg.msix;
1668         struct resource_list_entry *rle;
1669         int i;
1670
1671         /* Do we have any messages to release? */
1672         if (msix->msix_alloc == 0)
1673                 return (ENODEV);
1674
1675         /* Make sure none of the resources are allocated. */
1676         for (i = 0; i < msix->msix_table_len; i++) {
1677                 if (msix->msix_table[i].mte_vector == 0)
1678                         continue;
1679                 if (msix->msix_table[i].mte_handlers > 0)
1680                         return (EBUSY);
1681                 rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, i + 1);
1682                 KASSERT(rle != NULL, ("missing resource"));
1683                 if (rle->res != NULL)
1684                         return (EBUSY);
1685         }
1686
1687         /* Update control register to disable MSI-X. */
1688         msix->msix_ctrl &= ~PCIM_MSIXCTRL_MSIX_ENABLE;
1689         pci_write_config(child, msix->msix_location + PCIR_MSIX_CTRL,
1690             msix->msix_ctrl, 2);
1691
1692         /* Free the resource list entries. */
1693         for (i = 0; i < msix->msix_table_len; i++) {
1694                 if (msix->msix_table[i].mte_vector == 0)
1695                         continue;
1696                 resource_list_delete(&dinfo->resources, SYS_RES_IRQ, i + 1);
1697         }
1698         free(msix->msix_table, M_DEVBUF);
1699         msix->msix_table_len = 0;
1700
1701         /* Release the IRQs. */
1702         for (i = 0; i < msix->msix_alloc; i++)
1703                 PCIB_RELEASE_MSIX(device_get_parent(dev), child,
1704                     msix->msix_vectors[i].mv_irq);
1705         free(msix->msix_vectors, M_DEVBUF);
1706         msix->msix_alloc = 0;
1707         return (0);
1708 }
1709
1710 /*
1711  * Return the max supported MSI-X messages this device supports.
1712  * Basically, assuming the MD code can alloc messages, this function
1713  * should return the maximum value that pci_alloc_msix() can return.
1714  * Thus, it is subject to the tunables, etc.
1715  */
1716 int
1717 pci_msix_count_method(device_t dev, device_t child)
1718 {
1719         struct pci_devinfo *dinfo = device_get_ivars(child);
1720         struct pcicfg_msix *msix = &dinfo->cfg.msix;
1721
1722         if (pci_do_msix && msix->msix_location != 0)
1723                 return (msix->msix_msgnum);
1724         return (0);
1725 }
1726
1727 /*
1728  * HyperTransport MSI mapping control
1729  */
1730 void
1731 pci_ht_map_msi(device_t dev, uint64_t addr)
1732 {
1733         struct pci_devinfo *dinfo = device_get_ivars(dev);
1734         struct pcicfg_ht *ht = &dinfo->cfg.ht;
1735
1736         if (!ht->ht_msimap)
1737                 return;
1738
1739         if (addr && !(ht->ht_msictrl & PCIM_HTCMD_MSI_ENABLE) &&
1740             ht->ht_msiaddr >> 20 == addr >> 20) {
1741                 /* Enable MSI -> HT mapping. */
1742                 ht->ht_msictrl |= PCIM_HTCMD_MSI_ENABLE;
1743                 pci_write_config(dev, ht->ht_msimap + PCIR_HT_COMMAND,
1744                     ht->ht_msictrl, 2);
1745         }
1746
1747         if (!addr && ht->ht_msictrl & PCIM_HTCMD_MSI_ENABLE) {
1748                 /* Disable MSI -> HT mapping. */
1749                 ht->ht_msictrl &= ~PCIM_HTCMD_MSI_ENABLE;
1750                 pci_write_config(dev, ht->ht_msimap + PCIR_HT_COMMAND,
1751                     ht->ht_msictrl, 2);
1752         }
1753 }
1754
1755 int
1756 pci_get_max_read_req(device_t dev)
1757 {
1758         int cap;
1759         uint16_t val;
1760
1761         if (pci_find_cap(dev, PCIY_EXPRESS, &cap) != 0)
1762                 return (0);
1763         val = pci_read_config(dev, cap + PCIER_DEVICE_CTL, 2);
1764         val &= PCIEM_CTL_MAX_READ_REQUEST;
1765         val >>= 12;
1766         return (1 << (val + 7));
1767 }
1768
1769 int
1770 pci_set_max_read_req(device_t dev, int size)
1771 {
1772         int cap;
1773         uint16_t val;
1774
1775         if (pci_find_cap(dev, PCIY_EXPRESS, &cap) != 0)
1776                 return (0);
1777         if (size < 128)
1778                 size = 128;
1779         if (size > 4096)
1780                 size = 4096;
1781         size = (1 << (fls(size) - 1));
1782         val = pci_read_config(dev, cap + PCIER_DEVICE_CTL, 2);
1783         val &= ~PCIEM_CTL_MAX_READ_REQUEST;
1784         val |= (fls(size) - 8) << 12;
1785         pci_write_config(dev, cap + PCIER_DEVICE_CTL, val, 2);
1786         return (size);
1787 }
1788
1789 /*
1790  * Support for MSI message signalled interrupts.
1791  */
1792 void
1793 pci_enable_msi(device_t dev, uint64_t address, uint16_t data)
1794 {
1795         struct pci_devinfo *dinfo = device_get_ivars(dev);
1796         struct pcicfg_msi *msi = &dinfo->cfg.msi;
1797
1798         /* Write data and address values. */
1799         pci_write_config(dev, msi->msi_location + PCIR_MSI_ADDR,
1800             address & 0xffffffff, 4);
1801         if (msi->msi_ctrl & PCIM_MSICTRL_64BIT) {
1802                 pci_write_config(dev, msi->msi_location + PCIR_MSI_ADDR_HIGH,
1803                     address >> 32, 4);
1804                 pci_write_config(dev, msi->msi_location + PCIR_MSI_DATA_64BIT,
1805                     data, 2);
1806         } else
1807                 pci_write_config(dev, msi->msi_location + PCIR_MSI_DATA, data,
1808                     2);
1809
1810         /* Enable MSI in the control register. */
1811         msi->msi_ctrl |= PCIM_MSICTRL_MSI_ENABLE;
1812         pci_write_config(dev, msi->msi_location + PCIR_MSI_CTRL, msi->msi_ctrl,
1813             2);
1814
1815         /* Enable MSI -> HT mapping. */
1816         pci_ht_map_msi(dev, address);
1817 }
1818
1819 void
1820 pci_disable_msi(device_t dev)
1821 {
1822         struct pci_devinfo *dinfo = device_get_ivars(dev);
1823         struct pcicfg_msi *msi = &dinfo->cfg.msi;
1824
1825         /* Disable MSI -> HT mapping. */
1826         pci_ht_map_msi(dev, 0);
1827
1828         /* Disable MSI in the control register. */
1829         msi->msi_ctrl &= ~PCIM_MSICTRL_MSI_ENABLE;
1830         pci_write_config(dev, msi->msi_location + PCIR_MSI_CTRL, msi->msi_ctrl,
1831             2);
1832 }
1833
1834 /*
1835  * Restore MSI registers during resume.  If MSI is enabled then
1836  * restore the data and address registers in addition to the control
1837  * register.
1838  */
1839 static void
1840 pci_resume_msi(device_t dev)
1841 {
1842         struct pci_devinfo *dinfo = device_get_ivars(dev);
1843         struct pcicfg_msi *msi = &dinfo->cfg.msi;
1844         uint64_t address;
1845         uint16_t data;
1846
1847         if (msi->msi_ctrl & PCIM_MSICTRL_MSI_ENABLE) {
1848                 address = msi->msi_addr;
1849                 data = msi->msi_data;
1850                 pci_write_config(dev, msi->msi_location + PCIR_MSI_ADDR,
1851                     address & 0xffffffff, 4);
1852                 if (msi->msi_ctrl & PCIM_MSICTRL_64BIT) {
1853                         pci_write_config(dev, msi->msi_location +
1854                             PCIR_MSI_ADDR_HIGH, address >> 32, 4);
1855                         pci_write_config(dev, msi->msi_location +
1856                             PCIR_MSI_DATA_64BIT, data, 2);
1857                 } else
1858                         pci_write_config(dev, msi->msi_location + PCIR_MSI_DATA,
1859                             data, 2);
1860         }
1861         pci_write_config(dev, msi->msi_location + PCIR_MSI_CTRL, msi->msi_ctrl,
1862             2);
1863 }
1864
1865 static int
1866 pci_remap_intr_method(device_t bus, device_t dev, u_int irq)
1867 {
1868         struct pci_devinfo *dinfo = device_get_ivars(dev);
1869         pcicfgregs *cfg = &dinfo->cfg;
1870         struct resource_list_entry *rle;
1871         struct msix_table_entry *mte;
1872         struct msix_vector *mv;
1873         uint64_t addr;
1874         uint32_t data;  
1875         int error, i, j;
1876
1877         /*
1878          * Handle MSI first.  We try to find this IRQ among our list
1879          * of MSI IRQs.  If we find it, we request updated address and
1880          * data registers and apply the results.
1881          */
1882         if (cfg->msi.msi_alloc > 0) {
1883
1884                 /* If we don't have any active handlers, nothing to do. */
1885                 if (cfg->msi.msi_handlers == 0)
1886                         return (0);
1887                 for (i = 0; i < cfg->msi.msi_alloc; i++) {
1888                         rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ,
1889                             i + 1);
1890                         if (rle->start == irq) {
1891                                 error = PCIB_MAP_MSI(device_get_parent(bus),
1892                                     dev, irq, &addr, &data);
1893                                 if (error)
1894                                         return (error);
1895                                 pci_disable_msi(dev);
1896                                 dinfo->cfg.msi.msi_addr = addr;
1897                                 dinfo->cfg.msi.msi_data = data;
1898                                 pci_enable_msi(dev, addr, data);
1899                                 return (0);
1900                         }
1901                 }
1902                 return (ENOENT);
1903         }
1904
1905         /*
1906          * For MSI-X, we check to see if we have this IRQ.  If we do,
1907          * we request the updated mapping info.  If that works, we go
1908          * through all the slots that use this IRQ and update them.
1909          */
1910         if (cfg->msix.msix_alloc > 0) {
1911                 for (i = 0; i < cfg->msix.msix_alloc; i++) {
1912                         mv = &cfg->msix.msix_vectors[i];
1913                         if (mv->mv_irq == irq) {
1914                                 error = PCIB_MAP_MSI(device_get_parent(bus),
1915                                     dev, irq, &addr, &data);
1916                                 if (error)
1917                                         return (error);
1918                                 mv->mv_address = addr;
1919                                 mv->mv_data = data;
1920                                 for (j = 0; j < cfg->msix.msix_table_len; j++) {
1921                                         mte = &cfg->msix.msix_table[j];
1922                                         if (mte->mte_vector != i + 1)
1923                                                 continue;
1924                                         if (mte->mte_handlers == 0)
1925                                                 continue;
1926                                         pci_mask_msix(dev, j);
1927                                         pci_enable_msix(dev, j, addr, data);
1928                                         pci_unmask_msix(dev, j);
1929                                 }
1930                         }
1931                 }
1932                 return (ENOENT);
1933         }
1934
1935         return (ENOENT);
1936 }
1937
1938 /*
1939  * Returns true if the specified device is blacklisted because MSI
1940  * doesn't work.
1941  */
1942 int
1943 pci_msi_device_blacklisted(device_t dev)
1944 {
1945
1946         if (!pci_honor_msi_blacklist)
1947                 return (0);
1948
1949         return (pci_has_quirk(pci_get_devid(dev), PCI_QUIRK_DISABLE_MSI));
1950 }
1951
1952 /*
1953  * Determine if MSI is blacklisted globally on this system.  Currently,
1954  * we just check for blacklisted chipsets as represented by the
1955  * host-PCI bridge at device 0:0:0.  In the future, it may become
1956  * necessary to check other system attributes, such as the kenv values
1957  * that give the motherboard manufacturer and model number.
1958  */
1959 static int
1960 pci_msi_blacklisted(void)
1961 {
1962         device_t dev;
1963
1964         if (!pci_honor_msi_blacklist)
1965                 return (0);
1966
1967         /* Blacklist all non-PCI-express and non-PCI-X chipsets. */
1968         if (!(pcie_chipset || pcix_chipset)) {
1969                 if (vm_guest != VM_GUEST_NO) {
1970                         /*
1971                          * Whitelist older chipsets in virtual
1972                          * machines known to support MSI.
1973                          */
1974                         dev = pci_find_bsf(0, 0, 0);
1975                         if (dev != NULL)
1976                                 return (!pci_has_quirk(pci_get_devid(dev),
1977                                         PCI_QUIRK_ENABLE_MSI_VM));
1978                 }
1979                 return (1);
1980         }
1981
1982         dev = pci_find_bsf(0, 0, 0);
1983         if (dev != NULL)
1984                 return (pci_msi_device_blacklisted(dev));
1985         return (0);
1986 }
1987
1988 /*
1989  * Returns true if the specified device is blacklisted because MSI-X
1990  * doesn't work.  Note that this assumes that if MSI doesn't work,
1991  * MSI-X doesn't either.
1992  */
1993 int
1994 pci_msix_device_blacklisted(device_t dev)
1995 {
1996
1997         if (!pci_honor_msi_blacklist)
1998                 return (0);
1999
2000         if (pci_has_quirk(pci_get_devid(dev), PCI_QUIRK_DISABLE_MSIX))
2001                 return (1);
2002
2003         return (pci_msi_device_blacklisted(dev));
2004 }
2005
2006 /*
2007  * Determine if MSI-X is blacklisted globally on this system.  If MSI
2008  * is blacklisted, assume that MSI-X is as well.  Check for additional
2009  * chipsets where MSI works but MSI-X does not.
2010  */
2011 static int
2012 pci_msix_blacklisted(void)
2013 {
2014         device_t dev;
2015
2016         if (!pci_honor_msi_blacklist)
2017                 return (0);
2018
2019         dev = pci_find_bsf(0, 0, 0);
2020         if (dev != NULL && pci_has_quirk(pci_get_devid(dev),
2021             PCI_QUIRK_DISABLE_MSIX))
2022                 return (1);
2023
2024         return (pci_msi_blacklisted());
2025 }
2026
2027 /*
2028  * Attempt to allocate *count MSI messages.  The actual number allocated is
2029  * returned in *count.  After this function returns, each message will be
2030  * available to the driver as SYS_RES_IRQ resources starting at a rid 1.
2031  */
2032 int
2033 pci_alloc_msi_method(device_t dev, device_t child, int *count)
2034 {
2035         struct pci_devinfo *dinfo = device_get_ivars(child);
2036         pcicfgregs *cfg = &dinfo->cfg;
2037         struct resource_list_entry *rle;
2038         int actual, error, i, irqs[32];
2039         uint16_t ctrl;
2040
2041         /* Don't let count == 0 get us into trouble. */
2042         if (*count == 0)
2043                 return (EINVAL);
2044
2045         /* If rid 0 is allocated, then fail. */
2046         rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, 0);
2047         if (rle != NULL && rle->res != NULL)
2048                 return (ENXIO);
2049
2050         /* Already have allocated messages? */
2051         if (cfg->msi.msi_alloc != 0 || cfg->msix.msix_alloc != 0)
2052                 return (ENXIO);
2053
2054         /* If MSI is blacklisted for this system, fail. */
2055         if (pci_msi_blacklisted())
2056                 return (ENXIO);
2057
2058         /* MSI capability present? */
2059         if (cfg->msi.msi_location == 0 || !pci_do_msi)
2060                 return (ENODEV);
2061
2062         if (bootverbose)
2063                 device_printf(child,
2064                     "attempting to allocate %d MSI vectors (%d supported)\n",
2065                     *count, cfg->msi.msi_msgnum);
2066
2067         /* Don't ask for more than the device supports. */
2068         actual = min(*count, cfg->msi.msi_msgnum);
2069
2070         /* Don't ask for more than 32 messages. */
2071         actual = min(actual, 32);
2072
2073         /* MSI requires power of 2 number of messages. */
2074         if (!powerof2(actual))
2075                 return (EINVAL);
2076
2077         for (;;) {
2078                 /* Try to allocate N messages. */
2079                 error = PCIB_ALLOC_MSI(device_get_parent(dev), child, actual,
2080                     actual, irqs);
2081                 if (error == 0)
2082                         break;
2083                 if (actual == 1)
2084                         return (error);
2085
2086                 /* Try N / 2. */
2087                 actual >>= 1;
2088         }
2089
2090         /*
2091          * We now have N actual messages mapped onto SYS_RES_IRQ
2092          * resources in the irqs[] array, so add new resources
2093          * starting at rid 1.
2094          */
2095         for (i = 0; i < actual; i++)
2096                 resource_list_add(&dinfo->resources, SYS_RES_IRQ, i + 1,
2097                     irqs[i], irqs[i], 1);
2098
2099         if (bootverbose) {
2100                 if (actual == 1)
2101                         device_printf(child, "using IRQ %d for MSI\n", irqs[0]);
2102                 else {
2103                         int run;
2104
2105                         /*
2106                          * Be fancy and try to print contiguous runs
2107                          * of IRQ values as ranges.  'run' is true if
2108                          * we are in a range.
2109                          */
2110                         device_printf(child, "using IRQs %d", irqs[0]);
2111                         run = 0;
2112                         for (i = 1; i < actual; i++) {
2113
2114                                 /* Still in a run? */
2115                                 if (irqs[i] == irqs[i - 1] + 1) {
2116                                         run = 1;
2117                                         continue;
2118                                 }
2119
2120                                 /* Finish previous range. */
2121                                 if (run) {
2122                                         printf("-%d", irqs[i - 1]);
2123                                         run = 0;
2124                                 }
2125
2126                                 /* Start new range. */
2127                                 printf(",%d", irqs[i]);
2128                         }
2129
2130                         /* Unfinished range? */
2131                         if (run)
2132                                 printf("-%d", irqs[actual - 1]);
2133                         printf(" for MSI\n");
2134                 }
2135         }
2136
2137         /* Update control register with actual count. */
2138         ctrl = cfg->msi.msi_ctrl;
2139         ctrl &= ~PCIM_MSICTRL_MME_MASK;
2140         ctrl |= (ffs(actual) - 1) << 4;
2141         cfg->msi.msi_ctrl = ctrl;
2142         pci_write_config(child, cfg->msi.msi_location + PCIR_MSI_CTRL, ctrl, 2);
2143
2144         /* Update counts of alloc'd messages. */
2145         cfg->msi.msi_alloc = actual;
2146         cfg->msi.msi_handlers = 0;
2147         *count = actual;
2148         return (0);
2149 }
2150
2151 /* Release the MSI messages associated with this device. */
2152 int
2153 pci_release_msi_method(device_t dev, device_t child)
2154 {
2155         struct pci_devinfo *dinfo = device_get_ivars(child);
2156         struct pcicfg_msi *msi = &dinfo->cfg.msi;
2157         struct resource_list_entry *rle;
2158         int error, i, irqs[32];
2159
2160         /* Try MSI-X first. */
2161         error = pci_release_msix(dev, child);
2162         if (error != ENODEV)
2163                 return (error);
2164
2165         /* Do we have any messages to release? */
2166         if (msi->msi_alloc == 0)
2167                 return (ENODEV);
2168         KASSERT(msi->msi_alloc <= 32, ("more than 32 alloc'd messages"));
2169
2170         /* Make sure none of the resources are allocated. */
2171         if (msi->msi_handlers > 0)
2172                 return (EBUSY);
2173         for (i = 0; i < msi->msi_alloc; i++) {
2174                 rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, i + 1);
2175                 KASSERT(rle != NULL, ("missing MSI resource"));
2176                 if (rle->res != NULL)
2177                         return (EBUSY);
2178                 irqs[i] = rle->start;
2179         }
2180
2181         /* Update control register with 0 count. */
2182         KASSERT(!(msi->msi_ctrl & PCIM_MSICTRL_MSI_ENABLE),
2183             ("%s: MSI still enabled", __func__));
2184         msi->msi_ctrl &= ~PCIM_MSICTRL_MME_MASK;
2185         pci_write_config(child, msi->msi_location + PCIR_MSI_CTRL,
2186             msi->msi_ctrl, 2);
2187
2188         /* Release the messages. */
2189         PCIB_RELEASE_MSI(device_get_parent(dev), child, msi->msi_alloc, irqs);
2190         for (i = 0; i < msi->msi_alloc; i++)
2191                 resource_list_delete(&dinfo->resources, SYS_RES_IRQ, i + 1);
2192
2193         /* Update alloc count. */
2194         msi->msi_alloc = 0;
2195         msi->msi_addr = 0;
2196         msi->msi_data = 0;
2197         return (0);
2198 }
2199
2200 /*
2201  * Return the max supported MSI messages this device supports.
2202  * Basically, assuming the MD code can alloc messages, this function
2203  * should return the maximum value that pci_alloc_msi() can return.
2204  * Thus, it is subject to the tunables, etc.
2205  */
2206 int
2207 pci_msi_count_method(device_t dev, device_t child)
2208 {
2209         struct pci_devinfo *dinfo = device_get_ivars(child);
2210         struct pcicfg_msi *msi = &dinfo->cfg.msi;
2211
2212         if (pci_do_msi && msi->msi_location != 0)
2213                 return (msi->msi_msgnum);
2214         return (0);
2215 }
2216
2217 /* free pcicfgregs structure and all depending data structures */
2218
2219 int
2220 pci_freecfg(struct pci_devinfo *dinfo)
2221 {
2222         struct devlist *devlist_head;
2223         struct pci_map *pm, *next;
2224         int i;
2225
2226         devlist_head = &pci_devq;
2227
2228         if (dinfo->cfg.vpd.vpd_reg) {
2229                 free(dinfo->cfg.vpd.vpd_ident, M_DEVBUF);
2230                 for (i = 0; i < dinfo->cfg.vpd.vpd_rocnt; i++)
2231                         free(dinfo->cfg.vpd.vpd_ros[i].value, M_DEVBUF);
2232                 free(dinfo->cfg.vpd.vpd_ros, M_DEVBUF);
2233                 for (i = 0; i < dinfo->cfg.vpd.vpd_wcnt; i++)
2234                         free(dinfo->cfg.vpd.vpd_w[i].value, M_DEVBUF);
2235                 free(dinfo->cfg.vpd.vpd_w, M_DEVBUF);
2236         }
2237         STAILQ_FOREACH_SAFE(pm, &dinfo->cfg.maps, pm_link, next) {
2238                 free(pm, M_DEVBUF);
2239         }
2240         STAILQ_REMOVE(devlist_head, dinfo, pci_devinfo, pci_links);
2241         free(dinfo, M_DEVBUF);
2242
2243         /* increment the generation count */
2244         pci_generation++;
2245
2246         /* we're losing one device */
2247         pci_numdevs--;
2248         return (0);
2249 }
2250
2251 /*
2252  * PCI power manangement
2253  */
2254 int
2255 pci_set_powerstate_method(device_t dev, device_t child, int state)
2256 {
2257         struct pci_devinfo *dinfo = device_get_ivars(child);
2258         pcicfgregs *cfg = &dinfo->cfg;
2259         uint16_t status;
2260         int result, oldstate, highest, delay;
2261
2262         if (cfg->pp.pp_cap == 0)
2263                 return (EOPNOTSUPP);
2264
2265         /*
2266          * Optimize a no state change request away.  While it would be OK to
2267          * write to the hardware in theory, some devices have shown odd
2268          * behavior when going from D3 -> D3.
2269          */
2270         oldstate = pci_get_powerstate(child);
2271         if (oldstate == state)
2272                 return (0);
2273
2274         /*
2275          * The PCI power management specification states that after a state
2276          * transition between PCI power states, system software must
2277          * guarantee a minimal delay before the function accesses the device.
2278          * Compute the worst case delay that we need to guarantee before we
2279          * access the device.  Many devices will be responsive much more
2280          * quickly than this delay, but there are some that don't respond
2281          * instantly to state changes.  Transitions to/from D3 state require
2282          * 10ms, while D2 requires 200us, and D0/1 require none.  The delay
2283          * is done below with DELAY rather than a sleeper function because
2284          * this function can be called from contexts where we cannot sleep.
2285          */
2286         highest = (oldstate > state) ? oldstate : state;
2287         if (highest == PCI_POWERSTATE_D3)
2288             delay = 10000;
2289         else if (highest == PCI_POWERSTATE_D2)
2290             delay = 200;
2291         else
2292             delay = 0;
2293         status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2)
2294             & ~PCIM_PSTAT_DMASK;
2295         result = 0;
2296         switch (state) {
2297         case PCI_POWERSTATE_D0:
2298                 status |= PCIM_PSTAT_D0;
2299                 break;
2300         case PCI_POWERSTATE_D1:
2301                 if ((cfg->pp.pp_cap & PCIM_PCAP_D1SUPP) == 0)
2302                         return (EOPNOTSUPP);
2303                 status |= PCIM_PSTAT_D1;
2304                 break;
2305         case PCI_POWERSTATE_D2:
2306                 if ((cfg->pp.pp_cap & PCIM_PCAP_D2SUPP) == 0)
2307                         return (EOPNOTSUPP);
2308                 status |= PCIM_PSTAT_D2;
2309                 break;
2310         case PCI_POWERSTATE_D3:
2311                 status |= PCIM_PSTAT_D3;
2312                 break;
2313         default:
2314                 return (EINVAL);
2315         }
2316
2317         if (bootverbose)
2318                 pci_printf(cfg, "Transition from D%d to D%d\n", oldstate,
2319                     state);
2320
2321         PCI_WRITE_CONFIG(dev, child, cfg->pp.pp_status, status, 2);
2322         if (delay)
2323                 DELAY(delay);
2324         return (0);
2325 }
2326
2327 int
2328 pci_get_powerstate_method(device_t dev, device_t child)
2329 {
2330         struct pci_devinfo *dinfo = device_get_ivars(child);
2331         pcicfgregs *cfg = &dinfo->cfg;
2332         uint16_t status;
2333         int result;
2334
2335         if (cfg->pp.pp_cap != 0) {
2336                 status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2);
2337                 switch (status & PCIM_PSTAT_DMASK) {
2338                 case PCIM_PSTAT_D0:
2339                         result = PCI_POWERSTATE_D0;
2340                         break;
2341                 case PCIM_PSTAT_D1:
2342                         result = PCI_POWERSTATE_D1;
2343                         break;
2344                 case PCIM_PSTAT_D2:
2345                         result = PCI_POWERSTATE_D2;
2346                         break;
2347                 case PCIM_PSTAT_D3:
2348                         result = PCI_POWERSTATE_D3;
2349                         break;
2350                 default:
2351                         result = PCI_POWERSTATE_UNKNOWN;
2352                         break;
2353                 }
2354         } else {
2355                 /* No support, device is always at D0 */
2356                 result = PCI_POWERSTATE_D0;
2357         }
2358         return (result);
2359 }
2360
2361 /*
2362  * Some convenience functions for PCI device drivers.
2363  */
2364
2365 static __inline void
2366 pci_set_command_bit(device_t dev, device_t child, uint16_t bit)
2367 {
2368         uint16_t        command;
2369
2370         command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
2371         command |= bit;
2372         PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
2373 }
2374
2375 static __inline void
2376 pci_clear_command_bit(device_t dev, device_t child, uint16_t bit)
2377 {
2378         uint16_t        command;
2379
2380         command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
2381         command &= ~bit;
2382         PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
2383 }
2384
2385 int
2386 pci_enable_busmaster_method(device_t dev, device_t child)
2387 {
2388         pci_set_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
2389         return (0);
2390 }
2391
2392 int
2393 pci_disable_busmaster_method(device_t dev, device_t child)
2394 {
2395         pci_clear_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
2396         return (0);
2397 }
2398
2399 int
2400 pci_enable_io_method(device_t dev, device_t child, int space)
2401 {
2402         uint16_t bit;
2403
2404         switch(space) {
2405         case SYS_RES_IOPORT:
2406                 bit = PCIM_CMD_PORTEN;
2407                 break;
2408         case SYS_RES_MEMORY:
2409                 bit = PCIM_CMD_MEMEN;
2410                 break;
2411         default:
2412                 return (EINVAL);
2413         }
2414         pci_set_command_bit(dev, child, bit);
2415         return (0);
2416 }
2417
2418 int
2419 pci_disable_io_method(device_t dev, device_t child, int space)
2420 {
2421         uint16_t bit;
2422
2423         switch(space) {
2424         case SYS_RES_IOPORT:
2425                 bit = PCIM_CMD_PORTEN;
2426                 break;
2427         case SYS_RES_MEMORY:
2428                 bit = PCIM_CMD_MEMEN;
2429                 break;
2430         default:
2431                 return (EINVAL);
2432         }
2433         pci_clear_command_bit(dev, child, bit);
2434         return (0);
2435 }
2436
2437 /*
2438  * New style pci driver.  Parent device is either a pci-host-bridge or a
2439  * pci-pci-bridge.  Both kinds are represented by instances of pcib.
2440  */
2441
2442 void
2443 pci_print_verbose(struct pci_devinfo *dinfo)
2444 {
2445
2446         if (bootverbose) {
2447                 pcicfgregs *cfg = &dinfo->cfg;
2448
2449                 printf("found->\tvendor=0x%04x, dev=0x%04x, revid=0x%02x\n",
2450                     cfg->vendor, cfg->device, cfg->revid);
2451                 printf("\tdomain=%d, bus=%d, slot=%d, func=%d\n",
2452                     cfg->domain, cfg->bus, cfg->slot, cfg->func);
2453                 printf("\tclass=%02x-%02x-%02x, hdrtype=0x%02x, mfdev=%d\n",
2454                     cfg->baseclass, cfg->subclass, cfg->progif, cfg->hdrtype,
2455                     cfg->mfdev);
2456                 printf("\tcmdreg=0x%04x, statreg=0x%04x, cachelnsz=%d (dwords)\n",
2457                     cfg->cmdreg, cfg->statreg, cfg->cachelnsz);
2458                 printf("\tlattimer=0x%02x (%d ns), mingnt=0x%02x (%d ns), maxlat=0x%02x (%d ns)\n",
2459                     cfg->lattimer, cfg->lattimer * 30, cfg->mingnt,
2460                     cfg->mingnt * 250, cfg->maxlat, cfg->maxlat * 250);
2461                 if (cfg->intpin > 0)
2462                         printf("\tintpin=%c, irq=%d\n",
2463                             cfg->intpin +'a' -1, cfg->intline);
2464                 if (cfg->pp.pp_cap) {
2465                         uint16_t status;
2466
2467                         status = pci_read_config(cfg->dev, cfg->pp.pp_status, 2);
2468                         printf("\tpowerspec %d  supports D0%s%s D3  current D%d\n",
2469                             cfg->pp.pp_cap & PCIM_PCAP_SPEC,
2470                             cfg->pp.pp_cap & PCIM_PCAP_D1SUPP ? " D1" : "",
2471                             cfg->pp.pp_cap & PCIM_PCAP_D2SUPP ? " D2" : "",
2472                             status & PCIM_PSTAT_DMASK);
2473                 }
2474                 if (cfg->msi.msi_location) {
2475                         int ctrl;
2476
2477                         ctrl = cfg->msi.msi_ctrl;
2478                         printf("\tMSI supports %d message%s%s%s\n",
2479                             cfg->msi.msi_msgnum,
2480                             (cfg->msi.msi_msgnum == 1) ? "" : "s",
2481                             (ctrl & PCIM_MSICTRL_64BIT) ? ", 64 bit" : "",
2482                             (ctrl & PCIM_MSICTRL_VECTOR) ? ", vector masks":"");
2483                 }
2484                 if (cfg->msix.msix_location) {
2485                         printf("\tMSI-X supports %d message%s ",
2486                             cfg->msix.msix_msgnum,
2487                             (cfg->msix.msix_msgnum == 1) ? "" : "s");
2488                         if (cfg->msix.msix_table_bar == cfg->msix.msix_pba_bar)
2489                                 printf("in map 0x%x\n",
2490                                     cfg->msix.msix_table_bar);
2491                         else
2492                                 printf("in maps 0x%x and 0x%x\n",
2493                                     cfg->msix.msix_table_bar,
2494                                     cfg->msix.msix_pba_bar);
2495                 }
2496         }
2497 }
2498
2499 static int
2500 pci_porten(device_t dev)
2501 {
2502         return (pci_read_config(dev, PCIR_COMMAND, 2) & PCIM_CMD_PORTEN) != 0;
2503 }
2504
2505 static int
2506 pci_memen(device_t dev)
2507 {
2508         return (pci_read_config(dev, PCIR_COMMAND, 2) & PCIM_CMD_MEMEN) != 0;
2509 }
2510
2511 static void
2512 pci_read_bar(device_t dev, int reg, pci_addr_t *mapp, pci_addr_t *testvalp)
2513 {
2514         struct pci_devinfo *dinfo;
2515         pci_addr_t map, testval;
2516         int ln2range;
2517         uint16_t cmd;
2518
2519         /*
2520          * The device ROM BAR is special.  It is always a 32-bit
2521          * memory BAR.  Bit 0 is special and should not be set when
2522          * sizing the BAR.
2523          */
2524         dinfo = device_get_ivars(dev);
2525         if (PCIR_IS_BIOS(&dinfo->cfg, reg)) {
2526                 map = pci_read_config(dev, reg, 4);
2527                 pci_write_config(dev, reg, 0xfffffffe, 4);
2528                 testval = pci_read_config(dev, reg, 4);
2529                 pci_write_config(dev, reg, map, 4);
2530                 *mapp = map;
2531                 *testvalp = testval;
2532                 return;
2533         }
2534
2535         map = pci_read_config(dev, reg, 4);
2536         ln2range = pci_maprange(map);
2537         if (ln2range == 64)
2538                 map |= (pci_addr_t)pci_read_config(dev, reg + 4, 4) << 32;
2539
2540         /*
2541          * Disable decoding via the command register before
2542          * determining the BAR's length since we will be placing it in
2543          * a weird state.
2544          */
2545         cmd = pci_read_config(dev, PCIR_COMMAND, 2);
2546         pci_write_config(dev, PCIR_COMMAND,
2547             cmd & ~(PCI_BAR_MEM(map) ? PCIM_CMD_MEMEN : PCIM_CMD_PORTEN), 2);
2548
2549         /*
2550          * Determine the BAR's length by writing all 1's.  The bottom
2551          * log_2(size) bits of the BAR will stick as 0 when we read
2552          * the value back.
2553          */
2554         pci_write_config(dev, reg, 0xffffffff, 4);
2555         testval = pci_read_config(dev, reg, 4);
2556         if (ln2range == 64) {
2557                 pci_write_config(dev, reg + 4, 0xffffffff, 4);
2558                 testval |= (pci_addr_t)pci_read_config(dev, reg + 4, 4) << 32;
2559         }
2560
2561         /*
2562          * Restore the original value of the BAR.  We may have reprogrammed
2563          * the BAR of the low-level console device and when booting verbose,
2564          * we need the console device addressable.
2565          */
2566         pci_write_config(dev, reg, map, 4);
2567         if (ln2range == 64)
2568                 pci_write_config(dev, reg + 4, map >> 32, 4);
2569         pci_write_config(dev, PCIR_COMMAND, cmd, 2);
2570
2571         *mapp = map;
2572         *testvalp = testval;
2573 }
2574
2575 static void
2576 pci_write_bar(device_t dev, struct pci_map *pm, pci_addr_t base)
2577 {
2578         struct pci_devinfo *dinfo;
2579         int ln2range;
2580
2581         /* The device ROM BAR is always a 32-bit memory BAR. */
2582         dinfo = device_get_ivars(dev);
2583         if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg))
2584                 ln2range = 32;
2585         else
2586                 ln2range = pci_maprange(pm->pm_value);
2587         pci_write_config(dev, pm->pm_reg, base, 4);
2588         if (ln2range == 64)
2589                 pci_write_config(dev, pm->pm_reg + 4, base >> 32, 4);
2590         pm->pm_value = pci_read_config(dev, pm->pm_reg, 4);
2591         if (ln2range == 64)
2592                 pm->pm_value |= (pci_addr_t)pci_read_config(dev,
2593                     pm->pm_reg + 4, 4) << 32;
2594 }
2595
2596 struct pci_map *
2597 pci_find_bar(device_t dev, int reg)
2598 {
2599         struct pci_devinfo *dinfo;
2600         struct pci_map *pm;
2601
2602         dinfo = device_get_ivars(dev);
2603         STAILQ_FOREACH(pm, &dinfo->cfg.maps, pm_link) {
2604                 if (pm->pm_reg == reg)
2605                         return (pm);
2606         }
2607         return (NULL);
2608 }
2609
2610 int
2611 pci_bar_enabled(device_t dev, struct pci_map *pm)
2612 {
2613         struct pci_devinfo *dinfo;
2614         uint16_t cmd;
2615
2616         dinfo = device_get_ivars(dev);
2617         if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg) &&
2618             !(pm->pm_value & PCIM_BIOS_ENABLE))
2619                 return (0);
2620         cmd = pci_read_config(dev, PCIR_COMMAND, 2);
2621         if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg) || PCI_BAR_MEM(pm->pm_value))
2622                 return ((cmd & PCIM_CMD_MEMEN) != 0);
2623         else
2624                 return ((cmd & PCIM_CMD_PORTEN) != 0);
2625 }
2626
2627 static struct pci_map *
2628 pci_add_bar(device_t dev, int reg, pci_addr_t value, pci_addr_t size)
2629 {
2630         struct pci_devinfo *dinfo;
2631         struct pci_map *pm, *prev;
2632
2633         dinfo = device_get_ivars(dev);
2634         pm = malloc(sizeof(*pm), M_DEVBUF, M_WAITOK | M_ZERO);
2635         pm->pm_reg = reg;
2636         pm->pm_value = value;
2637         pm->pm_size = size;
2638         STAILQ_FOREACH(prev, &dinfo->cfg.maps, pm_link) {
2639                 KASSERT(prev->pm_reg != pm->pm_reg, ("duplicate map %02x",
2640                     reg));
2641                 if (STAILQ_NEXT(prev, pm_link) == NULL ||
2642                     STAILQ_NEXT(prev, pm_link)->pm_reg > pm->pm_reg)
2643                         break;
2644         }
2645         if (prev != NULL)
2646                 STAILQ_INSERT_AFTER(&dinfo->cfg.maps, prev, pm, pm_link);
2647         else
2648                 STAILQ_INSERT_TAIL(&dinfo->cfg.maps, pm, pm_link);
2649         return (pm);
2650 }
2651
2652 static void
2653 pci_restore_bars(device_t dev)
2654 {
2655         struct pci_devinfo *dinfo;
2656         struct pci_map *pm;
2657         int ln2range;
2658
2659         dinfo = device_get_ivars(dev);
2660         STAILQ_FOREACH(pm, &dinfo->cfg.maps, pm_link) {
2661                 if (PCIR_IS_BIOS(&dinfo->cfg, pm->pm_reg))
2662                         ln2range = 32;
2663                 else
2664                         ln2range = pci_maprange(pm->pm_value);
2665                 pci_write_config(dev, pm->pm_reg, pm->pm_value, 4);
2666                 if (ln2range == 64)
2667                         pci_write_config(dev, pm->pm_reg + 4,
2668                             pm->pm_value >> 32, 4);
2669         }
2670 }
2671
2672 /*
2673  * Add a resource based on a pci map register. Return 1 if the map
2674  * register is a 32bit map register or 2 if it is a 64bit register.
2675  */
2676 static int
2677 pci_add_map(device_t bus, device_t dev, int reg, struct resource_list *rl,
2678     int force, int prefetch)
2679 {
2680         struct pci_map *pm;
2681         pci_addr_t base, map, testval;
2682         pci_addr_t start, end, count;
2683         int barlen, basezero, flags, maprange, mapsize, type;
2684         uint16_t cmd;
2685         struct resource *res;
2686
2687         /*
2688          * The BAR may already exist if the device is a CardBus card
2689          * whose CIS is stored in this BAR.
2690          */
2691         pm = pci_find_bar(dev, reg);
2692         if (pm != NULL) {
2693                 maprange = pci_maprange(pm->pm_value);
2694                 barlen = maprange == 64 ? 2 : 1;
2695                 return (barlen);
2696         }
2697
2698         pci_read_bar(dev, reg, &map, &testval);
2699         if (PCI_BAR_MEM(map)) {
2700                 type = SYS_RES_MEMORY;
2701                 if (map & PCIM_BAR_MEM_PREFETCH)
2702                         prefetch = 1;
2703         } else
2704                 type = SYS_RES_IOPORT;
2705         mapsize = pci_mapsize(testval);
2706         base = pci_mapbase(map);
2707 #ifdef __PCI_BAR_ZERO_VALID
2708         basezero = 0;
2709 #else
2710         basezero = base == 0;
2711 #endif
2712         maprange = pci_maprange(map);
2713         barlen = maprange == 64 ? 2 : 1;
2714
2715         /*
2716          * For I/O registers, if bottom bit is set, and the next bit up
2717          * isn't clear, we know we have a BAR that doesn't conform to the
2718          * spec, so ignore it.  Also, sanity check the size of the data
2719          * areas to the type of memory involved.  Memory must be at least
2720          * 16 bytes in size, while I/O ranges must be at least 4.
2721          */
2722         if (PCI_BAR_IO(testval) && (testval & PCIM_BAR_IO_RESERVED) != 0)
2723                 return (barlen);
2724         if ((type == SYS_RES_MEMORY && mapsize < 4) ||
2725             (type == SYS_RES_IOPORT && mapsize < 2))
2726                 return (barlen);
2727
2728         /* Save a record of this BAR. */
2729         pm = pci_add_bar(dev, reg, map, mapsize);
2730         if (bootverbose) {
2731                 printf("\tmap[%02x]: type %s, range %2d, base %#jx, size %2d",
2732                     reg, pci_maptype(map), maprange, (uintmax_t)base, mapsize);
2733                 if (type == SYS_RES_IOPORT && !pci_porten(dev))
2734                         printf(", port disabled\n");
2735                 else if (type == SYS_RES_MEMORY && !pci_memen(dev))
2736                         printf(", memory disabled\n");
2737                 else
2738                         printf(", enabled\n");
2739         }
2740
2741         /*
2742          * If base is 0, then we have problems if this architecture does
2743          * not allow that.  It is best to ignore such entries for the
2744          * moment.  These will be allocated later if the driver specifically
2745          * requests them.  However, some removable busses look better when
2746          * all resources are allocated, so allow '0' to be overriden.
2747          *
2748          * Similarly treat maps whose values is the same as the test value
2749          * read back.  These maps have had all f's written to them by the
2750          * BIOS in an attempt to disable the resources.
2751          */
2752         if (!force && (basezero || map == testval))
2753                 return (barlen);
2754         if ((u_long)base != base) {
2755                 device_printf(bus,
2756                     "pci%d:%d:%d:%d bar %#x too many address bits",
2757                     pci_get_domain(dev), pci_get_bus(dev), pci_get_slot(dev),
2758                     pci_get_function(dev), reg);
2759                 return (barlen);
2760         }
2761
2762         /*
2763          * This code theoretically does the right thing, but has
2764          * undesirable side effects in some cases where peripherals
2765          * respond oddly to having these bits enabled.  Let the user
2766          * be able to turn them off (since pci_enable_io_modes is 1 by
2767          * default).
2768          */
2769         if (pci_enable_io_modes) {
2770                 /* Turn on resources that have been left off by a lazy BIOS */
2771                 if (type == SYS_RES_IOPORT && !pci_porten(dev)) {
2772                         cmd = pci_read_config(dev, PCIR_COMMAND, 2);
2773                         cmd |= PCIM_CMD_PORTEN;
2774                         pci_write_config(dev, PCIR_COMMAND, cmd, 2);
2775                 }
2776                 if (type == SYS_RES_MEMORY && !pci_memen(dev)) {
2777                         cmd = pci_read_config(dev, PCIR_COMMAND, 2);
2778                         cmd |= PCIM_CMD_MEMEN;
2779                         pci_write_config(dev, PCIR_COMMAND, cmd, 2);
2780                 }
2781         } else {
2782                 if (type == SYS_RES_IOPORT && !pci_porten(dev))
2783                         return (barlen);
2784                 if (type == SYS_RES_MEMORY && !pci_memen(dev))
2785                         return (barlen);
2786         }
2787
2788         count = (pci_addr_t)1 << mapsize;
2789         flags = RF_ALIGNMENT_LOG2(mapsize);
2790         if (prefetch)
2791                 flags |= RF_PREFETCHABLE;
2792         if (basezero || base == pci_mapbase(testval) || pci_clear_bars) {
2793                 start = 0;      /* Let the parent decide. */
2794                 end = ~0ul;
2795         } else {
2796                 start = base;
2797                 end = base + count - 1;
2798         }
2799         resource_list_add(rl, type, reg, start, end, count);
2800
2801         /*
2802          * Try to allocate the resource for this BAR from our parent
2803          * so that this resource range is already reserved.  The
2804          * driver for this device will later inherit this resource in
2805          * pci_alloc_resource().
2806          */
2807         res = resource_list_reserve(rl, bus, dev, type, &reg, start, end, count,
2808             flags);
2809         if (pci_do_realloc_bars && res == NULL && (start != 0 || end != ~0ul)) {
2810                 /*
2811                  * If the allocation fails, try to allocate a resource for
2812                  * this BAR using any available range.  The firmware felt
2813                  * it was important enough to assign a resource, so don't
2814                  * disable decoding if we can help it.
2815                  */
2816                 resource_list_delete(rl, type, reg);
2817                 resource_list_add(rl, type, reg, 0, ~0ul, count);
2818                 res = resource_list_reserve(rl, bus, dev, type, &reg, 0, ~0ul,
2819                     count, flags);
2820         }
2821         if (res == NULL) {
2822                 /*
2823                  * If the allocation fails, delete the resource list entry
2824                  * and disable decoding for this device.
2825                  *
2826                  * If the driver requests this resource in the future,
2827                  * pci_reserve_map() will try to allocate a fresh
2828                  * resource range.
2829                  */
2830                 resource_list_delete(rl, type, reg);
2831                 pci_disable_io(dev, type);
2832                 if (bootverbose)
2833                         device_printf(bus,
2834                             "pci%d:%d:%d:%d bar %#x failed to allocate\n",
2835                             pci_get_domain(dev), pci_get_bus(dev),
2836                             pci_get_slot(dev), pci_get_function(dev), reg);
2837         } else {
2838                 start = rman_get_start(res);
2839                 pci_write_bar(dev, pm, start);
2840         }
2841         return (barlen);
2842 }
2843
2844 /*
2845  * For ATA devices we need to decide early what addressing mode to use.
2846  * Legacy demands that the primary and secondary ATA ports sits on the
2847  * same addresses that old ISA hardware did. This dictates that we use
2848  * those addresses and ignore the BAR's if we cannot set PCI native
2849  * addressing mode.
2850  */
2851 static void
2852 pci_ata_maps(device_t bus, device_t dev, struct resource_list *rl, int force,
2853     uint32_t prefetchmask)
2854 {
2855         struct resource *r;
2856         int rid, type, progif;
2857 #if 0
2858         /* if this device supports PCI native addressing use it */
2859         progif = pci_read_config(dev, PCIR_PROGIF, 1);
2860         if ((progif & 0x8a) == 0x8a) {
2861                 if (pci_mapbase(pci_read_config(dev, PCIR_BAR(0), 4)) &&
2862                     pci_mapbase(pci_read_config(dev, PCIR_BAR(2), 4))) {
2863                         printf("Trying ATA native PCI addressing mode\n");
2864                         pci_write_config(dev, PCIR_PROGIF, progif | 0x05, 1);
2865                 }
2866         }
2867 #endif
2868         progif = pci_read_config(dev, PCIR_PROGIF, 1);
2869         type = SYS_RES_IOPORT;
2870         if (progif & PCIP_STORAGE_IDE_MODEPRIM) {
2871                 pci_add_map(bus, dev, PCIR_BAR(0), rl, force,
2872                     prefetchmask & (1 << 0));
2873                 pci_add_map(bus, dev, PCIR_BAR(1), rl, force,
2874                     prefetchmask & (1 << 1));
2875         } else {
2876                 rid = PCIR_BAR(0);
2877                 resource_list_add(rl, type, rid, 0x1f0, 0x1f7, 8);
2878                 r = resource_list_reserve(rl, bus, dev, type, &rid, 0x1f0,
2879                     0x1f7, 8, 0);
2880                 rid = PCIR_BAR(1);
2881                 resource_list_add(rl, type, rid, 0x3f6, 0x3f6, 1);
2882                 r = resource_list_reserve(rl, bus, dev, type, &rid, 0x3f6,
2883                     0x3f6, 1, 0);
2884         }
2885         if (progif & PCIP_STORAGE_IDE_MODESEC) {
2886                 pci_add_map(bus, dev, PCIR_BAR(2), rl, force,
2887                     prefetchmask & (1 << 2));
2888                 pci_add_map(bus, dev, PCIR_BAR(3), rl, force,
2889                     prefetchmask & (1 << 3));
2890         } else {
2891                 rid = PCIR_BAR(2);
2892                 resource_list_add(rl, type, rid, 0x170, 0x177, 8);
2893                 r = resource_list_reserve(rl, bus, dev, type, &rid, 0x170,
2894                     0x177, 8, 0);
2895                 rid = PCIR_BAR(3);
2896                 resource_list_add(rl, type, rid, 0x376, 0x376, 1);
2897                 r = resource_list_reserve(rl, bus, dev, type, &rid, 0x376,
2898                     0x376, 1, 0);
2899         }
2900         pci_add_map(bus, dev, PCIR_BAR(4), rl, force,
2901             prefetchmask & (1 << 4));
2902         pci_add_map(bus, dev, PCIR_BAR(5), rl, force,
2903             prefetchmask & (1 << 5));
2904 }
2905
2906 static void
2907 pci_assign_interrupt(device_t bus, device_t dev, int force_route)
2908 {
2909         struct pci_devinfo *dinfo = device_get_ivars(dev);
2910         pcicfgregs *cfg = &dinfo->cfg;
2911         char tunable_name[64];
2912         int irq;
2913
2914         /* Has to have an intpin to have an interrupt. */
2915         if (cfg->intpin == 0)
2916                 return;
2917
2918         /* Let the user override the IRQ with a tunable. */
2919         irq = PCI_INVALID_IRQ;
2920         snprintf(tunable_name, sizeof(tunable_name),
2921             "hw.pci%d.%d.%d.INT%c.irq",
2922             cfg->domain, cfg->bus, cfg->slot, cfg->intpin + 'A' - 1);
2923         if (TUNABLE_INT_FETCH(tunable_name, &irq) && (irq >= 255 || irq <= 0))
2924                 irq = PCI_INVALID_IRQ;
2925
2926         /*
2927          * If we didn't get an IRQ via the tunable, then we either use the
2928          * IRQ value in the intline register or we ask the bus to route an
2929          * interrupt for us.  If force_route is true, then we only use the
2930          * value in the intline register if the bus was unable to assign an
2931          * IRQ.
2932          */
2933         if (!PCI_INTERRUPT_VALID(irq)) {
2934                 if (!PCI_INTERRUPT_VALID(cfg->intline) || force_route)
2935                         irq = PCI_ASSIGN_INTERRUPT(bus, dev);
2936                 if (!PCI_INTERRUPT_VALID(irq))
2937                         irq = cfg->intline;
2938         }
2939
2940         /* If after all that we don't have an IRQ, just bail. */
2941         if (!PCI_INTERRUPT_VALID(irq))
2942                 return;
2943
2944         /* Update the config register if it changed. */
2945         if (irq != cfg->intline) {
2946                 cfg->intline = irq;
2947                 pci_write_config(dev, PCIR_INTLINE, irq, 1);
2948         }
2949
2950         /* Add this IRQ as rid 0 interrupt resource. */
2951         resource_list_add(&dinfo->resources, SYS_RES_IRQ, 0, irq, irq, 1);
2952 }
2953
2954 /* Perform early OHCI takeover from SMM. */
2955 static void
2956 ohci_early_takeover(device_t self)
2957 {
2958         struct resource *res;
2959         uint32_t ctl;
2960         int rid;
2961         int i;
2962
2963         rid = PCIR_BAR(0);
2964         res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
2965         if (res == NULL)
2966                 return;
2967
2968         ctl = bus_read_4(res, OHCI_CONTROL);
2969         if (ctl & OHCI_IR) {
2970                 if (bootverbose)
2971                         printf("ohci early: "
2972                             "SMM active, request owner change\n");
2973                 bus_write_4(res, OHCI_COMMAND_STATUS, OHCI_OCR);
2974                 for (i = 0; (i < 100) && (ctl & OHCI_IR); i++) {
2975                         DELAY(1000);
2976                         ctl = bus_read_4(res, OHCI_CONTROL);
2977                 }
2978                 if (ctl & OHCI_IR) {
2979                         if (bootverbose)
2980                                 printf("ohci early: "
2981                                     "SMM does not respond, resetting\n");
2982                         bus_write_4(res, OHCI_CONTROL, OHCI_HCFS_RESET);
2983                 }
2984                 /* Disable interrupts */
2985                 bus_write_4(res, OHCI_INTERRUPT_DISABLE, OHCI_ALL_INTRS);
2986         }
2987
2988         bus_release_resource(self, SYS_RES_MEMORY, rid, res);
2989 }
2990
2991 /* Perform early UHCI takeover from SMM. */
2992 static void
2993 uhci_early_takeover(device_t self)
2994 {
2995         struct resource *res;
2996         int rid;
2997
2998         /*
2999          * Set the PIRQD enable bit and switch off all the others. We don't
3000          * want legacy support to interfere with us XXX Does this also mean
3001          * that the BIOS won't touch the keyboard anymore if it is connected
3002          * to the ports of the root hub?
3003          */
3004         pci_write_config(self, PCI_LEGSUP, PCI_LEGSUP_USBPIRQDEN, 2);
3005
3006         /* Disable interrupts */
3007         rid = PCI_UHCI_BASE_REG;
3008         res = bus_alloc_resource_any(self, SYS_RES_IOPORT, &rid, RF_ACTIVE);
3009         if (res != NULL) {
3010                 bus_write_2(res, UHCI_INTR, 0);
3011                 bus_release_resource(self, SYS_RES_IOPORT, rid, res);
3012         }
3013 }
3014
3015 /* Perform early EHCI takeover from SMM. */
3016 static void
3017 ehci_early_takeover(device_t self)
3018 {
3019         struct resource *res;
3020         uint32_t cparams;
3021         uint32_t eec;
3022         uint8_t eecp;
3023         uint8_t bios_sem;
3024         uint8_t offs;
3025         int rid;
3026         int i;
3027
3028         rid = PCIR_BAR(0);
3029         res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3030         if (res == NULL)
3031                 return;
3032
3033         cparams = bus_read_4(res, EHCI_HCCPARAMS);
3034
3035         /* Synchronise with the BIOS if it owns the controller. */
3036         for (eecp = EHCI_HCC_EECP(cparams); eecp != 0;
3037             eecp = EHCI_EECP_NEXT(eec)) {
3038                 eec = pci_read_config(self, eecp, 4);
3039                 if (EHCI_EECP_ID(eec) != EHCI_EC_LEGSUP) {
3040                         continue;
3041                 }
3042                 bios_sem = pci_read_config(self, eecp +
3043                     EHCI_LEGSUP_BIOS_SEM, 1);
3044                 if (bios_sem == 0) {
3045                         continue;
3046                 }
3047                 if (bootverbose)
3048                         printf("ehci early: "
3049                             "SMM active, request owner change\n");
3050
3051                 pci_write_config(self, eecp + EHCI_LEGSUP_OS_SEM, 1, 1);
3052
3053                 for (i = 0; (i < 100) && (bios_sem != 0); i++) {
3054                         DELAY(1000);
3055                         bios_sem = pci_read_config(self, eecp +
3056                             EHCI_LEGSUP_BIOS_SEM, 1);
3057                 }
3058
3059                 if (bios_sem != 0) {
3060                         if (bootverbose)
3061                                 printf("ehci early: "
3062                                     "SMM does not respond\n");
3063                 }
3064                 /* Disable interrupts */
3065                 offs = EHCI_CAPLENGTH(bus_read_4(res, EHCI_CAPLEN_HCIVERSION));
3066                 bus_write_4(res, offs + EHCI_USBINTR, 0);
3067         }
3068         bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3069 }
3070
3071 /* Perform early XHCI takeover from SMM. */
3072 static void
3073 xhci_early_takeover(device_t self)
3074 {
3075         struct resource *res;
3076         uint32_t cparams;
3077         uint32_t eec;
3078         uint8_t eecp;
3079         uint8_t bios_sem;
3080         uint8_t offs;
3081         int rid;
3082         int i;
3083
3084         rid = PCIR_BAR(0);
3085         res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, RF_ACTIVE);
3086         if (res == NULL)
3087                 return;
3088
3089         cparams = bus_read_4(res, XHCI_HCSPARAMS0);
3090
3091         eec = -1;
3092
3093         /* Synchronise with the BIOS if it owns the controller. */
3094         for (eecp = XHCI_HCS0_XECP(cparams) << 2; eecp != 0 && XHCI_XECP_NEXT(eec);
3095             eecp += XHCI_XECP_NEXT(eec) << 2) {
3096                 eec = bus_read_4(res, eecp);
3097
3098                 if (XHCI_XECP_ID(eec) != XHCI_ID_USB_LEGACY)
3099                         continue;
3100
3101                 bios_sem = bus_read_1(res, eecp + XHCI_XECP_BIOS_SEM);
3102                 if (bios_sem == 0)
3103                         continue;
3104
3105                 if (bootverbose)
3106                         printf("xhci early: "
3107                             "SMM active, request owner change\n");
3108
3109                 bus_write_1(res, eecp + XHCI_XECP_OS_SEM, 1);
3110
3111                 /* wait a maximum of 5 second */
3112
3113                 for (i = 0; (i < 5000) && (bios_sem != 0); i++) {
3114                         DELAY(1000);
3115                         bios_sem = bus_read_1(res, eecp +
3116                             XHCI_XECP_BIOS_SEM);
3117                 }
3118
3119                 if (bios_sem != 0) {
3120                         if (bootverbose)
3121                                 printf("xhci early: "
3122                                     "SMM does not respond\n");
3123                 }
3124
3125                 /* Disable interrupts */
3126                 offs = bus_read_1(res, XHCI_CAPLENGTH);
3127                 bus_write_4(res, offs + XHCI_USBCMD, 0);
3128                 bus_read_4(res, offs + XHCI_USBSTS);
3129         }
3130         bus_release_resource(self, SYS_RES_MEMORY, rid, res);
3131 }
3132
3133 void
3134 pci_add_resources(device_t bus, device_t dev, int force, uint32_t prefetchmask)
3135 {
3136         struct pci_devinfo *dinfo;
3137         pcicfgregs *cfg;
3138         struct resource_list *rl;
3139         const struct pci_quirk *q;
3140         uint32_t devid;
3141         int i;
3142
3143         dinfo = device_get_ivars(dev);
3144         cfg = &dinfo->cfg;
3145         rl = &dinfo->resources;
3146         devid = (cfg->device << 16) | cfg->vendor;
3147
3148         /* ATA devices needs special map treatment */
3149         if ((pci_get_class(dev) == PCIC_STORAGE) &&
3150             (pci_get_subclass(dev) == PCIS_STORAGE_IDE) &&
3151             ((pci_get_progif(dev) & PCIP_STORAGE_IDE_MASTERDEV) ||
3152              (!pci_read_config(dev, PCIR_BAR(0), 4) &&
3153               !pci_read_config(dev, PCIR_BAR(2), 4))) )
3154                 pci_ata_maps(bus, dev, rl, force, prefetchmask);
3155         else
3156                 for (i = 0; i < cfg->nummaps;) {
3157                         /*
3158                          * Skip quirked resources.
3159                          */
3160                         for (q = &pci_quirks[0]; q->devid != 0; q++)
3161                                 if (q->devid == devid &&
3162                                     q->type == PCI_QUIRK_UNMAP_REG &&
3163                                     q->arg1 == PCIR_BAR(i))
3164                                         break;
3165                         if (q->devid != 0) {
3166                                 i++;
3167                                 continue;
3168                         }
3169                         i += pci_add_map(bus, dev, PCIR_BAR(i), rl, force,
3170                             prefetchmask & (1 << i));
3171                 }
3172
3173         /*
3174          * Add additional, quirked resources.
3175          */
3176         for (q = &pci_quirks[0]; q->devid != 0; q++)
3177                 if (q->devid == devid && q->type == PCI_QUIRK_MAP_REG)
3178                         pci_add_map(bus, dev, q->arg1, rl, force, 0);
3179
3180         if (cfg->intpin > 0 && PCI_INTERRUPT_VALID(cfg->intline)) {
3181 #ifdef __PCI_REROUTE_INTERRUPT
3182                 /*
3183                  * Try to re-route interrupts. Sometimes the BIOS or
3184                  * firmware may leave bogus values in these registers.
3185                  * If the re-route fails, then just stick with what we
3186                  * have.
3187                  */
3188                 pci_assign_interrupt(bus, dev, 1);
3189 #else
3190                 pci_assign_interrupt(bus, dev, 0);
3191 #endif
3192         }
3193
3194         if (pci_usb_takeover && pci_get_class(dev) == PCIC_SERIALBUS &&
3195             pci_get_subclass(dev) == PCIS_SERIALBUS_USB) {
3196                 if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_XHCI)
3197                         xhci_early_takeover(dev);
3198                 else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_EHCI)
3199                         ehci_early_takeover(dev);
3200                 else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_OHCI)
3201                         ohci_early_takeover(dev);
3202                 else if (pci_get_progif(dev) == PCIP_SERIALBUS_USB_UHCI)
3203                         uhci_early_takeover(dev);
3204         }
3205 }
3206
3207 void
3208 pci_add_children(device_t dev, int domain, int busno, size_t dinfo_size)
3209 {
3210 #define REG(n, w)       PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
3211         device_t pcib = device_get_parent(dev);
3212         struct pci_devinfo *dinfo;
3213         int maxslots;
3214         int s, f, pcifunchigh;
3215         uint8_t hdrtype;
3216
3217         KASSERT(dinfo_size >= sizeof(struct pci_devinfo),
3218             ("dinfo_size too small"));
3219         maxslots = PCIB_MAXSLOTS(pcib);
3220         for (s = 0; s <= maxslots; s++) {
3221                 pcifunchigh = 0;
3222                 f = 0;
3223                 DELAY(1);
3224                 hdrtype = REG(PCIR_HDRTYPE, 1);
3225                 if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
3226                         continue;
3227                 if (hdrtype & PCIM_MFDEV)
3228                         pcifunchigh = PCI_FUNCMAX;
3229                 for (f = 0; f <= pcifunchigh; f++) {
3230                         dinfo = pci_read_device(pcib, domain, busno, s, f,
3231                             dinfo_size);
3232                         if (dinfo != NULL) {
3233                                 pci_add_child(dev, dinfo);
3234                         }
3235                 }
3236         }
3237 #undef REG
3238 }
3239
3240 void
3241 pci_add_child(device_t bus, struct pci_devinfo *dinfo)
3242 {
3243         dinfo->cfg.dev = device_add_child(bus, NULL, -1);
3244         device_set_ivars(dinfo->cfg.dev, dinfo);
3245         resource_list_init(&dinfo->resources);
3246         pci_cfg_save(dinfo->cfg.dev, dinfo, 0);
3247         pci_cfg_restore(dinfo->cfg.dev, dinfo);
3248         pci_print_verbose(dinfo);
3249         pci_add_resources(bus, dinfo->cfg.dev, 0, 0);
3250 }
3251
3252 static int
3253 pci_probe(device_t dev)
3254 {
3255
3256         device_set_desc(dev, "PCI bus");
3257
3258         /* Allow other subclasses to override this driver. */
3259         return (BUS_PROBE_GENERIC);
3260 }
3261
3262 int
3263 pci_attach_common(device_t dev)
3264 {
3265         struct pci_softc *sc;
3266         int busno, domain;
3267 #ifdef PCI_DMA_BOUNDARY
3268         int error, tag_valid;
3269 #endif
3270
3271         sc = device_get_softc(dev);
3272         domain = pcib_get_domain(dev);
3273         busno = pcib_get_bus(dev);
3274         if (bootverbose)
3275                 device_printf(dev, "domain=%d, physical bus=%d\n",
3276                     domain, busno);
3277 #ifdef PCI_DMA_BOUNDARY
3278         tag_valid = 0;
3279         if (device_get_devclass(device_get_parent(device_get_parent(dev))) !=
3280             devclass_find("pci")) {
3281                 error = bus_dma_tag_create(bus_get_dma_tag(dev), 1,
3282                     PCI_DMA_BOUNDARY, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
3283                     NULL, NULL, BUS_SPACE_MAXSIZE, BUS_SPACE_UNRESTRICTED,
3284                     BUS_SPACE_MAXSIZE, 0, NULL, NULL, &sc->sc_dma_tag);
3285                 if (error)
3286                         device_printf(dev, "Failed to create DMA tag: %d\n",
3287                             error);
3288                 else
3289                         tag_valid = 1;
3290         }
3291         if (!tag_valid)
3292 #endif
3293                 sc->sc_dma_tag = bus_get_dma_tag(dev);
3294         return (0);
3295 }
3296
3297 static int
3298 pci_attach(device_t dev)
3299 {
3300         int busno, domain, error;
3301
3302         error = pci_attach_common(dev);
3303         if (error)
3304                 return (error);
3305
3306         /*
3307          * Since there can be multiple independantly numbered PCI
3308          * busses on systems with multiple PCI domains, we can't use
3309          * the unit number to decide which bus we are probing. We ask
3310          * the parent pcib what our domain and bus numbers are.
3311          */
3312         domain = pcib_get_domain(dev);
3313         busno = pcib_get_bus(dev);
3314         pci_add_children(dev, domain, busno, sizeof(struct pci_devinfo));
3315         return (bus_generic_attach(dev));
3316 }
3317
3318 static void
3319 pci_set_power_children(device_t dev, device_t *devlist, int numdevs,
3320     int state)
3321 {
3322         device_t child, pcib;
3323         struct pci_devinfo *dinfo;
3324         int dstate, i;
3325
3326         /*
3327          * Set the device to the given state.  If the firmware suggests
3328          * a different power state, use it instead.  If power management
3329          * is not present, the firmware is responsible for managing
3330          * device power.  Skip children who aren't attached since they
3331          * are handled separately.
3332          */
3333         pcib = device_get_parent(dev);
3334         for (i = 0; i < numdevs; i++) {
3335                 child = devlist[i];
3336                 dinfo = device_get_ivars(child);
3337                 dstate = state;
3338                 if (device_is_attached(child) &&
3339                     PCIB_POWER_FOR_SLEEP(pcib, dev, &dstate) == 0)
3340                         pci_set_powerstate(child, dstate);
3341         }
3342 }
3343
3344 int
3345 pci_suspend(device_t dev)
3346 {
3347         device_t child, *devlist;
3348         struct pci_devinfo *dinfo;
3349         int error, i, numdevs;
3350
3351         /*
3352          * Save the PCI configuration space for each child and set the
3353          * device in the appropriate power state for this sleep state.
3354          */
3355         if ((error = device_get_children(dev, &devlist, &numdevs)) != 0)
3356                 return (error);
3357         for (i = 0; i < numdevs; i++) {
3358                 child = devlist[i];
3359                 dinfo = device_get_ivars(child);
3360                 pci_cfg_save(child, dinfo, 0);
3361         }
3362
3363         /* Suspend devices before potentially powering them down. */
3364         error = bus_generic_suspend(dev);
3365         if (error) {
3366                 free(devlist, M_TEMP);
3367                 return (error);
3368         }
3369         if (pci_do_power_suspend)
3370                 pci_set_power_children(dev, devlist, numdevs,
3371                     PCI_POWERSTATE_D3);
3372         free(devlist, M_TEMP);
3373         return (0);
3374 }
3375
3376 int
3377 pci_resume(device_t dev)
3378 {
3379         device_t child, *devlist;
3380         struct pci_devinfo *dinfo;
3381         int error, i, numdevs;
3382
3383         /*
3384          * Set each child to D0 and restore its PCI configuration space.
3385          */
3386         if ((error = device_get_children(dev, &devlist, &numdevs)) != 0)
3387                 return (error);
3388         if (pci_do_power_resume)
3389                 pci_set_power_children(dev, devlist, numdevs,
3390                     PCI_POWERSTATE_D0);
3391
3392         /* Now the device is powered up, restore its config space. */
3393         for (i = 0; i < numdevs; i++) {
3394                 child = devlist[i];
3395                 dinfo = device_get_ivars(child);
3396
3397                 pci_cfg_restore(child, dinfo);
3398                 if (!device_is_attached(child))
3399                         pci_cfg_save(child, dinfo, 1);
3400         }
3401
3402         /*
3403          * Resume critical devices first, then everything else later.
3404          */
3405         for (i = 0; i < numdevs; i++) {
3406                 child = devlist[i];
3407                 switch (pci_get_class(child)) {
3408                 case PCIC_DISPLAY:
3409                 case PCIC_MEMORY:
3410                 case PCIC_BRIDGE:
3411                 case PCIC_BASEPERIPH:
3412                         DEVICE_RESUME(child);
3413                         break;
3414                 }
3415         }
3416         for (i = 0; i < numdevs; i++) {
3417                 child = devlist[i];
3418                 switch (pci_get_class(child)) {
3419                 case PCIC_DISPLAY:
3420                 case PCIC_MEMORY:
3421                 case PCIC_BRIDGE:
3422                 case PCIC_BASEPERIPH:
3423                         break;
3424                 default:
3425                         DEVICE_RESUME(child);
3426                 }
3427         }
3428         free(devlist, M_TEMP);
3429         return (0);
3430 }
3431
3432 static void
3433 pci_load_vendor_data(void)
3434 {
3435         caddr_t data;
3436         void *ptr;
3437         size_t sz;
3438
3439         data = preload_search_by_type("pci_vendor_data");
3440         if (data != NULL) {
3441                 ptr = preload_fetch_addr(data);
3442                 sz = preload_fetch_size(data);
3443                 if (ptr != NULL && sz != 0) {
3444                         pci_vendordata = ptr;
3445                         pci_vendordata_size = sz;
3446                         /* terminate the database */
3447                         pci_vendordata[pci_vendordata_size] = '\n';
3448                 }
3449         }
3450 }
3451
3452 void
3453 pci_driver_added(device_t dev, driver_t *driver)
3454 {
3455         int numdevs;
3456         device_t *devlist;
3457         device_t child;
3458         struct pci_devinfo *dinfo;
3459         int i;
3460
3461         if (bootverbose)
3462                 device_printf(dev, "driver added\n");
3463         DEVICE_IDENTIFY(driver, dev);
3464         if (device_get_children(dev, &devlist, &numdevs) != 0)
3465                 return;
3466         for (i = 0; i < numdevs; i++) {
3467                 child = devlist[i];
3468                 if (device_get_state(child) != DS_NOTPRESENT)
3469                         continue;
3470                 dinfo = device_get_ivars(child);
3471                 pci_print_verbose(dinfo);
3472                 if (bootverbose)
3473                         pci_printf(&dinfo->cfg, "reprobing on driver added\n");
3474                 pci_cfg_restore(child, dinfo);
3475                 if (device_probe_and_attach(child) != 0)
3476                         pci_cfg_save(child, dinfo, 1);
3477         }
3478         free(devlist, M_TEMP);
3479 }
3480
3481 int
3482 pci_setup_intr(device_t dev, device_t child, struct resource *irq, int flags,
3483     driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep)
3484 {
3485         struct pci_devinfo *dinfo;
3486         struct msix_table_entry *mte;
3487         struct msix_vector *mv;
3488         uint64_t addr;
3489         uint32_t data;
3490         void *cookie;
3491         int error, rid;
3492
3493         error = bus_generic_setup_intr(dev, child, irq, flags, filter, intr,
3494             arg, &cookie);
3495         if (error)
3496                 return (error);
3497
3498         /* If this is not a direct child, just bail out. */
3499         if (device_get_parent(child) != dev) {
3500                 *cookiep = cookie;
3501                 return(0);
3502         }
3503
3504         rid = rman_get_rid(irq);
3505         if (rid == 0) {
3506                 /* Make sure that INTx is enabled */
3507                 pci_clear_command_bit(dev, child, PCIM_CMD_INTxDIS);
3508         } else {
3509                 /*
3510                  * Check to see if the interrupt is MSI or MSI-X.
3511                  * Ask our parent to map the MSI and give
3512                  * us the address and data register values.
3513                  * If we fail for some reason, teardown the
3514                  * interrupt handler.
3515                  */
3516                 dinfo = device_get_ivars(child);
3517                 if (dinfo->cfg.msi.msi_alloc > 0) {
3518                         if (dinfo->cfg.msi.msi_addr == 0) {
3519                                 KASSERT(dinfo->cfg.msi.msi_handlers == 0,
3520                             ("MSI has handlers, but vectors not mapped"));
3521                                 error = PCIB_MAP_MSI(device_get_parent(dev),
3522                                     child, rman_get_start(irq), &addr, &data);
3523                                 if (error)
3524                                         goto bad;
3525                                 dinfo->cfg.msi.msi_addr = addr;
3526                                 dinfo->cfg.msi.msi_data = data;
3527                         }
3528                         if (dinfo->cfg.msi.msi_handlers == 0)
3529                                 pci_enable_msi(child, dinfo->cfg.msi.msi_addr,
3530                                     dinfo->cfg.msi.msi_data);
3531                         dinfo->cfg.msi.msi_handlers++;
3532                 } else {
3533                         KASSERT(dinfo->cfg.msix.msix_alloc > 0,
3534                             ("No MSI or MSI-X interrupts allocated"));
3535                         KASSERT(rid <= dinfo->cfg.msix.msix_table_len,
3536                             ("MSI-X index too high"));
3537                         mte = &dinfo->cfg.msix.msix_table[rid - 1];
3538                         KASSERT(mte->mte_vector != 0, ("no message vector"));
3539                         mv = &dinfo->cfg.msix.msix_vectors[mte->mte_vector - 1];
3540                         KASSERT(mv->mv_irq == rman_get_start(irq),
3541                             ("IRQ mismatch"));
3542                         if (mv->mv_address == 0) {
3543                                 KASSERT(mte->mte_handlers == 0,
3544                     ("MSI-X table entry has handlers, but vector not mapped"));
3545                                 error = PCIB_MAP_MSI(device_get_parent(dev),
3546                                     child, rman_get_start(irq), &addr, &data);
3547                                 if (error)
3548                                         goto bad;
3549                                 mv->mv_address = addr;
3550                                 mv->mv_data = data;
3551                         }
3552                         if (mte->mte_handlers == 0) {
3553                                 pci_enable_msix(child, rid - 1, mv->mv_address,
3554                                     mv->mv_data);
3555                                 pci_unmask_msix(child, rid - 1);
3556                         }
3557                         mte->mte_handlers++;
3558                 }
3559
3560                 /* Make sure that INTx is disabled if we are using MSI/MSIX */
3561                 pci_set_command_bit(dev, child, PCIM_CMD_INTxDIS);
3562         bad:
3563                 if (error) {
3564                         (void)bus_generic_teardown_intr(dev, child, irq,
3565                             cookie);
3566                         return (error);
3567                 }
3568         }
3569         *cookiep = cookie;
3570         return (0);
3571 }
3572
3573 int
3574 pci_teardown_intr(device_t dev, device_t child, struct resource *irq,
3575     void *cookie)
3576 {
3577         struct msix_table_entry *mte;
3578         struct resource_list_entry *rle;
3579         struct pci_devinfo *dinfo;
3580         int error, rid;
3581
3582         if (irq == NULL || !(rman_get_flags(irq) & RF_ACTIVE))
3583                 return (EINVAL);
3584
3585         /* If this isn't a direct child, just bail out */
3586         if (device_get_parent(child) != dev)
3587                 return(bus_generic_teardown_intr(dev, child, irq, cookie));
3588
3589         rid = rman_get_rid(irq);
3590         if (rid == 0) {
3591                 /* Mask INTx */
3592                 pci_set_command_bit(dev, child, PCIM_CMD_INTxDIS);
3593         } else {
3594                 /*
3595                  * Check to see if the interrupt is MSI or MSI-X.  If so,
3596                  * decrement the appropriate handlers count and mask the
3597                  * MSI-X message, or disable MSI messages if the count
3598                  * drops to 0.
3599                  */
3600                 dinfo = device_get_ivars(child);
3601                 rle = resource_list_find(&dinfo->resources, SYS_RES_IRQ, rid);
3602                 if (rle->res != irq)
3603                         return (EINVAL);
3604                 if (dinfo->cfg.msi.msi_alloc > 0) {
3605                         KASSERT(rid <= dinfo->cfg.msi.msi_alloc,
3606                             ("MSI-X index too high"));
3607                         if (dinfo->cfg.msi.msi_handlers == 0)
3608                                 return (EINVAL);
3609                         dinfo->cfg.msi.msi_handlers--;
3610                         if (dinfo->cfg.msi.msi_handlers == 0)
3611                                 pci_disable_msi(child);
3612                 } else {
3613                         KASSERT(dinfo->cfg.msix.msix_alloc > 0,
3614                             ("No MSI or MSI-X interrupts allocated"));
3615                         KASSERT(rid <= dinfo->cfg.msix.msix_table_len,
3616                             ("MSI-X index too high"));
3617                         mte = &dinfo->cfg.msix.msix_table[rid - 1];
3618                         if (mte->mte_handlers == 0)
3619                                 return (EINVAL);
3620                         mte->mte_handlers--;
3621                         if (mte->mte_handlers == 0)
3622                                 pci_mask_msix(child, rid - 1);
3623                 }
3624         }
3625         error = bus_generic_teardown_intr(dev, child, irq, cookie);
3626         if (rid > 0)
3627                 KASSERT(error == 0,
3628                     ("%s: generic teardown failed for MSI/MSI-X", __func__));
3629         return (error);
3630 }
3631
3632 int
3633 pci_print_child(device_t dev, device_t child)
3634 {
3635         struct pci_devinfo *dinfo;
3636         struct resource_list *rl;
3637         int retval = 0;
3638
3639         dinfo = device_get_ivars(child);
3640         rl = &dinfo->resources;
3641
3642         retval += bus_print_child_header(dev, child);
3643
3644         retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#lx");
3645         retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY, "%#lx");
3646         retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%ld");
3647         if (device_get_flags(dev))
3648                 retval += printf(" flags %#x", device_get_flags(dev));
3649
3650         retval += printf(" at device %d.%d", pci_get_slot(child),
3651             pci_get_function(child));
3652
3653         retval += bus_print_child_footer(dev, child);
3654
3655         return (retval);
3656 }
3657
3658 static const struct
3659 {
3660         int             class;
3661         int             subclass;
3662         int             report; /* 0 = bootverbose, 1 = always */
3663         const char      *desc;
3664 } pci_nomatch_tab[] = {
3665         {PCIC_OLD,              -1,                     1, "old"},
3666         {PCIC_OLD,              PCIS_OLD_NONVGA,        1, "non-VGA display device"},
3667         {PCIC_OLD,              PCIS_OLD_VGA,           1, "VGA-compatible display device"},
3668         {PCIC_STORAGE,          -1,                     1, "mass storage"},
3669         {PCIC_STORAGE,          PCIS_STORAGE_SCSI,      1, "SCSI"},
3670         {PCIC_STORAGE,          PCIS_STORAGE_IDE,       1, "ATA"},
3671         {PCIC_STORAGE,          PCIS_STORAGE_FLOPPY,    1, "floppy disk"},
3672         {PCIC_STORAGE,          PCIS_STORAGE_IPI,       1, "IPI"},
3673         {PCIC_STORAGE,          PCIS_STORAGE_RAID,      1, "RAID"},
3674         {PCIC_STORAGE,          PCIS_STORAGE_ATA_ADMA,  1, "ATA (ADMA)"},
3675         {PCIC_STORAGE,          PCIS_STORAGE_SATA,      1, "SATA"},
3676         {PCIC_STORAGE,          PCIS_STORAGE_SAS,       1, "SAS"},
3677         {PCIC_STORAGE,          PCIS_STORAGE_NVM,       1, "NVM"},
3678         {PCIC_NETWORK,          -1,                     1, "network"},
3679         {PCIC_NETWORK,          PCIS_NETWORK_ETHERNET,  1, "ethernet"},
3680         {PCIC_NETWORK,          PCIS_NETWORK_TOKENRING, 1, "token ring"},
3681         {PCIC_NETWORK,          PCIS_NETWORK_FDDI,      1, "fddi"},
3682         {PCIC_NETWORK,          PCIS_NETWORK_ATM,       1, "ATM"},
3683         {PCIC_NETWORK,          PCIS_NETWORK_ISDN,      1, "ISDN"},
3684         {PCIC_DISPLAY,          -1,                     1, "display"},
3685         {PCIC_DISPLAY,          PCIS_DISPLAY_VGA,       1, "VGA"},
3686         {PCIC_DISPLAY,          PCIS_DISPLAY_XGA,       1, "XGA"},
3687         {PCIC_DISPLAY,          PCIS_DISPLAY_3D,        1, "3D"},
3688         {PCIC_MULTIMEDIA,       -1,                     1, "multimedia"},
3689         {PCIC_MULTIMEDIA,       PCIS_MULTIMEDIA_VIDEO,  1, "video"},
3690         {PCIC_MULTIMEDIA,       PCIS_MULTIMEDIA_AUDIO,  1, "audio"},
3691         {PCIC_MULTIMEDIA,       PCIS_MULTIMEDIA_TELE,   1, "telephony"},
3692         {PCIC_MULTIMEDIA,       PCIS_MULTIMEDIA_HDA,    1, "HDA"},
3693         {PCIC_MEMORY,           -1,                     1, "memory"},
3694         {PCIC_MEMORY,           PCIS_MEMORY_RAM,        1, "RAM"},
3695         {PCIC_MEMORY,           PCIS_MEMORY_FLASH,      1, "flash"},
3696         {PCIC_BRIDGE,           -1,                     1, "bridge"},
3697         {PCIC_BRIDGE,           PCIS_BRIDGE_HOST,       1, "HOST-PCI"},
3698         {PCIC_BRIDGE,           PCIS_BRIDGE_ISA,        1, "PCI-ISA"},
3699         {PCIC_BRIDGE,           PCIS_BRIDGE_EISA,       1, "PCI-EISA"},
3700         {PCIC_BRIDGE,           PCIS_BRIDGE_MCA,        1, "PCI-MCA"},
3701         {PCIC_BRIDGE,           PCIS_BRIDGE_PCI,        1, "PCI-PCI"},
3702         {PCIC_BRIDGE,           PCIS_BRIDGE_PCMCIA,     1, "PCI-PCMCIA"},
3703         {PCIC_BRIDGE,           PCIS_BRIDGE_NUBUS,      1, "PCI-NuBus"},
3704         {PCIC_BRIDGE,           PCIS_BRIDGE_CARDBUS,    1, "PCI-CardBus"},
3705         {PCIC_BRIDGE,           PCIS_BRIDGE_RACEWAY,    1, "PCI-RACEway"},
3706         {PCIC_SIMPLECOMM,       -1,                     1, "simple comms"},
3707         {PCIC_SIMPLECOMM,       PCIS_SIMPLECOMM_UART,   1, "UART"},     /* could detect 16550 */
3708         {PCIC_SIMPLECOMM,       PCIS_SIMPLECOMM_PAR,    1, "parallel port"},
3709         {PCIC_SIMPLECOMM,       PCIS_SIMPLECOMM_MULSER, 1, "multiport serial"},
3710         {PCIC_SIMPLECOMM,       PCIS_SIMPLECOMM_MODEM,  1, "generic modem"},
3711         {PCIC_BASEPERIPH,       -1,                     0, "base peripheral"},
3712         {PCIC_BASEPERIPH,       PCIS_BASEPERIPH_PIC,    1, "interrupt controller"},
3713         {PCIC_BASEPERIPH,       PCIS_BASEPERIPH_DMA,    1, "DMA controller"},
3714         {PCIC_BASEPERIPH,       PCIS_BASEPERIPH_TIMER,  1, "timer"},
3715         {PCIC_BASEPERIPH,       PCIS_BASEPERIPH_RTC,    1, "realtime clock"},
3716         {PCIC_BASEPERIPH,       PCIS_BASEPERIPH_PCIHOT, 1, "PCI hot-plug controller"},
3717         {PCIC_BASEPERIPH,       PCIS_BASEPERIPH_SDHC,   1, "SD host controller"},
3718         {PCIC_INPUTDEV,         -1,                     1, "input device"},
3719         {PCIC_INPUTDEV,         PCIS_INPUTDEV_KEYBOARD, 1, "keyboard"},
3720         {PCIC_INPUTDEV,         PCIS_INPUTDEV_DIGITIZER,1, "digitizer"},
3721         {PCIC_INPUTDEV,         PCIS_INPUTDEV_MOUSE,    1, "mouse"},
3722         {PCIC_INPUTDEV,         PCIS_INPUTDEV_SCANNER,  1, "scanner"},
3723         {PCIC_INPUTDEV,         PCIS_INPUTDEV_GAMEPORT, 1, "gameport"},
3724         {PCIC_DOCKING,          -1,                     1, "docking station"},
3725         {PCIC_PROCESSOR,        -1,                     1, "processor"},
3726         {PCIC_SERIALBUS,        -1,                     1, "serial bus"},
3727         {PCIC_SERIALBUS,        PCIS_SERIALBUS_FW,      1, "FireWire"},
3728         {PCIC_SERIALBUS,        PCIS_SERIALBUS_ACCESS,  1, "AccessBus"},
3729         {PCIC_SERIALBUS,        PCIS_SERIALBUS_SSA,     1, "SSA"},
3730         {PCIC_SERIALBUS,        PCIS_SERIALBUS_USB,     1, "USB"},
3731         {PCIC_SERIALBUS,        PCIS_SERIALBUS_FC,      1, "Fibre Channel"},
3732         {PCIC_SERIALBUS,        PCIS_SERIALBUS_SMBUS,   0, "SMBus"},
3733         {PCIC_WIRELESS,         -1,                     1, "wireless controller"},
3734         {PCIC_WIRELESS,         PCIS_WIRELESS_IRDA,     1, "iRDA"},
3735         {PCIC_WIRELESS,         PCIS_WIRELESS_IR,       1, "IR"},
3736         {PCIC_WIRELESS,         PCIS_WIRELESS_RF,       1, "RF"},
3737         {PCIC_INTELLIIO,        -1,                     1, "intelligent I/O controller"},
3738         {PCIC_INTELLIIO,        PCIS_INTELLIIO_I2O,     1, "I2O"},
3739         {PCIC_SATCOM,           -1,                     1, "satellite communication"},
3740         {PCIC_SATCOM,           PCIS_SATCOM_TV,         1, "sat TV"},
3741         {PCIC_SATCOM,           PCIS_SATCOM_AUDIO,      1, "sat audio"},
3742         {PCIC_SATCOM,           PCIS_SATCOM_VOICE,      1, "sat voice"},
3743         {PCIC_SATCOM,           PCIS_SATCOM_DATA,       1, "sat data"},
3744         {PCIC_CRYPTO,           -1,                     1, "encrypt/decrypt"},
3745         {PCIC_CRYPTO,           PCIS_CRYPTO_NETCOMP,    1, "network/computer crypto"},
3746         {PCIC_CRYPTO,           PCIS_CRYPTO_ENTERTAIN,  1, "entertainment crypto"},
3747         {PCIC_DASP,             -1,                     0, "dasp"},
3748         {PCIC_DASP,             PCIS_DASP_DPIO,         1, "DPIO module"},
3749         {0, 0, 0,               NULL}
3750 };
3751
3752 void
3753 pci_probe_nomatch(device_t dev, device_t child)
3754 {
3755         int i, report;
3756         const char *cp, *scp;
3757         char *device;
3758
3759         /*
3760          * Look for a listing for this device in a loaded device database.
3761          */
3762         report = 1;
3763         if ((device = pci_describe_device(child)) != NULL) {
3764                 device_printf(dev, "<%s>", device);
3765                 free(device, M_DEVBUF);
3766         } else {
3767                 /*
3768                  * Scan the class/subclass descriptions for a general
3769                  * description.
3770                  */
3771                 cp = "unknown";
3772                 scp = NULL;
3773                 for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
3774                         if (pci_nomatch_tab[i].class == pci_get_class(child)) {
3775                                 if (pci_nomatch_tab[i].subclass == -1) {
3776                                         cp = pci_nomatch_tab[i].desc;
3777                                         report = pci_nomatch_tab[i].report;
3778                                 } else if (pci_nomatch_tab[i].subclass ==
3779                                     pci_get_subclass(child)) {
3780                                         scp = pci_nomatch_tab[i].desc;
3781                                         report = pci_nomatch_tab[i].report;
3782                                 }
3783                         }
3784                 }
3785                 if (report || bootverbose) {
3786                         device_printf(dev, "<%s%s%s>",
3787                             cp ? cp : "",
3788                             ((cp != NULL) && (scp != NULL)) ? ", " : "",
3789                             scp ? scp : "");
3790                 }
3791         }
3792         if (report || bootverbose) {
3793                 printf(" at device %d.%d (no driver attached)\n",
3794                     pci_get_slot(child), pci_get_function(child));
3795         }
3796         pci_cfg_save(child, device_get_ivars(child), 1);
3797 }
3798
3799 /*
3800  * Parse the PCI device database, if loaded, and return a pointer to a
3801  * description of the device.
3802  *
3803  * The database is flat text formatted as follows:
3804  *
3805  * Any line not in a valid format is ignored.
3806  * Lines are terminated with newline '\n' characters.
3807  *
3808  * A VENDOR line consists of the 4 digit (hex) vendor code, a TAB, then
3809  * the vendor name.
3810  *
3811  * A DEVICE line is entered immediately below the corresponding VENDOR ID.
3812  * - devices cannot be listed without a corresponding VENDOR line.
3813  * A DEVICE line consists of a TAB, the 4 digit (hex) device code,
3814  * another TAB, then the device name.
3815  */
3816
3817 /*
3818  * Assuming (ptr) points to the beginning of a line in the database,
3819  * return the vendor or device and description of the next entry.
3820  * The value of (vendor) or (device) inappropriate for the entry type
3821  * is set to -1.  Returns nonzero at the end of the database.
3822  *
3823  * Note that this is slightly unrobust in the face of corrupt data;
3824  * we attempt to safeguard against this by spamming the end of the
3825  * database with a newline when we initialise.
3826  */
3827 static int
3828 pci_describe_parse_line(char **ptr, int *vendor, int *device, char **desc)
3829 {
3830         char    *cp = *ptr;
3831         int     left;
3832
3833         *device = -1;
3834         *vendor = -1;
3835         **desc = '\0';
3836         for (;;) {
3837                 left = pci_vendordata_size - (cp - pci_vendordata);
3838                 if (left <= 0) {
3839                         *ptr = cp;
3840                         return(1);
3841                 }
3842
3843                 /* vendor entry? */
3844                 if (*cp != '\t' &&
3845                     sscanf(cp, "%x\t%80[^\n]", vendor, *desc) == 2)
3846                         break;
3847                 /* device entry? */
3848                 if (*cp == '\t' &&
3849                     sscanf(cp, "%x\t%80[^\n]", device, *desc) == 2)
3850                         break;
3851
3852                 /* skip to next line */
3853                 while (*cp != '\n' && left > 0) {
3854                         cp++;
3855                         left--;
3856                 }
3857                 if (*cp == '\n') {
3858                         cp++;
3859                         left--;
3860                 }
3861         }
3862         /* skip to next line */
3863         while (*cp != '\n' && left > 0) {
3864                 cp++;
3865                 left--;
3866         }
3867         if (*cp == '\n' && left > 0)
3868                 cp++;
3869         *ptr = cp;
3870         return(0);
3871 }
3872
3873 static char *
3874 pci_describe_device(device_t dev)
3875 {
3876         int     vendor, device;
3877         char    *desc, *vp, *dp, *line;
3878
3879         desc = vp = dp = NULL;
3880
3881         /*
3882          * If we have no vendor data, we can't do anything.
3883          */
3884         if (pci_vendordata == NULL)
3885                 goto out;
3886
3887         /*
3888          * Scan the vendor data looking for this device
3889          */
3890         line = pci_vendordata;
3891         if ((vp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
3892                 goto out;
3893         for (;;) {
3894                 if (pci_describe_parse_line(&line, &vendor, &device, &vp))
3895                         goto out;
3896                 if (vendor == pci_get_vendor(dev))
3897                         break;
3898         }
3899         if ((dp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
3900                 goto out;
3901         for (;;) {
3902                 if (pci_describe_parse_line(&line, &vendor, &device, &dp)) {
3903                         *dp = 0;
3904                         break;
3905                 }
3906                 if (vendor != -1) {
3907                         *dp = 0;
3908                         break;
3909                 }
3910                 if (device == pci_get_device(dev))
3911                         break;
3912         }
3913         if (dp[0] == '\0')
3914                 snprintf(dp, 80, "0x%x", pci_get_device(dev));
3915         if ((desc = malloc(strlen(vp) + strlen(dp) + 3, M_DEVBUF, M_NOWAIT)) !=
3916             NULL)
3917                 sprintf(desc, "%s, %s", vp, dp);
3918 out:
3919         if (vp != NULL)
3920                 free(vp, M_DEVBUF);
3921         if (dp != NULL)
3922                 free(dp, M_DEVBUF);
3923         return(desc);
3924 }
3925
3926 int
3927 pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
3928 {
3929         struct pci_devinfo *dinfo;
3930         pcicfgregs *cfg;
3931
3932         dinfo = device_get_ivars(child);
3933         cfg = &dinfo->cfg;
3934
3935         switch (which) {
3936         case PCI_IVAR_ETHADDR:
3937                 /*
3938                  * The generic accessor doesn't deal with failure, so
3939                  * we set the return value, then return an error.
3940                  */
3941                 *((uint8_t **) result) = NULL;
3942                 return (EINVAL);
3943         case PCI_IVAR_SUBVENDOR:
3944                 *result = cfg->subvendor;
3945                 break;
3946         case PCI_IVAR_SUBDEVICE:
3947                 *result = cfg->subdevice;
3948                 break;
3949         case PCI_IVAR_VENDOR:
3950                 *result = cfg->vendor;
3951                 break;
3952         case PCI_IVAR_DEVICE:
3953                 *result = cfg->device;
3954                 break;
3955         case PCI_IVAR_DEVID:
3956                 *result = (cfg->device << 16) | cfg->vendor;
3957                 break;
3958         case PCI_IVAR_CLASS:
3959                 *result = cfg->baseclass;
3960                 break;
3961         case PCI_IVAR_SUBCLASS:
3962                 *result = cfg->subclass;
3963                 break;
3964         case PCI_IVAR_PROGIF:
3965                 *result = cfg->progif;
3966                 break;
3967         case PCI_IVAR_REVID:
3968                 *result = cfg->revid;
3969                 break;
3970         case PCI_IVAR_INTPIN:
3971                 *result = cfg->intpin;
3972                 break;
3973         case PCI_IVAR_IRQ:
3974                 *result = cfg->intline;
3975                 break;
3976         case PCI_IVAR_DOMAIN:
3977                 *result = cfg->domain;
3978                 break;
3979         case PCI_IVAR_BUS:
3980                 *result = cfg->bus;
3981                 break;
3982         case PCI_IVAR_SLOT:
3983                 *result = cfg->slot;
3984                 break;
3985         case PCI_IVAR_FUNCTION:
3986                 *result = cfg->func;
3987                 break;
3988         case PCI_IVAR_CMDREG:
3989                 *result = cfg->cmdreg;
3990                 break;
3991         case PCI_IVAR_CACHELNSZ:
3992                 *result = cfg->cachelnsz;
3993                 break;
3994         case PCI_IVAR_MINGNT:
3995                 *result = cfg->mingnt;
3996                 break;
3997         case PCI_IVAR_MAXLAT:
3998                 *result = cfg->maxlat;
3999                 break;
4000         case PCI_IVAR_LATTIMER:
4001                 *result = cfg->lattimer;
4002                 break;
4003         default:
4004                 return (ENOENT);
4005         }
4006         return (0);
4007 }
4008
4009 int
4010 pci_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
4011 {
4012         struct pci_devinfo *dinfo;
4013
4014         dinfo = device_get_ivars(child);
4015
4016         switch (which) {
4017         case PCI_IVAR_INTPIN:
4018                 dinfo->cfg.intpin = value;
4019                 return (0);
4020         case PCI_IVAR_ETHADDR:
4021         case PCI_IVAR_SUBVENDOR:
4022         case PCI_IVAR_SUBDEVICE:
4023         case PCI_IVAR_VENDOR:
4024         case PCI_IVAR_DEVICE:
4025         case PCI_IVAR_DEVID:
4026         case PCI_IVAR_CLASS:
4027         case PCI_IVAR_SUBCLASS:
4028         case PCI_IVAR_PROGIF:
4029         case PCI_IVAR_REVID:
4030         case PCI_IVAR_IRQ:
4031         case PCI_IVAR_DOMAIN:
4032         case PCI_IVAR_BUS:
4033         case PCI_IVAR_SLOT:
4034         case PCI_IVAR_FUNCTION:
4035                 return (EINVAL);        /* disallow for now */
4036
4037         default:
4038                 return (ENOENT);
4039         }
4040 }
4041
4042 #include "opt_ddb.h"
4043 #ifdef DDB
4044 #include <ddb/ddb.h>
4045 #include <sys/cons.h>
4046
4047 /*
4048  * List resources based on pci map registers, used for within ddb
4049  */
4050
4051 DB_SHOW_COMMAND(pciregs, db_pci_dump)
4052 {
4053         struct pci_devinfo *dinfo;
4054         struct devlist *devlist_head;
4055         struct pci_conf *p;
4056         const char *name;
4057         int i, error, none_count;
4058
4059         none_count = 0;
4060         /* get the head of the device queue */
4061         devlist_head = &pci_devq;
4062
4063         /*
4064          * Go through the list of devices and print out devices
4065          */
4066         for (error = 0, i = 0,
4067              dinfo = STAILQ_FIRST(devlist_head);
4068              (dinfo != NULL) && (error == 0) && (i < pci_numdevs) && !db_pager_quit;
4069              dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {
4070
4071                 /* Populate pd_name and pd_unit */
4072                 name = NULL;
4073                 if (dinfo->cfg.dev)
4074                         name = device_get_name(dinfo->cfg.dev);
4075
4076                 p = &dinfo->conf;
4077                 db_printf("%s%d@pci%d:%d:%d:%d:\tclass=0x%06x card=0x%08x "
4078                         "chip=0x%08x rev=0x%02x hdr=0x%02x\n",
4079                         (name && *name) ? name : "none",
4080                         (name && *name) ? (int)device_get_unit(dinfo->cfg.dev) :
4081                         none_count++,
4082                         p->pc_sel.pc_domain, p->pc_sel.pc_bus, p->pc_sel.pc_dev,
4083                         p->pc_sel.pc_func, (p->pc_class << 16) |
4084                         (p->pc_subclass << 8) | p->pc_progif,
4085                         (p->pc_subdevice << 16) | p->pc_subvendor,
4086                         (p->pc_device << 16) | p->pc_vendor,
4087                         p->pc_revid, p->pc_hdr);
4088         }
4089 }
4090 #endif /* DDB */
4091
4092 static struct resource *
4093 pci_reserve_map(device_t dev, device_t child, int type, int *rid,
4094     u_long start, u_long end, u_long count, u_int flags)
4095 {
4096         struct pci_devinfo *dinfo = device_get_ivars(child);
4097         struct resource_list *rl = &dinfo->resources;
4098         struct resource *res;
4099         struct pci_map *pm;
4100         pci_addr_t map, testval;
4101         int mapsize;
4102
4103         res = NULL;
4104         pm = pci_find_bar(child, *rid);
4105         if (pm != NULL) {
4106                 /* This is a BAR that we failed to allocate earlier. */
4107                 mapsize = pm->pm_size;
4108                 map = pm->pm_value;
4109         } else {
4110                 /*
4111                  * Weed out the bogons, and figure out how large the
4112                  * BAR/map is.  BARs that read back 0 here are bogus
4113                  * and unimplemented.  Note: atapci in legacy mode are
4114                  * special and handled elsewhere in the code.  If you
4115                  * have a atapci device in legacy mode and it fails
4116                  * here, that other code is broken.
4117                  */
4118                 pci_read_bar(child, *rid, &map, &testval);
4119
4120                 /*
4121                  * Determine the size of the BAR and ignore BARs with a size
4122                  * of 0.  Device ROM BARs use a different mask value.
4123                  */
4124                 if (PCIR_IS_BIOS(&dinfo->cfg, *rid))
4125                         mapsize = pci_romsize(testval);
4126                 else
4127                         mapsize = pci_mapsize(testval);
4128                 if (mapsize == 0)
4129                         goto out;
4130                 pm = pci_add_bar(child, *rid, map, mapsize);
4131         }
4132
4133         if (PCI_BAR_MEM(map) || PCIR_IS_BIOS(&dinfo->cfg, *rid)) {
4134                 if (type != SYS_RES_MEMORY) {
4135                         if (bootverbose)
4136                                 device_printf(dev,
4137                                     "child %s requested type %d for rid %#x,"
4138                                     " but the BAR says it is an memio\n",
4139                                     device_get_nameunit(child), type, *rid);
4140                         goto out;
4141                 }
4142         } else {
4143                 if (type != SYS_RES_IOPORT) {
4144                         if (bootverbose)
4145                                 device_printf(dev,
4146                                     "child %s requested type %d for rid %#x,"
4147                                     " but the BAR says it is an ioport\n",
4148                                     device_get_nameunit(child), type, *rid);
4149                         goto out;
4150                 }
4151         }
4152
4153         /*
4154          * For real BARs, we need to override the size that
4155          * the driver requests, because that's what the BAR
4156          * actually uses and we would otherwise have a
4157          * situation where we might allocate the excess to
4158          * another driver, which won't work.
4159          */
4160         count = (pci_addr_t)1 << mapsize;
4161         if (RF_ALIGNMENT(flags) < mapsize)
4162                 flags = (flags & ~RF_ALIGNMENT_MASK) | RF_ALIGNMENT_LOG2(mapsize);
4163         if (PCI_BAR_MEM(map) && (map & PCIM_BAR_MEM_PREFETCH))
4164                 flags |= RF_PREFETCHABLE;
4165
4166         /*
4167          * Allocate enough resource, and then write back the
4168          * appropriate BAR for that resource.
4169          */
4170         resource_list_add(rl, type, *rid, start, end, count);
4171         res = resource_list_reserve(rl, dev, child, type, rid, start, end,
4172             count, flags & ~RF_ACTIVE);
4173         if (res == NULL) {
4174                 resource_list_delete(rl, type, *rid);
4175                 device_printf(child,
4176                     "%#lx bytes of rid %#x res %d failed (%#lx, %#lx).\n",
4177                     count, *rid, type, start, end);
4178                 goto out;
4179         }
4180         if (bootverbose)
4181                 device_printf(child,
4182                     "Lazy allocation of %#lx bytes rid %#x type %d at %#lx\n",
4183                     count, *rid, type, rman_get_start(res));
4184         map = rman_get_start(res);
4185         pci_write_bar(child, pm, map);
4186 out:
4187         return (res);
4188 }
4189
4190 struct resource *
4191 pci_alloc_resource(device_t dev, device_t child, int type, int *rid,
4192                    u_long start, u_long end, u_long count, u_int flags)
4193 {
4194         struct pci_devinfo *dinfo;
4195         struct resource_list *rl;
4196         struct resource_list_entry *rle;
4197         struct resource *res;
4198         pcicfgregs *cfg;
4199
4200         if (device_get_parent(child) != dev)
4201                 return (BUS_ALLOC_RESOURCE(device_get_parent(dev), child,
4202                     type, rid, start, end, count, flags));
4203
4204         /*
4205          * Perform lazy resource allocation
4206          */
4207         dinfo = device_get_ivars(child);
4208         rl = &dinfo->resources;
4209         cfg = &dinfo->cfg;
4210         switch (type) {
4211         case SYS_RES_IRQ:
4212                 /*
4213                  * Can't alloc legacy interrupt once MSI messages have
4214                  * been allocated.
4215                  */
4216                 if (*rid == 0 && (cfg->msi.msi_alloc > 0 ||
4217                     cfg->msix.msix_alloc > 0))
4218                         return (NULL);
4219
4220                 /*
4221                  * If the child device doesn't have an interrupt
4222                  * routed and is deserving of an interrupt, try to
4223                  * assign it one.
4224                  */
4225                 if (*rid == 0 && !PCI_INTERRUPT_VALID(cfg->intline) &&
4226                     (cfg->intpin != 0))
4227                         pci_assign_interrupt(dev, child, 0);
4228                 break;
4229         case SYS_RES_IOPORT:
4230         case SYS_RES_MEMORY:
4231 #ifdef NEW_PCIB
4232                 /*
4233                  * PCI-PCI bridge I/O window resources are not BARs.
4234                  * For those allocations just pass the request up the
4235                  * tree.
4236                  */
4237                 if (cfg->hdrtype == PCIM_HDRTYPE_BRIDGE) {
4238                         switch (*rid) {
4239                         case PCIR_IOBASEL_1:
4240                         case PCIR_MEMBASE_1:
4241                         case PCIR_PMBASEL_1:
4242                                 /*
4243                                  * XXX: Should we bother creating a resource
4244                                  * list entry?
4245                                  */
4246                                 return (bus_generic_alloc_resource(dev, child,
4247                                     type, rid, start, end, count, flags));
4248                         }
4249                 }
4250 #endif
4251                 /* Reserve resources for this BAR if needed. */
4252                 rle = resource_list_find(rl, type, *rid);
4253                 if (rle == NULL) {
4254                         res = pci_reserve_map(dev, child, type, rid, start, end,
4255                             count, flags);
4256                         if (res == NULL)
4257                                 return (NULL);
4258                 }
4259         }
4260         return (resource_list_alloc(rl, dev, child, type, rid,
4261             start, end, count, flags));
4262 }
4263
4264 int
4265 pci_release_resource(device_t dev, device_t child, int type, int rid,
4266     struct resource *r)
4267 {
4268         struct pci_devinfo *dinfo;
4269         struct resource_list *rl;
4270         pcicfgregs *cfg;
4271
4272         if (device_get_parent(child) != dev)
4273                 return (BUS_RELEASE_RESOURCE(device_get_parent(dev), child,
4274                     type, rid, r));
4275
4276         dinfo = device_get_ivars(child);
4277         cfg = &dinfo->cfg;
4278 #ifdef NEW_PCIB
4279         /*
4280          * PCI-PCI bridge I/O window resources are not BARs.  For
4281          * those allocations just pass the request up the tree.
4282          */
4283         if (cfg->hdrtype == PCIM_HDRTYPE_BRIDGE &&
4284             (type == SYS_RES_IOPORT || type == SYS_RES_MEMORY)) {
4285                 switch (rid) {
4286                 case PCIR_IOBASEL_1:
4287                 case PCIR_MEMBASE_1:
4288                 case PCIR_PMBASEL_1:
4289                         return (bus_generic_release_resource(dev, child, type,
4290                             rid, r));
4291                 }
4292         }
4293 #endif
4294
4295         rl = &dinfo->resources;
4296         return (resource_list_release(rl, dev, child, type, rid, r));
4297 }
4298
4299 int
4300 pci_activate_resource(device_t dev, device_t child, int type, int rid,
4301     struct resource *r)
4302 {
4303         struct pci_devinfo *dinfo;
4304         int error;
4305
4306         error = bus_generic_activate_resource(dev, child, type, rid, r);
4307         if (error)
4308                 return (error);
4309
4310         /* Enable decoding in the command register when activating BARs. */
4311         if (device_get_parent(child) == dev) {
4312                 /* Device ROMs need their decoding explicitly enabled. */
4313                 dinfo = device_get_ivars(child);
4314                 if (type == SYS_RES_MEMORY && PCIR_IS_BIOS(&dinfo->cfg, rid))
4315                         pci_write_bar(child, pci_find_bar(child, rid),
4316                             rman_get_start(r) | PCIM_BIOS_ENABLE);
4317                 switch (type) {
4318                 case SYS_RES_IOPORT:
4319                 case SYS_RES_MEMORY:
4320                         error = PCI_ENABLE_IO(dev, child, type);
4321                         break;
4322                 }
4323         }
4324         return (error);
4325 }
4326
4327 int
4328 pci_deactivate_resource(device_t dev, device_t child, int type,
4329     int rid, struct resource *r)
4330 {
4331         struct pci_devinfo *dinfo;
4332         int error;
4333
4334         error = bus_generic_deactivate_resource(dev, child, type, rid, r);
4335         if (error)
4336                 return (error);
4337
4338         /* Disable decoding for device ROMs. */ 
4339         if (device_get_parent(child) == dev) {
4340                 dinfo = device_get_ivars(child);
4341                 if (type == SYS_RES_MEMORY && PCIR_IS_BIOS(&dinfo->cfg, rid))
4342                         pci_write_bar(child, pci_find_bar(child, rid),
4343                             rman_get_start(r));
4344         }
4345         return (0);
4346 }
4347
4348 void
4349 pci_delete_child(device_t dev, device_t child)
4350 {
4351         struct resource_list_entry *rle;
4352         struct resource_list *rl;
4353         struct pci_devinfo *dinfo;
4354
4355         dinfo = device_get_ivars(child);
4356         rl = &dinfo->resources;
4357
4358         if (device_is_attached(child))
4359                 device_detach(child);
4360
4361         /* Turn off access to resources we're about to free */
4362         pci_write_config(child, PCIR_COMMAND, pci_read_config(child,
4363             PCIR_COMMAND, 2) & ~(PCIM_CMD_MEMEN | PCIM_CMD_PORTEN), 2);
4364
4365         /* Free all allocated resources */
4366         STAILQ_FOREACH(rle, rl, link) {
4367                 if (rle->res) {
4368                         if (rman_get_flags(rle->res) & RF_ACTIVE ||
4369                             resource_list_busy(rl, rle->type, rle->rid)) {
4370                                 pci_printf(&dinfo->cfg,
4371                                     "Resource still owned, oops. "
4372                                     "(type=%d, rid=%d, addr=%lx)\n",
4373                                     rle->type, rle->rid,
4374                                     rman_get_start(rle->res));
4375                                 bus_release_resource(child, rle->type, rle->rid,
4376                                     rle->res);
4377                         }
4378                         resource_list_unreserve(rl, dev, child, rle->type,
4379                             rle->rid);
4380                 }
4381         }
4382         resource_list_free(rl);
4383
4384         device_delete_child(dev, child);
4385         pci_freecfg(dinfo);
4386 }
4387
4388 void
4389 pci_delete_resource(device_t dev, device_t child, int type, int rid)
4390 {
4391         struct pci_devinfo *dinfo;
4392         struct resource_list *rl;
4393         struct resource_list_entry *rle;
4394
4395         if (device_get_parent(child) != dev)
4396                 return;
4397
4398         dinfo = device_get_ivars(child);
4399         rl = &dinfo->resources;
4400         rle = resource_list_find(rl, type, rid);
4401         if (rle == NULL)
4402                 return;
4403
4404         if (rle->res) {
4405                 if (rman_get_flags(rle->res) & RF_ACTIVE ||
4406                     resource_list_busy(rl, type, rid)) {
4407                         device_printf(dev, "delete_resource: "
4408                             "Resource still owned by child, oops. "
4409                             "(type=%d, rid=%d, addr=%lx)\n",
4410                             type, rid, rman_get_start(rle->res));
4411                         return;
4412                 }
4413                 resource_list_unreserve(rl, dev, child, type, rid);
4414         }
4415         resource_list_delete(rl, type, rid);
4416 }
4417
4418 struct resource_list *
4419 pci_get_resource_list (device_t dev, device_t child)
4420 {
4421         struct pci_devinfo *dinfo = device_get_ivars(child);
4422
4423         return (&dinfo->resources);
4424 }
4425
4426 bus_dma_tag_t
4427 pci_get_dma_tag(device_t bus, device_t dev)
4428 {
4429         struct pci_softc *sc = device_get_softc(bus);
4430
4431         return (sc->sc_dma_tag);
4432 }
4433
4434 uint32_t
4435 pci_read_config_method(device_t dev, device_t child, int reg, int width)
4436 {
4437         struct pci_devinfo *dinfo = device_get_ivars(child);
4438         pcicfgregs *cfg = &dinfo->cfg;
4439
4440         return (PCIB_READ_CONFIG(device_get_parent(dev),
4441             cfg->bus, cfg->slot, cfg->func, reg, width));
4442 }
4443
4444 void
4445 pci_write_config_method(device_t dev, device_t child, int reg,
4446     uint32_t val, int width)
4447 {
4448         struct pci_devinfo *dinfo = device_get_ivars(child);
4449         pcicfgregs *cfg = &dinfo->cfg;
4450
4451         PCIB_WRITE_CONFIG(device_get_parent(dev),
4452             cfg->bus, cfg->slot, cfg->func, reg, val, width);
4453 }
4454
4455 int
4456 pci_child_location_str_method(device_t dev, device_t child, char *buf,
4457     size_t buflen)
4458 {
4459
4460         snprintf(buf, buflen, "slot=%d function=%d", pci_get_slot(child),
4461             pci_get_function(child));
4462         return (0);
4463 }
4464
4465 int
4466 pci_child_pnpinfo_str_method(device_t dev, device_t child, char *buf,
4467     size_t buflen)
4468 {
4469         struct pci_devinfo *dinfo;
4470         pcicfgregs *cfg;
4471
4472         dinfo = device_get_ivars(child);
4473         cfg = &dinfo->cfg;
4474         snprintf(buf, buflen, "vendor=0x%04x device=0x%04x subvendor=0x%04x "
4475             "subdevice=0x%04x class=0x%02x%02x%02x", cfg->vendor, cfg->device,
4476             cfg->subvendor, cfg->subdevice, cfg->baseclass, cfg->subclass,
4477             cfg->progif);
4478         return (0);
4479 }
4480
4481 int
4482 pci_assign_interrupt_method(device_t dev, device_t child)
4483 {
4484         struct pci_devinfo *dinfo = device_get_ivars(child);
4485         pcicfgregs *cfg = &dinfo->cfg;
4486
4487         return (PCIB_ROUTE_INTERRUPT(device_get_parent(dev), child,
4488             cfg->intpin));
4489 }
4490
4491 static int
4492 pci_modevent(module_t mod, int what, void *arg)
4493 {
4494         static struct cdev *pci_cdev;
4495
4496         switch (what) {
4497         case MOD_LOAD:
4498                 STAILQ_INIT(&pci_devq);
4499                 pci_generation = 0;
4500                 pci_cdev = make_dev(&pcicdev, 0, UID_ROOT, GID_WHEEL, 0644,
4501                     "pci");
4502                 pci_load_vendor_data();
4503                 break;
4504
4505         case MOD_UNLOAD:
4506                 destroy_dev(pci_cdev);
4507                 break;
4508         }
4509
4510         return (0);
4511 }
4512
4513 void
4514 pci_cfg_restore(device_t dev, struct pci_devinfo *dinfo)
4515 {
4516
4517         /*
4518          * Only do header type 0 devices.  Type 1 devices are bridges,
4519          * which we know need special treatment.  Type 2 devices are
4520          * cardbus bridges which also require special treatment.
4521          * Other types are unknown, and we err on the side of safety
4522          * by ignoring them.
4523          */
4524         if ((dinfo->cfg.hdrtype & PCIM_HDRTYPE) != PCIM_HDRTYPE_NORMAL)
4525                 return;
4526
4527         /*
4528          * Restore the device to full power mode.  We must do this
4529          * before we restore the registers because moving from D3 to
4530          * D0 will cause the chip's BARs and some other registers to
4531          * be reset to some unknown power on reset values.  Cut down
4532          * the noise on boot by doing nothing if we are already in
4533          * state D0.
4534          */
4535         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0)
4536                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
4537         pci_restore_bars(dev);
4538         pci_write_config(dev, PCIR_COMMAND, dinfo->cfg.cmdreg, 2);
4539         pci_write_config(dev, PCIR_INTLINE, dinfo->cfg.intline, 1);
4540         pci_write_config(dev, PCIR_INTPIN, dinfo->cfg.intpin, 1);
4541         pci_write_config(dev, PCIR_MINGNT, dinfo->cfg.mingnt, 1);
4542         pci_write_config(dev, PCIR_MAXLAT, dinfo->cfg.maxlat, 1);
4543         pci_write_config(dev, PCIR_CACHELNSZ, dinfo->cfg.cachelnsz, 1);
4544         pci_write_config(dev, PCIR_LATTIMER, dinfo->cfg.lattimer, 1);
4545         pci_write_config(dev, PCIR_PROGIF, dinfo->cfg.progif, 1);
4546         pci_write_config(dev, PCIR_REVID, dinfo->cfg.revid, 1);
4547
4548         /* Restore MSI and MSI-X configurations if they are present. */
4549         if (dinfo->cfg.msi.msi_location != 0)
4550                 pci_resume_msi(dev);
4551         if (dinfo->cfg.msix.msix_location != 0)
4552                 pci_resume_msix(dev);
4553 }
4554
4555 void
4556 pci_cfg_save(device_t dev, struct pci_devinfo *dinfo, int setstate)
4557 {
4558         uint32_t cls;
4559         int ps;
4560
4561         /*
4562          * Only do header type 0 devices.  Type 1 devices are bridges, which
4563          * we know need special treatment.  Type 2 devices are cardbus bridges
4564          * which also require special treatment.  Other types are unknown, and
4565          * we err on the side of safety by ignoring them.  Powering down
4566          * bridges should not be undertaken lightly.
4567          */
4568         if ((dinfo->cfg.hdrtype & PCIM_HDRTYPE) != PCIM_HDRTYPE_NORMAL)
4569                 return;
4570
4571         /*
4572          * Some drivers apparently write to these registers w/o updating our
4573          * cached copy.  No harm happens if we update the copy, so do so here
4574          * so we can restore them.  The COMMAND register is modified by the
4575          * bus w/o updating the cache.  This should represent the normally
4576          * writable portion of the 'defined' part of type 0 headers.  In
4577          * theory we also need to save/restore the PCI capability structures
4578          * we know about, but apart from power we don't know any that are
4579          * writable.
4580          */
4581         dinfo->cfg.subvendor = pci_read_config(dev, PCIR_SUBVEND_0, 2);
4582         dinfo->cfg.subdevice = pci_read_config(dev, PCIR_SUBDEV_0, 2);
4583         dinfo->cfg.vendor = pci_read_config(dev, PCIR_VENDOR, 2);
4584         dinfo->cfg.device = pci_read_config(dev, PCIR_DEVICE, 2);
4585         dinfo->cfg.cmdreg = pci_read_config(dev, PCIR_COMMAND, 2);
4586         dinfo->cfg.intline = pci_read_config(dev, PCIR_INTLINE, 1);
4587         dinfo->cfg.intpin = pci_read_config(dev, PCIR_INTPIN, 1);
4588         dinfo->cfg.mingnt = pci_read_config(dev, PCIR_MINGNT, 1);
4589         dinfo->cfg.maxlat = pci_read_config(dev, PCIR_MAXLAT, 1);
4590         dinfo->cfg.cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
4591         dinfo->cfg.lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
4592         dinfo->cfg.baseclass = pci_read_config(dev, PCIR_CLASS, 1);
4593         dinfo->cfg.subclass = pci_read_config(dev, PCIR_SUBCLASS, 1);
4594         dinfo->cfg.progif = pci_read_config(dev, PCIR_PROGIF, 1);
4595         dinfo->cfg.revid = pci_read_config(dev, PCIR_REVID, 1);
4596
4597         /*
4598          * don't set the state for display devices, base peripherals and
4599          * memory devices since bad things happen when they are powered down.
4600          * We should (a) have drivers that can easily detach and (b) use
4601          * generic drivers for these devices so that some device actually
4602          * attaches.  We need to make sure that when we implement (a) we don't
4603          * power the device down on a reattach.
4604          */
4605         cls = pci_get_class(dev);
4606         if (!setstate)
4607                 return;
4608         switch (pci_do_power_nodriver)
4609         {
4610                 case 0:         /* NO powerdown at all */
4611                         return;
4612                 case 1:         /* Conservative about what to power down */
4613                         if (cls == PCIC_STORAGE)
4614                                 return;
4615                         /*FALLTHROUGH*/
4616                 case 2:         /* Agressive about what to power down */
4617                         if (cls == PCIC_DISPLAY || cls == PCIC_MEMORY ||
4618                             cls == PCIC_BASEPERIPH)
4619                                 return;
4620                         /*FALLTHROUGH*/
4621                 case 3:         /* Power down everything */
4622                         break;
4623         }
4624         /*
4625          * PCI spec says we can only go into D3 state from D0 state.
4626          * Transition from D[12] into D0 before going to D3 state.
4627          */
4628         ps = pci_get_powerstate(dev);
4629         if (ps != PCI_POWERSTATE_D0 && ps != PCI_POWERSTATE_D3)
4630                 pci_set_powerstate(dev, PCI_POWERSTATE_D0);
4631         if (pci_get_powerstate(dev) != PCI_POWERSTATE_D3)
4632                 pci_set_powerstate(dev, PCI_POWERSTATE_D3);
4633 }
4634
4635 /* Wrapper APIs suitable for device driver use. */
4636 void
4637 pci_save_state(device_t dev)
4638 {
4639         struct pci_devinfo *dinfo;
4640
4641         dinfo = device_get_ivars(dev);
4642         pci_cfg_save(dev, dinfo, 0);
4643 }
4644
4645 void
4646 pci_restore_state(device_t dev)
4647 {
4648         struct pci_devinfo *dinfo;
4649
4650         dinfo = device_get_ivars(dev);
4651         pci_cfg_restore(dev, dinfo);
4652 }