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