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