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