Fix typo.
[dragonfly.git] / sys / bus / pci / pci.c
1 /*
2  * Copyright (c) 1997, Stefan Esser <se@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions, and the following
10  *    disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/pci/pci.c,v 1.141.2.15 2002/04/30 17:48:18 tmm Exp $
27  * $DragonFly: src/sys/bus/pci/pci.c,v 1.47 2007/11/25 02:17:56 sephe Exp $
28  *
29  */
30
31 #include "opt_bus.h"
32 #include "opt_pci.h"
33
34 #include "opt_compat_oldpci.h"
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/fcntl.h>
41 #include <sys/conf.h>
42 #include <sys/kernel.h>
43 #include <sys/queue.h>
44 #include <sys/types.h>
45 #include <sys/buf.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 <sys/rman.h>
53 #include <machine/smp.h>
54 #ifdef __i386__
55 #include <bus/pci/i386/pci_cfgreg.h>
56 #endif
57
58 #include <sys/pciio.h>
59 #include "pcireg.h"
60 #include "pcivar.h"
61 #include "pci_private.h"
62
63 #include "pcib_if.h"
64
65 devclass_t      pci_devclass;
66 const char      *pcib_owner;
67
68 static void             pci_read_capabilities(device_t dev, pcicfgregs *cfg);
69
70 struct pci_quirk {
71         u_int32_t devid;        /* Vendor/device of the card */
72         int     type;
73 #define PCI_QUIRK_MAP_REG       1 /* PCI map register in weird place */
74         int     arg1;
75         int     arg2;
76 };
77
78 struct pci_quirk pci_quirks[] = {
79         /*
80          * The Intel 82371AB and 82443MX has a map register at offset 0x90.
81          */
82         { 0x71138086, PCI_QUIRK_MAP_REG,        0x90,    0 },
83         { 0x719b8086, PCI_QUIRK_MAP_REG,        0x90,    0 },
84         /* As does the Serverworks OSB4 (the SMBus mapping register) */
85         { 0x02001166, PCI_QUIRK_MAP_REG,        0x90,    0 },
86
87         { 0 }
88 };
89
90 /* map register information */
91 #define PCI_MAPMEM      0x01    /* memory map */
92 #define PCI_MAPMEMP     0x02    /* prefetchable memory map */
93 #define PCI_MAPPORT     0x04    /* port map */
94
95 static STAILQ_HEAD(devlist, pci_devinfo) pci_devq;
96 u_int32_t pci_numdevs = 0;
97 static u_int32_t pci_generation = 0;
98
99 device_t
100 pci_find_bsf(u_int8_t bus, u_int8_t slot, u_int8_t func)
101 {
102         struct pci_devinfo *dinfo;
103
104         STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
105                 if ((dinfo->cfg.bus == bus) &&
106                     (dinfo->cfg.slot == slot) &&
107                     (dinfo->cfg.func == func)) {
108                         return (dinfo->cfg.dev);
109                 }
110         }
111
112         return (NULL);
113 }
114
115 device_t
116 pci_find_device(u_int16_t vendor, u_int16_t device)
117 {
118         struct pci_devinfo *dinfo;
119
120         STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
121                 if ((dinfo->cfg.vendor == vendor) &&
122                     (dinfo->cfg.device == device)) {
123                         return (dinfo->cfg.dev);
124                 }
125         }
126
127         return (NULL);
128 }
129
130 /* return base address of memory or port map */
131
132 static u_int32_t
133 pci_mapbase(unsigned mapreg)
134 {
135         int mask = 0x03;
136         if ((mapreg & 0x01) == 0)
137                 mask = 0x0f;
138         return (mapreg & ~mask);
139 }
140
141 /* return map type of memory or port map */
142
143 static int
144 pci_maptype(unsigned mapreg)
145 {
146         static u_int8_t maptype[0x10] = {
147                 PCI_MAPMEM,             PCI_MAPPORT,
148                 PCI_MAPMEM,             0,
149                 PCI_MAPMEM,             PCI_MAPPORT,
150                 0,                      0,
151                 PCI_MAPMEM|PCI_MAPMEMP, PCI_MAPPORT,
152                 PCI_MAPMEM|PCI_MAPMEMP, 0,
153                 PCI_MAPMEM|PCI_MAPMEMP, PCI_MAPPORT,
154                 0,                      0,
155         };
156
157         return maptype[mapreg & 0x0f];
158 }
159
160 /* return log2 of map size decoded for memory or port map */
161
162 static int
163 pci_mapsize(unsigned testval)
164 {
165         int ln2size;
166
167         testval = pci_mapbase(testval);
168         ln2size = 0;
169         if (testval != 0) {
170                 while ((testval & 1) == 0)
171                 {
172                         ln2size++;
173                         testval >>= 1;
174                 }
175         }
176         return (ln2size);
177 }
178
179 /* return log2 of address range supported by map register */
180
181 static int
182 pci_maprange(unsigned mapreg)
183 {
184         int ln2range = 0;
185         switch (mapreg & 0x07) {
186         case 0x00:
187         case 0x01:
188         case 0x05:
189                 ln2range = 32;
190                 break;
191         case 0x02:
192                 ln2range = 20;
193                 break;
194         case 0x04:
195                 ln2range = 64;
196                 break;
197         }
198         return (ln2range);
199 }
200
201 /* adjust some values from PCI 1.0 devices to match 2.0 standards ... */
202
203 static void
204 pci_fixancient(pcicfgregs *cfg)
205 {
206         if (cfg->hdrtype != 0)
207                 return;
208
209         /* PCI to PCI bridges use header type 1 */
210         if (cfg->baseclass == PCIC_BRIDGE && cfg->subclass == PCIS_BRIDGE_PCI)
211                 cfg->hdrtype = 1;
212 }
213
214 /* read config data specific to header type 1 device (PCI to PCI bridge) */
215
216 static void *
217 pci_readppb(device_t pcib, int b, int s, int f)
218 {
219         pcih1cfgregs *p;
220
221         p = kmalloc(sizeof (pcih1cfgregs), M_DEVBUF, M_WAITOK | M_ZERO);
222         if (p == NULL)
223                 return (NULL);
224
225         p->secstat = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_SECSTAT_1, 2);
226         p->bridgectl = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_BRIDGECTL_1, 2);
227
228         p->seclat = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_SECLAT_1, 1);
229
230         p->iobase = PCI_PPBIOBASE (PCIB_READ_CONFIG(pcib, b, s, f,
231                                                     PCIR_IOBASEH_1, 2),
232                                    PCIB_READ_CONFIG(pcib, b, s, f,
233                                                     PCIR_IOBASEL_1, 1));
234         p->iolimit = PCI_PPBIOLIMIT (PCIB_READ_CONFIG(pcib, b, s, f,
235                                                       PCIR_IOLIMITH_1, 2),
236                                      PCIB_READ_CONFIG(pcib, b, s, f,
237                                                       PCIR_IOLIMITL_1, 1));
238
239         p->membase = PCI_PPBMEMBASE (0,
240                                      PCIB_READ_CONFIG(pcib, b, s, f,
241                                                       PCIR_MEMBASE_1, 2));
242         p->memlimit = PCI_PPBMEMLIMIT (0,
243                                        PCIB_READ_CONFIG(pcib, b, s, f,
244                                                         PCIR_MEMLIMIT_1, 2));
245
246         p->pmembase = PCI_PPBMEMBASE (
247                 (pci_addr_t)PCIB_READ_CONFIG(pcib, b, s, f, PCIR_PMBASEH_1, 4),
248                 PCIB_READ_CONFIG(pcib, b, s, f, PCIR_PMBASEL_1, 2));
249
250         p->pmemlimit = PCI_PPBMEMLIMIT (
251                 (pci_addr_t)PCIB_READ_CONFIG(pcib, b, s, f,
252                                              PCIR_PMLIMITH_1, 4),
253                 PCIB_READ_CONFIG(pcib, b, s, f, PCIR_PMLIMITL_1, 2));
254
255         return (p);
256 }
257
258 /* read config data specific to header type 2 device (PCI to CardBus bridge) */
259
260 static void *
261 pci_readpcb(device_t pcib, int b, int s, int f)
262 {
263         pcih2cfgregs *p;
264
265         p = kmalloc(sizeof (pcih2cfgregs), M_DEVBUF, M_WAITOK | M_ZERO);
266         if (p == NULL)
267                 return (NULL);
268
269         p->secstat = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_SECSTAT_2, 2);
270         p->bridgectl = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_BRIDGECTL_2, 2);
271         
272         p->seclat = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_SECLAT_2, 1);
273
274         p->membase0 = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_MEMBASE0_2, 4);
275         p->memlimit0 = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_MEMLIMIT0_2, 4);
276         p->membase1 = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_MEMBASE1_2, 4);
277         p->memlimit1 = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_MEMLIMIT1_2, 4);
278
279         p->iobase0 = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_IOBASE0_2, 4);
280         p->iolimit0 = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_IOLIMIT0_2, 4);
281         p->iobase1 = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_IOBASE1_2, 4);
282         p->iolimit1 = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_IOLIMIT1_2, 4);
283
284         p->pccardif = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_PCCARDIF_2, 4);
285         return p;
286 }
287
288 /* extract header type specific config data */
289
290 static void
291 pci_hdrtypedata(device_t pcib, int b, int s, int f, pcicfgregs *cfg)
292 {
293 #define REG(n,w)        PCIB_READ_CONFIG(pcib, b, s, f, n, w)
294         switch (cfg->hdrtype) {
295         case 0:
296                 cfg->subvendor      = REG(PCIR_SUBVEND_0, 2);
297                 cfg->subdevice      = REG(PCIR_SUBDEV_0, 2);
298                 cfg->nummaps        = PCI_MAXMAPS_0;
299                 break;
300         case 1:
301                 cfg->subvendor      = REG(PCIR_SUBVEND_1, 2);
302                 cfg->subdevice      = REG(PCIR_SUBDEV_1, 2);
303                 cfg->secondarybus   = REG(PCIR_SECBUS_1, 1);
304                 cfg->subordinatebus = REG(PCIR_SUBBUS_1, 1);
305                 cfg->nummaps        = PCI_MAXMAPS_1;
306                 cfg->hdrspec        = pci_readppb(pcib, b, s, f);
307                 break;
308         case 2:
309                 cfg->subvendor      = REG(PCIR_SUBVEND_2, 2);
310                 cfg->subdevice      = REG(PCIR_SUBDEV_2, 2);
311                 cfg->secondarybus   = REG(PCIR_SECBUS_2, 1);
312                 cfg->subordinatebus = REG(PCIR_SUBBUS_2, 1);
313                 cfg->nummaps        = PCI_MAXMAPS_2;
314                 cfg->hdrspec        = pci_readpcb(pcib, b, s, f);
315                 break;
316         }
317 #undef REG
318 }
319
320 /* read configuration header into pcicfgrect structure */
321
322 struct pci_devinfo *
323 pci_read_device(device_t pcib, int b, int s, int f, size_t size)
324 {
325 #define REG(n, w)       PCIB_READ_CONFIG(pcib, b, s, f, n, w)
326
327         pcicfgregs *cfg = NULL;
328         struct pci_devinfo *devlist_entry;
329         struct devlist *devlist_head;
330
331         devlist_head = &pci_devq;
332
333         devlist_entry = NULL;
334
335         if (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_DEVVENDOR, 4) != -1) {
336
337                 devlist_entry = kmalloc(size, M_DEVBUF, M_WAITOK | M_ZERO);
338                 if (devlist_entry == NULL)
339                         return (NULL);
340
341                 cfg = &devlist_entry->cfg;
342                 
343                 cfg->bus                = b;
344                 cfg->slot               = s;
345                 cfg->func               = f;
346                 cfg->vendor             = REG(PCIR_VENDOR, 2);
347                 cfg->device             = REG(PCIR_DEVICE, 2);
348                 cfg->cmdreg             = REG(PCIR_COMMAND, 2);
349                 cfg->statreg            = REG(PCIR_STATUS, 2);
350                 cfg->baseclass          = REG(PCIR_CLASS, 1);
351                 cfg->subclass           = REG(PCIR_SUBCLASS, 1);
352                 cfg->progif             = REG(PCIR_PROGIF, 1);
353                 cfg->revid              = REG(PCIR_REVID, 1);
354                 cfg->hdrtype            = REG(PCIR_HDRTYPE, 1);
355                 cfg->cachelnsz          = REG(PCIR_CACHELNSZ, 1);
356                 cfg->lattimer           = REG(PCIR_LATTIMER, 1);
357                 cfg->intpin             = REG(PCIR_INTPIN, 1);
358                 cfg->intline            = REG(PCIR_INTLINE, 1);
359
360 #ifdef APIC_IO
361                 /*
362                  * If using the APIC the intpin is probably wrong, since it
363                  * is often setup by the BIOS with the PIC in mind.
364                  */
365                 if (cfg->intpin != 0) {
366                         int airq;
367
368                         airq = pci_apic_irq(cfg->bus, cfg->slot, cfg->intpin);
369                         if (airq >= 0) {
370                                 /* PCI specific entry found in MP table */
371                                 if (airq != cfg->intline) {
372                                         undirect_pci_irq(cfg->intline);
373                                         cfg->intline = airq;
374                                 }
375                         } else {
376                                 /* 
377                                  * PCI interrupts might be redirected to the
378                                  * ISA bus according to some MP tables. Use the
379                                  * same methods as used by the ISA devices
380                                  * devices to find the proper IOAPIC int pin.
381                                  */
382                                 airq = isa_apic_irq(cfg->intline);
383                                 if ((airq >= 0) && (airq != cfg->intline)) {
384                                         /* XXX: undirect_pci_irq() ? */
385                                         undirect_isa_irq(cfg->intline);
386                                         cfg->intline = airq;
387                                 }
388                         }
389                 }
390 #endif /* APIC_IO */
391
392                 cfg->mingnt             = REG(PCIR_MINGNT, 1);
393                 cfg->maxlat             = REG(PCIR_MAXLAT, 1);
394
395                 cfg->mfdev              = (cfg->hdrtype & PCIM_MFDEV) != 0;
396                 cfg->hdrtype            &= ~PCIM_MFDEV;
397
398                 pci_fixancient(cfg);
399                 pci_hdrtypedata(pcib, b, s, f, cfg);
400                 pci_read_capabilities(pcib, cfg);
401
402                 STAILQ_INSERT_TAIL(devlist_head, devlist_entry, pci_links);
403
404                 devlist_entry->conf.pc_sel.pc_bus = cfg->bus;
405                 devlist_entry->conf.pc_sel.pc_dev = cfg->slot;
406                 devlist_entry->conf.pc_sel.pc_func = cfg->func;
407                 devlist_entry->conf.pc_hdr = cfg->hdrtype;
408
409                 devlist_entry->conf.pc_subvendor = cfg->subvendor;
410                 devlist_entry->conf.pc_subdevice = cfg->subdevice;
411                 devlist_entry->conf.pc_vendor = cfg->vendor;
412                 devlist_entry->conf.pc_device = cfg->device;
413
414                 devlist_entry->conf.pc_class = cfg->baseclass;
415                 devlist_entry->conf.pc_subclass = cfg->subclass;
416                 devlist_entry->conf.pc_progif = cfg->progif;
417                 devlist_entry->conf.pc_revid = cfg->revid;
418
419                 pci_numdevs++;
420                 pci_generation++;
421         }
422         return (devlist_entry);
423 #undef REG
424 }
425
426 static int
427 pci_fixup_nextptr(int *nextptr0)
428 {
429         int nextptr = *nextptr0;
430
431         /* "Next pointer" is only one byte */
432         KASSERT(nextptr <= 0xff, ("Illegal next pointer %d\n", nextptr));
433
434         if (nextptr & 0x3) {
435                 /*
436                  * PCI local bus spec 3.0:
437                  *
438                  * "... The bottom two bits of all pointers are reserved
439                  *  and must be implemented as 00b although software must
440                  *  mask them to allow for future uses of these bits ..."
441                  */
442                 if (bootverbose) {
443                         kprintf("Illegal PCI extended capability "
444                                 "offset, fixup 0x%02x -> 0x%02x\n",
445                                 nextptr, nextptr & ~0x3);
446                 }
447                 nextptr &= ~0x3;
448         }
449         *nextptr0 = nextptr;
450
451         if (nextptr < 0x40) {
452                 if (nextptr != 0) {
453                         kprintf("Illegal PCI extended capability "
454                                 "offset 0x%02x", nextptr);
455                 }
456                 return 0;
457         }
458         return 1;
459 }
460
461 static void
462 pci_read_cap_pmgt(device_t pcib, int ptr, pcicfgregs *cfg)
463 {
464 #define REG(n, w)       \
465         PCIB_READ_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, n, w)
466
467         struct pcicfg_pmgt *pmgt = &cfg->pmgt;
468
469         if (pmgt->pp_cap)
470                 return;
471
472         pmgt->pp_cap = REG(ptr + PCIR_POWER_CAP, 2);
473         pmgt->pp_status = ptr + PCIR_POWER_STATUS;
474         pmgt->pp_pmcsr = ptr + PCIR_POWER_PMCSR;
475         /*
476          * XXX
477          * Following way may be used to to test whether
478          * 'data' register exists:
479          * if 'data_select' register of
480          * PCIR_POWER_STATUS(bits[12,9]) is read-only
481          * then 'data' register is _not_ implemented.
482          */
483         pmgt->pp_data = 0;
484
485 #undef REG
486 }
487
488 static void
489 pci_read_capabilities(device_t pcib, pcicfgregs *cfg)
490 {
491 #define REG(n, w)       \
492         PCIB_READ_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, n, w)
493
494         int nextptr, ptrptr;
495
496         if ((REG(PCIR_STATUS, 2) & PCIM_STATUS_CAPPRESENT) == 0) {
497                 /* No capabilities */
498                 return;
499         }
500
501         switch (cfg->hdrtype) {
502         case 0:
503         case 1:
504                 ptrptr = PCIR_CAP_PTR;
505                 break;
506         case 2:
507                 ptrptr = PCIR_CAP_PTR_2;
508                 break;
509         default:
510                 return;         /* No capabilities support */
511         }
512         nextptr = REG(ptrptr, 1);
513
514         /*
515          * Read capability entries.
516          */
517         while (pci_fixup_nextptr(&nextptr)) {
518                 int ptr = nextptr;
519
520                 /* Process this entry */
521                 switch (REG(ptr, 1)) {
522                 case PCIY_PMG:          /* PCI power management */
523                         pci_read_cap_pmgt(pcib, ptr, cfg);
524                         break;
525                 default:
526                         break;
527                 }
528
529                 /* Find the next entry */
530                 nextptr = REG(ptr + 1, 1);
531         }
532
533 #undef REG
534 }
535
536 /* free pcicfgregs structure and all depending data structures */
537
538 int
539 pci_freecfg(struct pci_devinfo *dinfo)
540 {
541         struct devlist *devlist_head;
542
543         devlist_head = &pci_devq;
544
545         if (dinfo->cfg.hdrspec != NULL)
546                 kfree(dinfo->cfg.hdrspec, M_DEVBUF);
547         /* XXX this hasn't been tested */
548         STAILQ_REMOVE(devlist_head, dinfo, pci_devinfo, pci_links);
549         kfree(dinfo, M_DEVBUF);
550
551         /* increment the generation count */
552         pci_generation++;
553
554         /* we're losing one device */
555         pci_numdevs--;
556         return (0);
557 }
558
559
560 /*
561  * PCI power manangement
562  */
563 int
564 pci_set_powerstate_method(device_t dev, device_t child, int state)
565 {
566         struct pci_devinfo *dinfo = device_get_ivars(child);
567         pcicfgregs *cfg = &dinfo->cfg;
568         struct pcicfg_pmgt *pmgt = &cfg->pmgt;
569         u_int16_t status;
570         int result;
571
572         if (pmgt->pp_cap != 0) {
573                 status = PCI_READ_CONFIG(dev, child, pmgt->pp_status, 2) & ~PCIM_PSTAT_DMASK;
574                 result = 0;
575                 switch (state) {
576                 case PCI_POWERSTATE_D0:
577                         status |= PCIM_PSTAT_D0;
578                         break;
579                 case PCI_POWERSTATE_D1:
580                         if (pmgt->pp_cap & PCIM_PCAP_D1SUPP) {
581                                 status |= PCIM_PSTAT_D1;
582                         } else {
583                                 result = EOPNOTSUPP;
584                         }
585                         break;
586                 case PCI_POWERSTATE_D2:
587                         if (pmgt->pp_cap & PCIM_PCAP_D2SUPP) {
588                                 status |= PCIM_PSTAT_D2;
589                         } else {
590                                 result = EOPNOTSUPP;
591                         }
592                         break;
593                 case PCI_POWERSTATE_D3:
594                         status |= PCIM_PSTAT_D3;
595                         break;
596                 default:
597                         result = EINVAL;
598                 }
599                 if (result == 0)
600                         PCI_WRITE_CONFIG(dev, child, pmgt->pp_status, status, 2);
601         } else {
602                 result = ENXIO;
603         }
604         return(result);
605 }
606
607 int
608 pci_get_powerstate_method(device_t dev, device_t child)
609 {
610         struct pci_devinfo *dinfo = device_get_ivars(child);
611         pcicfgregs *cfg = &dinfo->cfg;
612         struct pcicfg_pmgt *pmgt = &cfg->pmgt;
613         u_int16_t status;
614         int result;
615
616         if (pmgt->pp_cap != 0) {
617                 status = PCI_READ_CONFIG(dev, child, pmgt->pp_status, 2);
618                 switch (status & PCIM_PSTAT_DMASK) {
619                 case PCIM_PSTAT_D0:
620                         result = PCI_POWERSTATE_D0;
621                         break;
622                 case PCIM_PSTAT_D1:
623                         result = PCI_POWERSTATE_D1;
624                         break;
625                 case PCIM_PSTAT_D2:
626                         result = PCI_POWERSTATE_D2;
627                         break;
628                 case PCIM_PSTAT_D3:
629                         result = PCI_POWERSTATE_D3;
630                         break;
631                 default:
632                         result = PCI_POWERSTATE_UNKNOWN;
633                         break;
634                 }
635         } else {
636                 /* No support, device is always at D0 */
637                 result = PCI_POWERSTATE_D0;
638         }
639         return(result);
640 }
641
642 /*
643  * Some convenience functions for PCI device drivers.
644  */
645
646 static __inline void
647 pci_set_command_bit(device_t dev, device_t child, u_int16_t bit)
648 {
649     u_int16_t   command;
650
651     command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
652     command |= bit;
653     PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
654 }
655
656 static __inline void
657 pci_clear_command_bit(device_t dev, device_t child, u_int16_t bit)
658 {
659     u_int16_t   command;
660
661     command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
662     command &= ~bit;
663     PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
664 }
665
666 int
667 pci_enable_busmaster_method(device_t dev, device_t child)
668 {
669     pci_set_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
670     return(0);
671 }
672
673 int
674 pci_disable_busmaster_method(device_t dev, device_t child)
675 {
676     pci_clear_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
677     return(0);
678 }
679
680 int
681 pci_enable_io_method(device_t dev, device_t child, int space)
682 {
683     uint16_t command;
684     uint16_t bit;
685     char *error;
686
687     bit = 0;
688     error = NULL;
689
690     switch(space) {
691     case SYS_RES_IOPORT:
692         bit = PCIM_CMD_PORTEN;
693         error = "port";
694         break;
695     case SYS_RES_MEMORY:
696         bit = PCIM_CMD_MEMEN;
697         error = "memory";
698         break;
699     default:
700         return(EINVAL);
701     }
702     pci_set_command_bit(dev, child, bit);
703     command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
704     if (command & bit)
705         return(0);
706     device_printf(child, "failed to enable %s mapping!\n", error);
707     return(ENXIO);
708 }
709
710 int
711 pci_disable_io_method(device_t dev, device_t child, int space)
712 {
713     uint16_t command;
714     uint16_t bit;
715     char *error;
716
717     bit = 0;
718     error = NULL;
719
720     switch(space) {
721     case SYS_RES_IOPORT:
722         bit = PCIM_CMD_PORTEN;
723         error = "port";
724         break;
725     case SYS_RES_MEMORY:
726         bit = PCIM_CMD_MEMEN;
727         error = "memory";
728         break;
729     default:
730         return (EINVAL);
731     }
732     pci_clear_command_bit(dev, child, bit);
733     command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
734     if (command & bit) {
735         device_printf(child, "failed to disable %s mapping!\n", error);
736         return (ENXIO);
737     }
738     return (0);
739 }
740
741 /*
742  * This is the user interface to PCI configuration space.
743  */
744   
745 static int
746 pci_open(struct dev_open_args *ap)
747 {
748         if ((ap->a_oflags & FWRITE) && securelevel > 0) {
749                 return EPERM;
750         }
751         return 0;
752 }
753
754 static int
755 pci_close(struct dev_close_args *ap)
756 {
757         return 0;
758 }
759
760 /*
761  * Match a single pci_conf structure against an array of pci_match_conf
762  * structures.  The first argument, 'matches', is an array of num_matches
763  * pci_match_conf structures.  match_buf is a pointer to the pci_conf
764  * structure that will be compared to every entry in the matches array.
765  * This function returns 1 on failure, 0 on success.
766  */
767 static int
768 pci_conf_match(struct pci_match_conf *matches, int num_matches, 
769                struct pci_conf *match_buf)
770 {
771         int i;
772
773         if ((matches == NULL) || (match_buf == NULL) || (num_matches <= 0))
774                 return(1);
775
776         for (i = 0; i < num_matches; i++) {
777                 /*
778                  * I'm not sure why someone would do this...but...
779                  */
780                 if (matches[i].flags == PCI_GETCONF_NO_MATCH)
781                         continue;
782
783                 /*
784                  * Look at each of the match flags.  If it's set, do the
785                  * comparison.  If the comparison fails, we don't have a
786                  * match, go on to the next item if there is one.
787                  */
788                 if (((matches[i].flags & PCI_GETCONF_MATCH_BUS) != 0)
789                  && (match_buf->pc_sel.pc_bus != matches[i].pc_sel.pc_bus))
790                         continue;
791
792                 if (((matches[i].flags & PCI_GETCONF_MATCH_DEV) != 0)
793                  && (match_buf->pc_sel.pc_dev != matches[i].pc_sel.pc_dev))
794                         continue;
795
796                 if (((matches[i].flags & PCI_GETCONF_MATCH_FUNC) != 0)
797                  && (match_buf->pc_sel.pc_func != matches[i].pc_sel.pc_func))
798                         continue;
799
800                 if (((matches[i].flags & PCI_GETCONF_MATCH_VENDOR) != 0) 
801                  && (match_buf->pc_vendor != matches[i].pc_vendor))
802                         continue;
803
804                 if (((matches[i].flags & PCI_GETCONF_MATCH_DEVICE) != 0)
805                  && (match_buf->pc_device != matches[i].pc_device))
806                         continue;
807
808                 if (((matches[i].flags & PCI_GETCONF_MATCH_CLASS) != 0)
809                  && (match_buf->pc_class != matches[i].pc_class))
810                         continue;
811
812                 if (((matches[i].flags & PCI_GETCONF_MATCH_UNIT) != 0)
813                  && (match_buf->pd_unit != matches[i].pd_unit))
814                         continue;
815
816                 if (((matches[i].flags & PCI_GETCONF_MATCH_NAME) != 0)
817                  && (strncmp(matches[i].pd_name, match_buf->pd_name,
818                              sizeof(match_buf->pd_name)) != 0))
819                         continue;
820
821                 return(0);
822         }
823
824         return(1);
825 }
826
827 /*
828  * Locate the parent of a PCI device by scanning the PCI devlist
829  * and return the entry for the parent.
830  * For devices on PCI Bus 0 (the host bus), this is the PCI Host.
831  * For devices on secondary PCI busses, this is that bus' PCI-PCI Bridge.
832  */
833
834 pcicfgregs *
835 pci_devlist_get_parent(pcicfgregs *cfg)
836 {
837         struct devlist *devlist_head;
838         struct pci_devinfo *dinfo;
839         pcicfgregs *bridge_cfg;
840         int i;
841
842         dinfo = STAILQ_FIRST(devlist_head = &pci_devq);
843
844         /* If the device is on PCI bus 0, look for the host */
845         if (cfg->bus == 0) {
846                 for (i = 0; (dinfo != NULL) && (i < pci_numdevs);
847                 dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {
848                         bridge_cfg = &dinfo->cfg;
849                         if (bridge_cfg->baseclass == PCIC_BRIDGE
850                                 && bridge_cfg->subclass == PCIS_BRIDGE_HOST
851                                 && bridge_cfg->bus == cfg->bus) {
852                                 return bridge_cfg;
853                         }
854                 }
855         }
856
857         /* If the device is not on PCI bus 0, look for the PCI-PCI bridge */
858         if (cfg->bus > 0) {
859                 for (i = 0; (dinfo != NULL) && (i < pci_numdevs);
860                 dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {
861                         bridge_cfg = &dinfo->cfg;
862                         if (bridge_cfg->baseclass == PCIC_BRIDGE
863                                 && bridge_cfg->subclass == PCIS_BRIDGE_PCI
864                                 && bridge_cfg->secondarybus == cfg->bus) {
865                                 return bridge_cfg;
866                         }
867                 }
868         }
869
870         return NULL; 
871 }
872
873 static int
874 pci_ioctl(struct dev_ioctl_args *ap)
875 {
876         device_t pci, pcib;
877         struct pci_io *io;
878         const char *name;
879         int error;
880
881         if (!(ap->a_fflag & FWRITE))
882                 return EPERM;
883
884         switch(ap->a_cmd) {
885         case PCIOCGETCONF:
886                 {
887                 struct pci_devinfo *dinfo;
888                 struct pci_conf_io *cio;
889                 struct devlist *devlist_head;
890                 struct pci_match_conf *pattern_buf;
891                 int num_patterns;
892                 size_t iolen;
893                 int ionum, i;
894
895                 cio = (struct pci_conf_io *)ap->a_data;
896
897                 num_patterns = 0;
898                 dinfo = NULL;
899
900                 /*
901                  * Hopefully the user won't pass in a null pointer, but it
902                  * can't hurt to check.
903                  */
904                 if (cio == NULL) {
905                         error = EINVAL;
906                         break;
907                 }
908
909                 /*
910                  * If the user specified an offset into the device list,
911                  * but the list has changed since they last called this
912                  * ioctl, tell them that the list has changed.  They will
913                  * have to get the list from the beginning.
914                  */
915                 if ((cio->offset != 0)
916                  && (cio->generation != pci_generation)){
917                         cio->num_matches = 0;   
918                         cio->status = PCI_GETCONF_LIST_CHANGED;
919                         error = 0;
920                         break;
921                 }
922
923                 /*
924                  * Check to see whether the user has asked for an offset
925                  * past the end of our list.
926                  */
927                 if (cio->offset >= pci_numdevs) {
928                         cio->num_matches = 0;
929                         cio->status = PCI_GETCONF_LAST_DEVICE;
930                         error = 0;
931                         break;
932                 }
933
934                 /* get the head of the device queue */
935                 devlist_head = &pci_devq;
936
937                 /*
938                  * Determine how much room we have for pci_conf structures.
939                  * Round the user's buffer size down to the nearest
940                  * multiple of sizeof(struct pci_conf) in case the user
941                  * didn't specify a multiple of that size.
942                  */
943                 iolen = min(cio->match_buf_len - 
944                             (cio->match_buf_len % sizeof(struct pci_conf)),
945                             pci_numdevs * sizeof(struct pci_conf));
946
947                 /*
948                  * Since we know that iolen is a multiple of the size of
949                  * the pciconf union, it's okay to do this.
950                  */
951                 ionum = iolen / sizeof(struct pci_conf);
952
953                 /*
954                  * If this test is true, the user wants the pci_conf
955                  * structures returned to match the supplied entries.
956                  */
957                 if ((cio->num_patterns > 0)
958                  && (cio->pat_buf_len > 0)) {
959                         /*
960                          * pat_buf_len needs to be:
961                          * num_patterns * sizeof(struct pci_match_conf)
962                          * While it is certainly possible the user just
963                          * allocated a large buffer, but set the number of
964                          * matches correctly, it is far more likely that
965                          * their kernel doesn't match the userland utility
966                          * they're using.  It's also possible that the user
967                          * forgot to initialize some variables.  Yes, this
968                          * may be overly picky, but I hazard to guess that
969                          * it's far more likely to just catch folks that
970                          * updated their kernel but not their userland.
971                          */
972                         if ((cio->num_patterns *
973                             sizeof(struct pci_match_conf)) != cio->pat_buf_len){
974                                 /* The user made a mistake, return an error*/
975                                 cio->status = PCI_GETCONF_ERROR;
976                                 kprintf("pci_ioctl: pat_buf_len %d != "
977                                        "num_patterns (%d) * sizeof(struct "
978                                        "pci_match_conf) (%d)\npci_ioctl: "
979                                        "pat_buf_len should be = %d\n",
980                                        cio->pat_buf_len, cio->num_patterns,
981                                        (int)sizeof(struct pci_match_conf),
982                                        (int)sizeof(struct pci_match_conf) * 
983                                        cio->num_patterns);
984                                 kprintf("pci_ioctl: do your headers match your "
985                                        "kernel?\n");
986                                 cio->num_matches = 0;
987                                 error = EINVAL;
988                                 break;
989                         }
990
991                         /*
992                          * Check the user's buffer to make sure it's readable.
993                          */
994                         if (!useracc((caddr_t)cio->patterns,
995                                     cio->pat_buf_len, VM_PROT_READ)) {
996                                 kprintf("pci_ioctl: pattern buffer %p, "
997                                        "length %u isn't user accessible for"
998                                        " READ\n", cio->patterns,
999                                        cio->pat_buf_len);
1000                                 error = EACCES;
1001                                 break;
1002                         }
1003                         /*
1004                          * Allocate a buffer to hold the patterns.
1005                          */
1006                         pattern_buf = kmalloc(cio->pat_buf_len, M_TEMP,
1007                                              M_WAITOK);
1008                         error = copyin(cio->patterns, pattern_buf,
1009                                        cio->pat_buf_len);
1010                         if (error != 0)
1011                                 break;
1012                         num_patterns = cio->num_patterns;
1013
1014                 } else if ((cio->num_patterns > 0)
1015                         || (cio->pat_buf_len > 0)) {
1016                         /*
1017                          * The user made a mistake, spit out an error.
1018                          */
1019                         cio->status = PCI_GETCONF_ERROR;
1020                         cio->num_matches = 0;
1021                         kprintf("pci_ioctl: invalid GETCONF arguments\n");
1022                         error = EINVAL;
1023                         break;
1024                 } else
1025                         pattern_buf = NULL;
1026
1027                 /*
1028                  * Make sure we can write to the match buffer.
1029                  */
1030                 if (!useracc((caddr_t)cio->matches,
1031                              cio->match_buf_len, VM_PROT_WRITE)) {
1032                         kprintf("pci_ioctl: match buffer %p, length %u "
1033                                "isn't user accessible for WRITE\n",
1034                                cio->matches, cio->match_buf_len);
1035                         error = EACCES;
1036                         break;
1037                 }
1038
1039                 /*
1040                  * Go through the list of devices and copy out the devices
1041                  * that match the user's criteria.
1042                  */
1043                 for (cio->num_matches = 0, error = 0, i = 0,
1044                      dinfo = STAILQ_FIRST(devlist_head);
1045                      (dinfo != NULL) && (cio->num_matches < ionum)
1046                      && (error == 0) && (i < pci_numdevs);
1047                      dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {
1048
1049                         if (i < cio->offset)
1050                                 continue;
1051
1052                         /* Populate pd_name and pd_unit */
1053                         name = NULL;
1054                         if (dinfo->cfg.dev && dinfo->conf.pd_name[0] == '\0')
1055                                 name = device_get_name(dinfo->cfg.dev);
1056                         if (name) {
1057                                 strncpy(dinfo->conf.pd_name, name,
1058                                         sizeof(dinfo->conf.pd_name));
1059                                 dinfo->conf.pd_name[PCI_MAXNAMELEN] = 0;
1060                                 dinfo->conf.pd_unit =
1061                                         device_get_unit(dinfo->cfg.dev);
1062                         }
1063
1064                         if ((pattern_buf == NULL) ||
1065                             (pci_conf_match(pattern_buf, num_patterns,
1066                                             &dinfo->conf) == 0)) {
1067
1068                                 /*
1069                                  * If we've filled up the user's buffer,
1070                                  * break out at this point.  Since we've
1071                                  * got a match here, we'll pick right back
1072                                  * up at the matching entry.  We can also
1073                                  * tell the user that there are more matches
1074                                  * left.
1075                                  */
1076                                 if (cio->num_matches >= ionum)
1077                                         break;
1078
1079                                 error = copyout(&dinfo->conf,
1080                                                 &cio->matches[cio->num_matches],
1081                                                 sizeof(struct pci_conf));
1082                                 cio->num_matches++;
1083                         }
1084                 }
1085
1086                 /*
1087                  * Set the pointer into the list, so if the user is getting
1088                  * n records at a time, where n < pci_numdevs,
1089                  */
1090                 cio->offset = i;
1091
1092                 /*
1093                  * Set the generation, the user will need this if they make
1094                  * another ioctl call with offset != 0.
1095                  */
1096                 cio->generation = pci_generation;
1097                 
1098                 /*
1099                  * If this is the last device, inform the user so he won't
1100                  * bother asking for more devices.  If dinfo isn't NULL, we
1101                  * know that there are more matches in the list because of
1102                  * the way the traversal is done.
1103                  */
1104                 if (dinfo == NULL)
1105                         cio->status = PCI_GETCONF_LAST_DEVICE;
1106                 else
1107                         cio->status = PCI_GETCONF_MORE_DEVS;
1108
1109                 if (pattern_buf != NULL)
1110                         kfree(pattern_buf, M_TEMP);
1111
1112                 break;
1113                 }
1114         case PCIOCREAD:
1115                 io = (struct pci_io *)ap->a_data;
1116                 switch(io->pi_width) {
1117                 case 4:
1118                 case 2:
1119                 case 1:
1120                         /*
1121                          * Assume that the user-level bus number is
1122                          * actually the pciN instance number. We map
1123                          * from that to the real pcib+bus combination.
1124                          */
1125                         pci = devclass_get_device(pci_devclass,
1126                                                   io->pi_sel.pc_bus);
1127                         if (pci) {
1128                                 /*
1129                                  * pci is the pci device and may contain
1130                                  * several children (for each function code).
1131                                  * The governing pci bus is the parent to
1132                                  * the pci device.
1133                                  */
1134                                 int b;
1135
1136                                 pcib = device_get_parent(pci);
1137                                 b = pcib_get_bus(pcib);
1138                                 io->pi_data = 
1139                                         PCIB_READ_CONFIG(pcib,
1140                                                          b,
1141                                                          io->pi_sel.pc_dev,
1142                                                          io->pi_sel.pc_func,
1143                                                          io->pi_reg,
1144                                                          io->pi_width);
1145                                 error = 0;
1146                         } else {
1147                                 error = ENODEV;
1148                         }
1149                         break;
1150                 default:
1151                         error = ENODEV;
1152                         break;
1153                 }
1154                 break;
1155
1156         case PCIOCWRITE:
1157                 io = (struct pci_io *)ap->a_data;
1158                 switch(io->pi_width) {
1159                 case 4:
1160                 case 2:
1161                 case 1:
1162                         /*
1163                          * Assume that the user-level bus number is
1164                          * actually the pciN instance number. We map
1165                          * from that to the real pcib+bus combination.
1166                          */
1167                         pci = devclass_get_device(pci_devclass,
1168                                                   io->pi_sel.pc_bus);
1169                         if (pci) {
1170                                 /*
1171                                  * pci is the pci device and may contain
1172                                  * several children (for each function code).
1173                                  * The governing pci bus is the parent to
1174                                  * the pci device.
1175                                  */
1176                                 int b;
1177
1178                                 pcib = device_get_parent(pci);
1179                                 b = pcib_get_bus(pcib);
1180                                 PCIB_WRITE_CONFIG(pcib,
1181                                                   b,
1182                                                   io->pi_sel.pc_dev,
1183                                                   io->pi_sel.pc_func,
1184                                                   io->pi_reg,
1185                                                   io->pi_data,
1186                                                   io->pi_width);
1187                                 error = 0;
1188                         } else {
1189                                 error = ENODEV;
1190                         }
1191                         break;
1192                 default:
1193                         error = ENODEV;
1194                         break;
1195                 }
1196                 break;
1197
1198         default:
1199                 error = ENOTTY;
1200                 break;
1201         }
1202
1203         return (error);
1204 }
1205
1206 #define PCI_CDEV        78
1207
1208 static struct dev_ops pcic_ops = {
1209         { "pci", PCI_CDEV, 0 },
1210         .d_open =       pci_open,
1211         .d_close =      pci_close,
1212         .d_ioctl =      pci_ioctl,
1213 };
1214
1215 #include "pci_if.h"
1216
1217 /*
1218  * New style pci driver.  Parent device is either a pci-host-bridge or a
1219  * pci-pci-bridge.  Both kinds are represented by instances of pcib.
1220  */
1221 const char *
1222 pci_class_to_string(int baseclass)
1223 {
1224         const char *name;
1225
1226         switch(baseclass) {
1227         case PCIC_OLD:
1228                 name = "OLD";
1229                 break;
1230         case PCIC_STORAGE:
1231                 name = "STORAGE";
1232                 break;
1233         case PCIC_NETWORK:
1234                 name = "NETWORK";
1235                 break;
1236         case PCIC_DISPLAY:
1237                 name = "DISPLAY";
1238                 break;
1239         case PCIC_MULTIMEDIA:
1240                 name = "MULTIMEDIA";
1241                 break;
1242         case PCIC_MEMORY:
1243                 name = "MEMORY";
1244                 break;
1245         case PCIC_BRIDGE:
1246                 name = "BRIDGE";
1247                 break;
1248         case PCIC_SIMPLECOMM:
1249                 name = "SIMPLECOMM";
1250                 break;
1251         case PCIC_BASEPERIPH:
1252                 name = "BASEPERIPH";
1253                 break;
1254         case PCIC_INPUTDEV:
1255                 name = "INPUTDEV";
1256                 break;
1257         case PCIC_DOCKING:
1258                 name = "DOCKING";
1259                 break;
1260         case PCIC_PROCESSOR:
1261                 name = "PROCESSOR";
1262                 break;
1263         case PCIC_SERIALBUS:
1264                 name = "SERIALBUS";
1265                 break;
1266         case PCIC_WIRELESS:
1267                 name = "WIRELESS";
1268                 break;
1269         case PCIC_I2O:
1270                 name = "I20";
1271                 break;
1272         case PCIC_SATELLITE:
1273                 name = "SATELLITE";
1274                 break;
1275         case PCIC_CRYPTO:
1276                 name = "CRYPTO";
1277                 break;
1278         case PCIC_SIGPROC:
1279                 name = "SIGPROC";
1280                 break;
1281         case PCIC_OTHER:
1282                 name = "OTHER";
1283                 break;
1284         default:
1285                 name = "?";
1286                 break;
1287         }
1288         return(name);
1289 }
1290
1291 void
1292 pci_print_verbose(struct pci_devinfo *dinfo)
1293 {
1294         if (bootverbose) {
1295                 pcicfgregs *cfg = &dinfo->cfg;
1296
1297                 kprintf("found->\tvendor=0x%04x, dev=0x%04x, revid=0x%02x\n", 
1298                        cfg->vendor, cfg->device, cfg->revid);
1299                 kprintf("\tbus=%d, slot=%d, func=%d\n",
1300                        cfg->bus, cfg->slot, cfg->func);
1301                 kprintf("\tclass=[%s]%02x-%02x-%02x, hdrtype=0x%02x, mfdev=%d\n",
1302                        pci_class_to_string(cfg->baseclass),
1303                        cfg->baseclass, cfg->subclass, cfg->progif,
1304                        cfg->hdrtype, cfg->mfdev);
1305                 kprintf("\tsubordinatebus=%x \tsecondarybus=%x\n",
1306                        cfg->subordinatebus, cfg->secondarybus);
1307 #ifdef PCI_DEBUG
1308                 kprintf("\tcmdreg=0x%04x, statreg=0x%04x, cachelnsz=%d (dwords)\n", 
1309                        cfg->cmdreg, cfg->statreg, cfg->cachelnsz);
1310                 kprintf("\tlattimer=0x%02x (%d ns), mingnt=0x%02x (%d ns), maxlat=0x%02x (%d ns)\n",
1311                        cfg->lattimer, cfg->lattimer * 30, 
1312                        cfg->mingnt, cfg->mingnt * 250, cfg->maxlat, cfg->maxlat * 250);
1313 #endif /* PCI_DEBUG */
1314                 if (cfg->intpin > 0)
1315                         kprintf("\tintpin=%c, irq=%d\n", cfg->intpin +'a' -1, cfg->intline);
1316         }
1317 }
1318
1319 static int
1320 pci_porten(device_t pcib, int b, int s, int f)
1321 {
1322         return (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2)
1323                 & PCIM_CMD_PORTEN) != 0;
1324 }
1325
1326 static int
1327 pci_memen(device_t pcib, int b, int s, int f)
1328 {
1329         return (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2)
1330                 & PCIM_CMD_MEMEN) != 0;
1331 }
1332
1333 /*
1334  * Add a resource based on a pci map register. Return 1 if the map
1335  * register is a 32bit map register or 2 if it is a 64bit register.
1336  */
1337 static int
1338 pci_add_map(device_t pcib, int b, int s, int f, int reg,
1339             struct resource_list *rl)
1340 {
1341         u_int32_t map;
1342         u_int64_t base;
1343         u_int8_t ln2size;
1344         u_int8_t ln2range;
1345         u_int32_t testval;
1346
1347
1348 #ifdef PCI_ENABLE_IO_MODES
1349         u_int16_t cmd;
1350 #endif          
1351         int type;
1352
1353         map = PCIB_READ_CONFIG(pcib, b, s, f, reg, 4);
1354
1355         if (map == 0 || map == 0xffffffff)
1356                 return 1; /* skip invalid entry */
1357
1358         PCIB_WRITE_CONFIG(pcib, b, s, f, reg, 0xffffffff, 4);
1359         testval = PCIB_READ_CONFIG(pcib, b, s, f, reg, 4);
1360         PCIB_WRITE_CONFIG(pcib, b, s, f, reg, map, 4);
1361
1362         base = pci_mapbase(map);
1363         if (pci_maptype(map) & PCI_MAPMEM)
1364                 type = SYS_RES_MEMORY;
1365         else
1366                 type = SYS_RES_IOPORT;
1367         ln2size = pci_mapsize(testval);
1368         ln2range = pci_maprange(testval);
1369         if (ln2range == 64) {
1370                 /* Read the other half of a 64bit map register */
1371                 base |= (u_int64_t) PCIB_READ_CONFIG(pcib, b, s, f, reg+4, 4);
1372         }
1373
1374         /*
1375          * This code theoretically does the right thing, but has
1376          * undesirable side effects in some cases where
1377          * peripherals respond oddly to having these bits
1378          * enabled.  Leave them alone by default.
1379          */
1380 #ifdef PCI_ENABLE_IO_MODES
1381         if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f)) {
1382                 cmd = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2);
1383                 cmd |= PCIM_CMD_PORTEN;
1384                 PCIB_WRITE_CONFIG(pcib, b, s, f, PCIR_COMMAND, cmd, 2);
1385         }
1386         if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f)) {
1387                 cmd = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2);
1388                 cmd |= PCIM_CMD_MEMEN;
1389                 PCIB_WRITE_CONFIG(pcib, b, s, f, PCIR_COMMAND, cmd, 2);
1390         }
1391 #else
1392         if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f))
1393                 return 1;
1394         if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f))
1395                 return 1;
1396 #endif
1397
1398         resource_list_add(rl, type, reg,
1399                           base, base + (1 << ln2size) - 1,
1400                           (1 << ln2size));
1401
1402         if (bootverbose) {
1403                 kprintf("\tmap[%02x]: type %x, range %2d, base %08x, size %2d\n",
1404                        reg, pci_maptype(base), ln2range,
1405                        (unsigned int) base, ln2size);
1406         }
1407
1408         return (ln2range == 64) ? 2 : 1;
1409 }
1410
1411 #ifdef PCI_MAP_FIXUP
1412 /*
1413  * For ATA devices we need to decide early on what addressing mode to use.
1414  * Legacy demands that the primary and secondary ATA ports sits on the
1415  * same addresses that old ISA hardware did. This dictates that we use
1416  * those addresses and ignore the BARs if we cannot set PCI native
1417  * addressing mode.
1418  */
1419 static void
1420 pci_ata_maps(device_t pcib, device_t bus, device_t dev, int b, int s, int f,
1421              struct resource_list *rl)
1422 {
1423         int rid, type, progif;
1424 #if 0
1425         /* if this device supports PCI native addressing use it */
1426         progif = pci_read_config(dev, PCIR_PROGIF, 1);
1427         if ((progif &0x8a) == 0x8a) {
1428                 if (pci_mapbase(pci_read_config(dev, PCIR_BAR(0), 4)) &&
1429                     pci_mapbase(pci_read_config(dev, PCIR_BAR(2), 4))) {
1430                         kprintf("Trying ATA native PCI addressing mode\n");
1431                         pci_write_config(dev, PCIR_PROGIF, progif | 0x05, 1);
1432                 }
1433         }
1434 #endif
1435         /*
1436          * Because we return any preallocated resources for lazy
1437          * allocation for PCI devices in pci_alloc_resource(), we can
1438          * allocate our legacy resources here.
1439          */
1440         progif = pci_read_config(dev, PCIR_PROGIF, 1);
1441         type = SYS_RES_IOPORT;
1442         if (progif & PCIP_STORAGE_IDE_MODEPRIM) {
1443                 pci_add_map(pcib, b, s, f, PCIR_BAR(0), rl);
1444                 pci_add_map(pcib, b, s, f, PCIR_BAR(1), rl);
1445         } else {
1446                 rid = PCIR_BAR(0);
1447                 resource_list_add(rl, type, rid, 0x1f0, 0x1f7, 8);
1448                 resource_list_alloc(rl, bus, dev, type, &rid, 0x1f0, 0x1f7, 8,
1449                                     0);
1450                 rid = PCIR_BAR(1);
1451                 resource_list_add(rl, type, rid, 0x3f6, 0x3f6, 1);
1452                 resource_list_alloc(rl, bus, dev, type, &rid, 0x3f6, 0x3f6, 1,
1453                                     0);
1454         }
1455         if (progif & PCIP_STORAGE_IDE_MODESEC) {
1456                 pci_add_map(pcib, b, s, f, PCIR_BAR(2), rl);
1457                 pci_add_map(pcib, b, s, f, PCIR_BAR(3), rl);
1458         } else {
1459                 rid = PCIR_BAR(2);
1460                 resource_list_add(rl, type, rid, 0x170, 0x177, 8);
1461                 resource_list_alloc(rl, bus, dev, type, &rid, 0x170, 0x177, 8,
1462                                     0);
1463                 rid = PCIR_BAR(3);
1464                 resource_list_add(rl, type, rid, 0x376, 0x376, 1);
1465                 resource_list_alloc(rl, bus, dev, type, &rid, 0x376, 0x376, 1,
1466                                     0);
1467         }
1468         pci_add_map(pcib, b, s, f, PCIR_BAR(4), rl);
1469         pci_add_map(pcib, b, s, f, PCIR_BAR(5), rl);
1470 }
1471 #endif /* PCI_MAP_FIXUP */
1472
1473 static void
1474 pci_add_resources(device_t pcib, device_t bus, device_t dev)
1475 {
1476         struct pci_devinfo *dinfo = device_get_ivars(dev);
1477         pcicfgregs *cfg = &dinfo->cfg;
1478         struct resource_list *rl = &dinfo->resources;
1479         struct pci_quirk *q;
1480         int b, i, f, s;
1481 #if 0   /* WILL BE USED WITH ADDITIONAL IMPORT FROM FREEBSD-5 XXX */
1482         int irq;
1483 #endif
1484
1485         b = cfg->bus;
1486         s = cfg->slot;
1487         f = cfg->func;
1488 #ifdef PCI_MAP_FIXUP
1489         /* atapci devices in legacy mode need special map treatment */
1490         if ((pci_get_class(dev) == PCIC_STORAGE) &&
1491             (pci_get_subclass(dev) == PCIS_STORAGE_IDE) &&
1492             ((pci_get_progif(dev) & PCIP_STORAGE_IDE_MASTERDEV) ||
1493              (!pci_read_config(dev, PCIR_BAR(0), 4) &&
1494               !pci_read_config(dev, PCIR_BAR(2), 4))) )
1495                 pci_ata_maps(pcib, bus, dev, b, s, f, rl);
1496         else
1497 #endif /* PCI_MAP_FIXUP */
1498                 for (i = 0; i < cfg->nummaps;) {
1499                         i += pci_add_map(pcib, b, s, f, PCIR_BAR(i),rl);
1500                 }
1501
1502         for (q = &pci_quirks[0]; q->devid; q++) {
1503                 if (q->devid == ((cfg->device << 16) | cfg->vendor)
1504                     && q->type == PCI_QUIRK_MAP_REG)
1505                         pci_add_map(pcib, b, s, f, q->arg1, rl);
1506         }
1507
1508         if (cfg->intpin > 0 && cfg->intline != 255)
1509                 resource_list_add(rl, SYS_RES_IRQ, 0,
1510                                   cfg->intline, cfg->intline, 1);
1511 }
1512
1513 void
1514 pci_add_children(device_t dev, int busno, size_t dinfo_size)
1515 {
1516 #define REG(n, w)       PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
1517         device_t pcib = device_get_parent(dev);
1518         struct pci_devinfo *dinfo;
1519         int maxslots;
1520         int s, f, pcifunchigh;
1521         uint8_t hdrtype;
1522
1523         KKASSERT(dinfo_size >= sizeof(struct pci_devinfo));
1524
1525         maxslots = PCIB_MAXSLOTS(pcib);
1526
1527         for (s = 0; s <= maxslots; s++) {
1528                 pcifunchigh = 0;
1529                 f = 0;
1530                 hdrtype = REG(PCIR_HDRTYPE, 1);
1531                 if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
1532                         continue;
1533                 if (hdrtype & PCIM_MFDEV)
1534                         pcifunchigh = PCI_FUNCMAX;
1535                 for (f = 0; f <= pcifunchigh; f++) {
1536                         dinfo = pci_read_device(pcib, busno, s, f, dinfo_size);
1537                         if (dinfo != NULL) {
1538                                 pci_add_child(dev, dinfo);
1539                         }
1540                 }
1541         }
1542 #undef REG
1543 }
1544
1545 /*
1546  * The actual PCI child that we add has a NULL driver whos parent
1547  * device will be "pci".  The child contains the ivars, not the parent.
1548  */
1549 void
1550 pci_add_child(device_t bus, struct pci_devinfo *dinfo)
1551 {
1552         device_t pcib;
1553
1554         pcib = device_get_parent(bus);
1555         dinfo->cfg.dev = device_add_child(bus, NULL, -1);
1556         device_set_ivars(dinfo->cfg.dev, dinfo);
1557         pci_add_resources(pcib, bus, dinfo->cfg.dev);
1558         pci_print_verbose(dinfo);
1559 }
1560
1561 /*
1562  * Probe the PCI bus.  Note: probe code is not supposed to add children
1563  * or call attach.
1564  */
1565 static int
1566 pci_probe(device_t dev)
1567 {
1568         device_set_desc(dev, "PCI bus");
1569
1570         /* Allow other subclasses to override this driver */
1571         return(-1000);
1572 }
1573
1574 static int
1575 pci_attach(device_t dev)
1576 {
1577         int busno;
1578         int lunit = device_get_unit(dev);
1579
1580         dev_ops_add(&pcic_ops, -1, lunit);
1581         make_dev(&pcic_ops, lunit, UID_ROOT, GID_WHEEL, 0644, "pci%d", lunit);
1582
1583         /*
1584          * Since there can be multiple independantly numbered PCI
1585          * busses on some large alpha systems, we can't use the unit
1586          * number to decide what bus we are probing. We ask the parent
1587          * pcib what our bus number is.
1588          *
1589          * pcib_get_bus() must act on the pci bus device, not on the pci
1590          * device, because it uses badly hacked nexus-based ivars to 
1591          * store and retrieve the physical bus number.  XXX
1592          */
1593         busno = pcib_get_bus(device_get_parent(dev));
1594         if (bootverbose)
1595                 device_printf(dev, "pci_attach() physical bus=%d\n", busno);
1596
1597         pci_add_children(dev, busno, sizeof(struct pci_devinfo));
1598
1599         return (bus_generic_attach(dev));
1600 }
1601
1602 static int
1603 pci_print_resources(struct resource_list *rl, const char *name, int type,
1604                     const char *format)
1605 {
1606         struct resource_list_entry *rle;
1607         int printed, retval;
1608
1609         printed = 0;
1610         retval = 0;
1611         /* Yes, this is kinda cheating */
1612         SLIST_FOREACH(rle, rl, link) {
1613                 if (rle->type == type) {
1614                         if (printed == 0)
1615                                 retval += kprintf(" %s ", name);
1616                         else if (printed > 0)
1617                                 retval += kprintf(",");
1618                         printed++;
1619                         retval += kprintf(format, rle->start);
1620                         if (rle->count > 1) {
1621                                 retval += kprintf("-");
1622                                 retval += kprintf(format, rle->start +
1623                                                  rle->count - 1);
1624                         }
1625                 }
1626         }
1627         return retval;
1628 }
1629
1630 int
1631 pci_print_child(device_t dev, device_t child)
1632 {
1633         struct pci_devinfo *dinfo;
1634         struct resource_list *rl;
1635         pcicfgregs *cfg;
1636         int retval = 0;
1637
1638         dinfo = device_get_ivars(child);
1639         cfg = &dinfo->cfg;
1640         rl = &dinfo->resources;
1641
1642         retval += bus_print_child_header(dev, child);
1643
1644         retval += pci_print_resources(rl, "port", SYS_RES_IOPORT, "%#lx");
1645         retval += pci_print_resources(rl, "mem", SYS_RES_MEMORY, "%#lx");
1646         retval += pci_print_resources(rl, "irq", SYS_RES_IRQ, "%ld");
1647         if (device_get_flags(dev))
1648                 retval += kprintf(" flags %#x", device_get_flags(dev));
1649
1650         retval += kprintf(" at device %d.%d", pci_get_slot(child),
1651                          pci_get_function(child));
1652
1653         retval += bus_print_child_footer(dev, child);
1654
1655         return (retval);
1656 }
1657
1658 void
1659 pci_probe_nomatch(device_t dev, device_t child)
1660 {
1661         struct pci_devinfo *dinfo;
1662         pcicfgregs *cfg;
1663         const char *desc;
1664         int unknown;
1665
1666         unknown = 0;
1667         dinfo = device_get_ivars(child);
1668         cfg = &dinfo->cfg;
1669         desc = pci_ata_match(child);
1670         if (!desc) desc = pci_usb_match(child);
1671         if (!desc) desc = pci_vga_match(child);
1672         if (!desc) desc = pci_chip_match(child);
1673         if (!desc) {
1674                 desc = "unknown card";
1675                 unknown++;
1676         }
1677         device_printf(dev, "<%s>", desc);
1678         if (bootverbose || unknown) {
1679                 kprintf(" (vendor=0x%04x, dev=0x%04x)",
1680                         cfg->vendor,
1681                         cfg->device);
1682         }
1683         kprintf(" at %d.%d",
1684                 pci_get_slot(child),
1685                 pci_get_function(child));
1686         if (cfg->intpin > 0 && cfg->intline != 255) {
1687                 kprintf(" irq %d", cfg->intline);
1688         }
1689         kprintf("\n");
1690                                       
1691         return;
1692 }
1693
1694 int
1695 pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1696 {
1697         struct pci_devinfo *dinfo;
1698         pcicfgregs *cfg;
1699
1700         dinfo = device_get_ivars(child);
1701         cfg = &dinfo->cfg;
1702
1703         switch (which) {
1704         case PCI_IVAR_SUBVENDOR:
1705                 *result = cfg->subvendor;
1706                 break;
1707         case PCI_IVAR_SUBDEVICE:
1708                 *result = cfg->subdevice;
1709                 break;
1710         case PCI_IVAR_VENDOR:
1711                 *result = cfg->vendor;
1712                 break;
1713         case PCI_IVAR_DEVICE:
1714                 *result = cfg->device;
1715                 break;
1716         case PCI_IVAR_DEVID:
1717                 *result = (cfg->device << 16) | cfg->vendor;
1718                 break;
1719         case PCI_IVAR_CLASS:
1720                 *result = cfg->baseclass;
1721                 break;
1722         case PCI_IVAR_SUBCLASS:
1723                 *result = cfg->subclass;
1724                 break;
1725         case PCI_IVAR_PROGIF:
1726                 *result = cfg->progif;
1727                 break;
1728         case PCI_IVAR_REVID:
1729                 *result = cfg->revid;
1730                 break;
1731         case PCI_IVAR_INTPIN:
1732                 *result = cfg->intpin;
1733                 break;
1734         case PCI_IVAR_IRQ:
1735                 *result = cfg->intline;
1736                 break;
1737         case PCI_IVAR_BUS:
1738                 *result = cfg->bus;
1739                 break;
1740         case PCI_IVAR_SLOT:
1741                 *result = cfg->slot;
1742                 break;
1743         case PCI_IVAR_FUNCTION:
1744                 *result = cfg->func;
1745                 break;
1746         case PCI_IVAR_SECONDARYBUS:
1747                 *result = cfg->secondarybus;
1748                 break;
1749         case PCI_IVAR_SUBORDINATEBUS:
1750                 *result = cfg->subordinatebus;
1751                 break;
1752         case PCI_IVAR_ETHADDR:
1753                 /*
1754                  * The generic accessor doesn't deal with failure, so
1755                  * we set the return value, then return an error.
1756                  */
1757                 *result = NULL;
1758                 return (EINVAL);
1759         default:
1760                 return ENOENT;
1761         }
1762         return 0;
1763 }
1764
1765 int
1766 pci_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1767 {
1768         struct pci_devinfo *dinfo;
1769         pcicfgregs *cfg;
1770
1771         dinfo = device_get_ivars(child);
1772         cfg = &dinfo->cfg;
1773
1774         switch (which) {
1775         case PCI_IVAR_SUBVENDOR:
1776         case PCI_IVAR_SUBDEVICE:
1777         case PCI_IVAR_VENDOR:
1778         case PCI_IVAR_DEVICE:
1779         case PCI_IVAR_DEVID:
1780         case PCI_IVAR_CLASS:
1781         case PCI_IVAR_SUBCLASS:
1782         case PCI_IVAR_PROGIF:
1783         case PCI_IVAR_REVID:
1784         case PCI_IVAR_INTPIN:
1785         case PCI_IVAR_IRQ:
1786         case PCI_IVAR_BUS:
1787         case PCI_IVAR_SLOT:
1788         case PCI_IVAR_FUNCTION:
1789         case PCI_IVAR_ETHADDR:
1790                 return EINVAL;  /* disallow for now */
1791
1792         case PCI_IVAR_SECONDARYBUS:
1793                 cfg->secondarybus = value;
1794                 break;
1795         case PCI_IVAR_SUBORDINATEBUS:
1796                 cfg->subordinatebus = value;
1797                 break;
1798         default:
1799                 return ENOENT;
1800         }
1801         return 0;
1802 }
1803
1804 #ifdef PCI_MAP_FIXUP
1805 static struct resource *
1806 pci_alloc_map(device_t dev, device_t child, int type, int *rid, u_long start,
1807               u_long end, u_long count, u_int flags)
1808 {
1809         struct pci_devinfo *dinfo = device_get_ivars(child);
1810         struct resource_list *rl = &dinfo->resources;
1811         struct resource_list_entry *rle;
1812         struct resource *res;
1813         uint32_t map, testval;
1814         int mapsize;
1815
1816         /*
1817          * Weed out the bogons, and figure out how large the BAR/map
1818          * is. BARs that read back 0 here are bogus and unimplemented.
1819          *
1820          * Note: atapci in legacy mode are special and handled elsewhere
1821          * in the code. If you have an atapci device in legacy mode and
1822          * it fails here, that other code is broken.
1823          */
1824         res = NULL;
1825         map = pci_read_config(child, *rid, 4);
1826         pci_write_config(child, *rid, 0xffffffff, 4);
1827         testval = pci_read_config(child, *rid, 4);
1828         if (pci_mapbase(testval) == 0)
1829                 goto out;
1830         if (pci_maptype(testval) & PCI_MAPMEM) {
1831                 if (type != SYS_RES_MEMORY) {
1832                         if (bootverbose)
1833                                 device_printf(dev, "child %s requested type %d"
1834                                               " for rid %#x, but the BAR says "
1835                                               "it is a memio\n",
1836                                               device_get_nameunit(child), type,
1837                                               *rid);
1838                         goto out;
1839                 }
1840         } else {
1841                 if (type != SYS_RES_IOPORT) {
1842                         if (bootverbose)
1843                                 device_printf(dev, "child %s requested type %d"
1844                                               " for rid %#x, but the BAR says "
1845                                               "it is an ioport\n",
1846                                               device_get_nameunit(child), type,
1847                                               *rid);
1848                         goto out;
1849                 }
1850         }
1851         /*
1852          * For real BARs, we need to override the size that
1853          * the driver requests, because that's what the BAR
1854          * actually uses and we would otherwise have a
1855          * situation where we might allocate the excess to
1856          * another driver, which won't work.
1857          */
1858         mapsize = pci_mapsize(testval);
1859         count = 1 << mapsize;
1860         if (RF_ALIGNMENT(flags) < mapsize)
1861                 flags = (flags & ~RF_ALIGNMENT_MASK) |
1862                    RF_ALIGNMENT_LOG2(mapsize);
1863         /*
1864          * Allocate enough resource, and then write back the
1865          * appropriate BAR for that resource.
1866          */
1867         res = BUS_ALLOC_RESOURCE(device_get_parent(dev), child, type, rid,
1868                                  start, end, count, flags);
1869         if (res == NULL) {
1870                 device_printf(child, "%#lx bytes at rid %#x res %d failed "
1871                               "(%#lx, %#lx)\n", count, *rid, type, start, end);
1872                 goto out;
1873         }
1874         resource_list_add(rl, type, *rid, start, end, count);
1875         rle = resource_list_find(rl, type, *rid);
1876         if (rle == NULL)
1877                 panic("pci_alloc_map: unexpectedly can't find resource.");
1878         rle->res = res;
1879         rle->start = rman_get_start(res);
1880         rle->end = rman_get_end(res);
1881         rle->count = count;
1882         if (bootverbose)
1883                 device_printf(child, "lazy allocation of %#lx bytes rid %#x "
1884                               "type %d at %#lx\n", count, *rid, type,
1885                               rman_get_start(res));
1886         map = rman_get_start(res);
1887 out:;
1888         pci_write_config(child, *rid, map, 4);
1889         return res;
1890 }
1891 #endif /* PCI_MAP_FIXUP */
1892
1893 struct resource *
1894 pci_alloc_resource(device_t dev, device_t child, int type, int *rid,
1895                    u_long start, u_long end, u_long count, u_int flags)
1896 {
1897         struct pci_devinfo *dinfo = device_get_ivars(child);
1898         struct resource_list *rl = &dinfo->resources;
1899 #ifdef PCI_MAP_FIXUP
1900         struct resource_list_entry *rle;
1901 #endif /* PCI_MAP_FIXUP */
1902         pcicfgregs *cfg = &dinfo->cfg;
1903
1904         /*
1905          * Perform lazy resource allocation
1906          */
1907         if (device_get_parent(child) == dev) {
1908                 switch (type) {
1909                 case SYS_RES_IRQ:
1910 #ifdef __i386__
1911                 /*
1912                  * If device doesn't have an interrupt routed, and is
1913                  * deserving of an interrupt, try to assign it one.
1914                  */
1915                         if ((cfg->intline == 255 || cfg->intline == 0) &&
1916                             (cfg->intpin != 0) &&
1917                             (start == 0) && (end == ~0UL)) {
1918                                 cfg->intline = PCIB_ROUTE_INTERRUPT(
1919                                         device_get_parent(dev), child,
1920                                         cfg->intpin);
1921                                 if (cfg->intline != 255) {
1922                                         pci_write_config(child, PCIR_INTLINE,
1923                                             cfg->intline, 1);
1924                                         resource_list_add(rl, SYS_RES_IRQ, 0,
1925                                             cfg->intline, cfg->intline, 1);
1926                                 }
1927                         }
1928                         break;
1929 #endif
1930                 case SYS_RES_IOPORT:
1931                         /* FALLTHROUGH */
1932                 case SYS_RES_MEMORY:
1933                         if (*rid < PCIR_BAR(cfg->nummaps)) {
1934                                 /*
1935                                  * Enable the I/O mode.  We should
1936                                  * also be assigning resources too
1937                                  * when none are present.  The
1938                                  * resource_list_alloc kind of sorta does
1939                                  * this...
1940                                  */
1941                                 if (PCI_ENABLE_IO(dev, child, type))
1942                                         return (NULL);
1943                         }
1944 #ifdef PCI_MAP_FIXUP
1945                         rle = resource_list_find(rl, type, *rid);
1946                         if (rle == NULL)
1947                                 return pci_alloc_map(dev, child, type, rid,
1948                                                      start, end, count, flags);
1949 #endif /* PCI_MAP_FIXUP */
1950                         break;
1951                 }
1952 #ifdef PCI_MAP_FIXUP
1953                 /*
1954                  * If we've already allocated the resource, then
1955                  * return it now. But first we may need to activate
1956                  * it, since we don't allocate the resource as active
1957                  * above. Normally this would be done down in the
1958                  * nexus, but since we short-circuit that path we have
1959                  * to do its job here. Not sure if we should free the
1960                  * resource if it fails to activate.
1961                  *
1962                  * Note: this also finds and returns resources for
1963                  * atapci devices in legacy mode as allocated in
1964                  * pci_ata_maps().
1965                  */
1966                 rle = resource_list_find(rl, type, *rid);
1967                 if (rle != NULL && rle->res != NULL) {
1968                         if (bootverbose)
1969                                 device_printf(child, "reserved %#lx bytes for "
1970                                               "rid %#x type %d at %#lx\n",
1971                                               rman_get_size(rle->res), *rid,
1972                                               type, rman_get_start(rle->res));
1973                         if ((flags & RF_ACTIVE) &&
1974                             bus_generic_activate_resource(dev, child, type,
1975                                                           *rid, rle->res) != 0)
1976                                 return NULL;
1977                         return rle->res;
1978                 }
1979 #endif /* PCI_MAP_FIXUP */
1980         }
1981         return resource_list_alloc(rl, dev, child, type, rid,
1982                                    start, end, count, flags);
1983 }
1984
1985 static int
1986 pci_release_resource(device_t dev, device_t child, int type, int rid,
1987                      struct resource *r)
1988 {
1989         struct pci_devinfo *dinfo = device_get_ivars(child);
1990         struct resource_list *rl = &dinfo->resources;
1991
1992         return resource_list_release(rl, dev, child, type, rid, r);
1993 }
1994
1995 static int
1996 pci_set_resource(device_t dev, device_t child, int type, int rid,
1997                  u_long start, u_long count)
1998 {
1999         struct pci_devinfo *dinfo = device_get_ivars(child);
2000         struct resource_list *rl = &dinfo->resources;
2001
2002         resource_list_add(rl, type, rid, start, start + count - 1, count);
2003         return 0;
2004 }
2005
2006 static int
2007 pci_get_resource(device_t dev, device_t child, int type, int rid,
2008                  u_long *startp, u_long *countp)
2009 {
2010         struct pci_devinfo *dinfo = device_get_ivars(child);
2011         struct resource_list *rl = &dinfo->resources;
2012         struct resource_list_entry *rle;
2013
2014         rle = resource_list_find(rl, type, rid);
2015         if (!rle)
2016                 return ENOENT;
2017         
2018         if (startp)
2019                 *startp = rle->start;
2020         if (countp)
2021                 *countp = rle->count;
2022
2023         return 0;
2024 }
2025
2026 void
2027 pci_delete_resource(device_t dev, device_t child, int type, int rid)
2028 {
2029         kprintf("pci_delete_resource: PCI resources can not be deleted\n");
2030 }
2031
2032 struct resource_list *
2033 pci_get_resource_list (device_t dev, device_t child)
2034 {
2035         struct pci_devinfo *dinfo = device_get_ivars(child); 
2036
2037         if (dinfo == NULL)
2038                 return (NULL);
2039         return (&dinfo->resources);
2040 }
2041
2042 u_int32_t
2043 pci_read_config_method(device_t dev, device_t child, int reg, int width)
2044 {
2045         struct pci_devinfo *dinfo = device_get_ivars(child);
2046         pcicfgregs *cfg = &dinfo->cfg;
2047
2048         return PCIB_READ_CONFIG(device_get_parent(dev),
2049                                  cfg->bus, cfg->slot, cfg->func,
2050                                  reg, width);
2051 }
2052
2053 void
2054 pci_write_config_method(device_t dev, device_t child, int reg,
2055                         u_int32_t val, int width)
2056 {
2057         struct pci_devinfo *dinfo = device_get_ivars(child);
2058         pcicfgregs *cfg = &dinfo->cfg;
2059
2060         PCIB_WRITE_CONFIG(device_get_parent(dev),
2061                           cfg->bus, cfg->slot, cfg->func,
2062                           reg, val, width);
2063 }
2064
2065 int
2066 pci_child_location_str_method(device_t cbdev, device_t child, char *buf,
2067     size_t buflen)
2068 {
2069         struct pci_devinfo *dinfo;
2070
2071         dinfo = device_get_ivars(child);
2072         ksnprintf(buf, buflen, "slot=%d function=%d", pci_get_slot(child),
2073             pci_get_function(child));
2074         return (0);
2075 }
2076
2077 int
2078 pci_child_pnpinfo_str_method(device_t cbdev, device_t child, char *buf,
2079     size_t buflen)
2080 {
2081         struct pci_devinfo *dinfo;
2082         pcicfgregs *cfg;
2083
2084         dinfo = device_get_ivars(child);
2085         cfg = &dinfo->cfg;
2086         ksnprintf(buf, buflen, "vendor=0x%04x device=0x%04x subvendor=0x%04x "
2087             "subdevice=0x%04x class=0x%02x%02x%02x", cfg->vendor, cfg->device,
2088             cfg->subvendor, cfg->subdevice, cfg->baseclass, cfg->subclass,
2089             cfg->progif);
2090         return (0);
2091 }
2092
2093 int
2094 pci_assign_interrupt_method(device_t dev, device_t child)
2095 {                       
2096         struct pci_devinfo *dinfo = device_get_ivars(child);
2097         pcicfgregs *cfg = &dinfo->cfg;
2098                          
2099         return (PCIB_ROUTE_INTERRUPT(device_get_parent(dev), child,
2100             cfg->intpin));
2101 }
2102
2103 static int
2104 pci_modevent(module_t mod, int what, void *arg)
2105 {
2106         switch (what) {
2107         case MOD_LOAD:
2108                 STAILQ_INIT(&pci_devq);
2109                 break;
2110         case MOD_UNLOAD:
2111                 break;
2112         }
2113
2114         return 0;
2115 }
2116
2117 int
2118 pci_resume(device_t dev)
2119 {
2120         int                     numdevs;
2121         int                     i;
2122         device_t                *children;
2123         device_t                child;
2124         struct pci_devinfo      *dinfo;
2125         pcicfgregs              *cfg;
2126
2127         device_get_children(dev, &children, &numdevs);
2128
2129         for (i = 0; i < numdevs; i++) {
2130                 child = children[i];
2131
2132                 dinfo = device_get_ivars(child);
2133                 cfg = &dinfo->cfg;
2134                 if (cfg->intpin > 0 && PCI_INTERRUPT_VALID(cfg->intline)) {
2135                         cfg->intline = PCI_ASSIGN_INTERRUPT(dev, child);
2136                         if (PCI_INTERRUPT_VALID(cfg->intline)) {
2137                                 pci_write_config(child, PCIR_INTLINE,
2138                                     cfg->intline, 1);
2139                         }
2140                 }
2141         }
2142
2143         kfree(children, M_TEMP);
2144
2145         return (bus_generic_resume(dev));
2146 }
2147
2148 static device_method_t pci_methods[] = {
2149         /* Device interface */
2150         DEVMETHOD(device_probe,         pci_probe),
2151         DEVMETHOD(device_attach,        pci_attach),
2152         DEVMETHOD(device_shutdown,      bus_generic_shutdown),
2153         DEVMETHOD(device_suspend,       bus_generic_suspend),
2154         DEVMETHOD(device_resume,        pci_resume),
2155
2156         /* Bus interface */
2157         DEVMETHOD(bus_print_child,      pci_print_child),
2158         DEVMETHOD(bus_probe_nomatch,    pci_probe_nomatch),
2159         DEVMETHOD(bus_read_ivar,        pci_read_ivar),
2160         DEVMETHOD(bus_write_ivar,       pci_write_ivar),
2161         DEVMETHOD(bus_driver_added,     bus_generic_driver_added),
2162         DEVMETHOD(bus_setup_intr,       bus_generic_setup_intr),
2163         DEVMETHOD(bus_teardown_intr,    bus_generic_teardown_intr),
2164
2165         DEVMETHOD(bus_get_resource_list,pci_get_resource_list),
2166         DEVMETHOD(bus_set_resource,     pci_set_resource),
2167         DEVMETHOD(bus_get_resource,     pci_get_resource),
2168         DEVMETHOD(bus_delete_resource,  pci_delete_resource),
2169         DEVMETHOD(bus_alloc_resource,   pci_alloc_resource),
2170         DEVMETHOD(bus_release_resource, pci_release_resource),
2171         DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
2172         DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
2173         DEVMETHOD(bus_child_pnpinfo_str, pci_child_pnpinfo_str_method),
2174         DEVMETHOD(bus_child_location_str, pci_child_location_str_method),
2175
2176         /* PCI interface */
2177         DEVMETHOD(pci_read_config,      pci_read_config_method),
2178         DEVMETHOD(pci_write_config,     pci_write_config_method),
2179         DEVMETHOD(pci_enable_busmaster, pci_enable_busmaster_method),
2180         DEVMETHOD(pci_disable_busmaster, pci_disable_busmaster_method),
2181         DEVMETHOD(pci_enable_io,        pci_enable_io_method),
2182         DEVMETHOD(pci_disable_io,       pci_disable_io_method),
2183         DEVMETHOD(pci_get_powerstate,   pci_get_powerstate_method),
2184         DEVMETHOD(pci_set_powerstate,   pci_set_powerstate_method),
2185         DEVMETHOD(pci_assign_interrupt, pci_assign_interrupt_method),   
2186
2187         { 0, 0 }
2188 };
2189
2190 driver_t pci_driver = {
2191         "pci",
2192         pci_methods,
2193         1,                      /* no softc */
2194 };
2195
2196 DRIVER_MODULE(pci, pcib, pci_driver, pci_devclass, pci_modevent, 0);
2197 MODULE_VERSION(pci, 1);