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