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