]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - sys/dev/pci/pci_pci.c
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.git] / sys / dev / pci / pci_pci.c
1 /*-
2  * Copyright (c) 1994,1995 Stefan Esser, Wolfgang StanglMeier
3  * Copyright (c) 2000 Michael Smith <msmith@freebsd.org>
4  * Copyright (c) 2000 BSDi
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33
34 /*
35  * PCI:PCI bridge support.
36  */
37
38 #include <sys/param.h>
39 #include <sys/bus.h>
40 #include <sys/kernel.h>
41 #include <sys/malloc.h>
42 #include <sys/module.h>
43 #include <sys/rman.h>
44 #include <sys/sysctl.h>
45 #include <sys/systm.h>
46
47 #include <dev/pci/pcivar.h>
48 #include <dev/pci/pcireg.h>
49 #include <dev/pci/pci_private.h>
50 #include <dev/pci/pcib_private.h>
51
52 #include "pcib_if.h"
53
54 static int              pcib_probe(device_t dev);
55 static int              pcib_suspend(device_t dev);
56 static int              pcib_resume(device_t dev);
57 static int              pcib_power_for_sleep(device_t pcib, device_t dev,
58                             int *pstate);
59 static uint16_t         pcib_ari_get_rid(device_t pcib, device_t dev);
60 static uint32_t         pcib_read_config(device_t dev, u_int b, u_int s, 
61     u_int f, u_int reg, int width);
62 static void             pcib_write_config(device_t dev, u_int b, u_int s,
63     u_int f, u_int reg, uint32_t val, int width);
64 static int              pcib_ari_maxslots(device_t dev);
65 static int              pcib_ari_maxfuncs(device_t dev);
66 static int              pcib_try_enable_ari(device_t pcib, device_t dev);
67
68 static device_method_t pcib_methods[] = {
69     /* Device interface */
70     DEVMETHOD(device_probe,             pcib_probe),
71     DEVMETHOD(device_attach,            pcib_attach),
72     DEVMETHOD(device_detach,            bus_generic_detach),
73     DEVMETHOD(device_shutdown,          bus_generic_shutdown),
74     DEVMETHOD(device_suspend,           pcib_suspend),
75     DEVMETHOD(device_resume,            pcib_resume),
76
77     /* Bus interface */
78     DEVMETHOD(bus_read_ivar,            pcib_read_ivar),
79     DEVMETHOD(bus_write_ivar,           pcib_write_ivar),
80     DEVMETHOD(bus_alloc_resource,       pcib_alloc_resource),
81 #ifdef NEW_PCIB
82     DEVMETHOD(bus_adjust_resource,      pcib_adjust_resource),
83     DEVMETHOD(bus_release_resource,     pcib_release_resource),
84 #else
85     DEVMETHOD(bus_adjust_resource,      bus_generic_adjust_resource),
86     DEVMETHOD(bus_release_resource,     bus_generic_release_resource),
87 #endif
88     DEVMETHOD(bus_activate_resource,    bus_generic_activate_resource),
89     DEVMETHOD(bus_deactivate_resource,  bus_generic_deactivate_resource),
90     DEVMETHOD(bus_setup_intr,           bus_generic_setup_intr),
91     DEVMETHOD(bus_teardown_intr,        bus_generic_teardown_intr),
92
93     /* pcib interface */
94     DEVMETHOD(pcib_maxslots,            pcib_ari_maxslots),
95     DEVMETHOD(pcib_maxfuncs,            pcib_ari_maxfuncs),
96     DEVMETHOD(pcib_read_config,         pcib_read_config),
97     DEVMETHOD(pcib_write_config,        pcib_write_config),
98     DEVMETHOD(pcib_route_interrupt,     pcib_route_interrupt),
99     DEVMETHOD(pcib_alloc_msi,           pcib_alloc_msi),
100     DEVMETHOD(pcib_release_msi,         pcib_release_msi),
101     DEVMETHOD(pcib_alloc_msix,          pcib_alloc_msix),
102     DEVMETHOD(pcib_release_msix,        pcib_release_msix),
103     DEVMETHOD(pcib_map_msi,             pcib_map_msi),
104     DEVMETHOD(pcib_power_for_sleep,     pcib_power_for_sleep),
105     DEVMETHOD(pcib_get_rid,             pcib_ari_get_rid),
106     DEVMETHOD(pcib_try_enable_ari,      pcib_try_enable_ari),
107
108     DEVMETHOD_END
109 };
110
111 static devclass_t pcib_devclass;
112
113 DEFINE_CLASS_0(pcib, pcib_driver, pcib_methods, sizeof(struct pcib_softc));
114 DRIVER_MODULE(pcib, pci, pcib_driver, pcib_devclass, NULL, NULL);
115
116 #ifdef NEW_PCIB
117 SYSCTL_DECL(_hw_pci);
118
119 static int pci_clear_pcib;
120 TUNABLE_INT("hw.pci.clear_pcib", &pci_clear_pcib);
121 SYSCTL_INT(_hw_pci, OID_AUTO, clear_pcib, CTLFLAG_RDTUN, &pci_clear_pcib, 0,
122     "Clear firmware-assigned resources for PCI-PCI bridge I/O windows.");
123
124 /*
125  * Is a resource from a child device sub-allocated from one of our
126  * resource managers?
127  */
128 static int
129 pcib_is_resource_managed(struct pcib_softc *sc, int type, struct resource *r)
130 {
131
132         switch (type) {
133 #ifdef PCI_RES_BUS
134         case PCI_RES_BUS:
135                 return (rman_is_region_manager(r, &sc->bus.rman));
136 #endif
137         case SYS_RES_IOPORT:
138                 return (rman_is_region_manager(r, &sc->io.rman));
139         case SYS_RES_MEMORY:
140                 /* Prefetchable resources may live in either memory rman. */
141                 if (rman_get_flags(r) & RF_PREFETCHABLE &&
142                     rman_is_region_manager(r, &sc->pmem.rman))
143                         return (1);
144                 return (rman_is_region_manager(r, &sc->mem.rman));
145         }
146         return (0);
147 }
148
149 static int
150 pcib_is_window_open(struct pcib_window *pw)
151 {
152
153         return (pw->valid && pw->base < pw->limit);
154 }
155
156 /*
157  * XXX: If RF_ACTIVE did not also imply allocating a bus space tag and
158  * handle for the resource, we could pass RF_ACTIVE up to the PCI bus
159  * when allocating the resource windows and rely on the PCI bus driver
160  * to do this for us.
161  */
162 static void
163 pcib_activate_window(struct pcib_softc *sc, int type)
164 {
165
166         PCI_ENABLE_IO(device_get_parent(sc->dev), sc->dev, type);
167 }
168
169 static void
170 pcib_write_windows(struct pcib_softc *sc, int mask)
171 {
172         device_t dev;
173         uint32_t val;
174
175         dev = sc->dev;
176         if (sc->io.valid && mask & WIN_IO) {
177                 val = pci_read_config(dev, PCIR_IOBASEL_1, 1);
178                 if ((val & PCIM_BRIO_MASK) == PCIM_BRIO_32) {
179                         pci_write_config(dev, PCIR_IOBASEH_1,
180                             sc->io.base >> 16, 2);
181                         pci_write_config(dev, PCIR_IOLIMITH_1,
182                             sc->io.limit >> 16, 2);
183                 }
184                 pci_write_config(dev, PCIR_IOBASEL_1, sc->io.base >> 8, 1);
185                 pci_write_config(dev, PCIR_IOLIMITL_1, sc->io.limit >> 8, 1);
186         }
187
188         if (mask & WIN_MEM) {
189                 pci_write_config(dev, PCIR_MEMBASE_1, sc->mem.base >> 16, 2);
190                 pci_write_config(dev, PCIR_MEMLIMIT_1, sc->mem.limit >> 16, 2);
191         }
192
193         if (sc->pmem.valid && mask & WIN_PMEM) {
194                 val = pci_read_config(dev, PCIR_PMBASEL_1, 2);
195                 if ((val & PCIM_BRPM_MASK) == PCIM_BRPM_64) {
196                         pci_write_config(dev, PCIR_PMBASEH_1,
197                             sc->pmem.base >> 32, 4);
198                         pci_write_config(dev, PCIR_PMLIMITH_1,
199                             sc->pmem.limit >> 32, 4);
200                 }
201                 pci_write_config(dev, PCIR_PMBASEL_1, sc->pmem.base >> 16, 2);
202                 pci_write_config(dev, PCIR_PMLIMITL_1, sc->pmem.limit >> 16, 2);
203         }
204 }
205
206 /*
207  * This is used to reject I/O port allocations that conflict with an
208  * ISA alias range.
209  */
210 static int
211 pcib_is_isa_range(struct pcib_softc *sc, u_long start, u_long end, u_long count)
212 {
213         u_long next_alias;
214
215         if (!(sc->bridgectl & PCIB_BCR_ISA_ENABLE))
216                 return (0);
217
218         /* Only check fixed ranges for overlap. */
219         if (start + count - 1 != end)
220                 return (0);
221
222         /* ISA aliases are only in the lower 64KB of I/O space. */
223         if (start >= 65536)
224                 return (0);
225
226         /* Check for overlap with 0x000 - 0x0ff as a special case. */
227         if (start < 0x100)
228                 goto alias;
229
230         /*
231          * If the start address is an alias, the range is an alias.
232          * Otherwise, compute the start of the next alias range and
233          * check if it is before the end of the candidate range.
234          */
235         if ((start & 0x300) != 0)
236                 goto alias;
237         next_alias = (start & ~0x3fful) | 0x100;
238         if (next_alias <= end)
239                 goto alias;
240         return (0);
241
242 alias:
243         if (bootverbose)
244                 device_printf(sc->dev,
245                     "I/O range %#lx-%#lx overlaps with an ISA alias\n", start,
246                     end);
247         return (1);
248 }
249
250 static void
251 pcib_add_window_resources(struct pcib_window *w, struct resource **res,
252     int count)
253 {
254         struct resource **newarray;
255         int error, i;
256
257         newarray = malloc(sizeof(struct resource *) * (w->count + count),
258             M_DEVBUF, M_WAITOK);
259         if (w->res != NULL)
260                 bcopy(w->res, newarray, sizeof(struct resource *) * w->count);
261         bcopy(res, newarray + w->count, sizeof(struct resource *) * count);
262         free(w->res, M_DEVBUF);
263         w->res = newarray;
264         w->count += count;
265         
266         for (i = 0; i < count; i++) {
267                 error = rman_manage_region(&w->rman, rman_get_start(res[i]),
268                     rman_get_end(res[i]));
269                 if (error)
270                         panic("Failed to add resource to rman");
271         }
272 }
273
274 typedef void (nonisa_callback)(u_long start, u_long end, void *arg);
275
276 static void
277 pcib_walk_nonisa_ranges(u_long start, u_long end, nonisa_callback *cb,
278     void *arg)
279 {
280         u_long next_end;
281
282         /*
283          * If start is within an ISA alias range, move up to the start
284          * of the next non-alias range.  As a special case, addresses
285          * in the range 0x000 - 0x0ff should also be skipped since
286          * those are used for various system I/O devices in ISA
287          * systems.
288          */
289         if (start <= 65535) {
290                 if (start < 0x100 || (start & 0x300) != 0) {
291                         start &= ~0x3ff;
292                         start += 0x400;
293                 }
294         }
295
296         /* ISA aliases are only in the lower 64KB of I/O space. */
297         while (start <= MIN(end, 65535)) {
298                 next_end = MIN(start | 0xff, end);
299                 cb(start, next_end, arg);
300                 start += 0x400;
301         }
302
303         if (start <= end)
304                 cb(start, end, arg);
305 }
306
307 static void
308 count_ranges(u_long start, u_long end, void *arg)
309 {
310         int *countp;
311
312         countp = arg;
313         (*countp)++;
314 }
315
316 struct alloc_state {
317         struct resource **res;
318         struct pcib_softc *sc;
319         int count, error;
320 };
321
322 static void
323 alloc_ranges(u_long start, u_long end, void *arg)
324 {
325         struct alloc_state *as;
326         struct pcib_window *w;
327         int rid;
328
329         as = arg;
330         if (as->error != 0)
331                 return;
332
333         w = &as->sc->io;
334         rid = w->reg;
335         if (bootverbose)
336                 device_printf(as->sc->dev,
337                     "allocating non-ISA range %#lx-%#lx\n", start, end);
338         as->res[as->count] = bus_alloc_resource(as->sc->dev, SYS_RES_IOPORT,
339             &rid, start, end, end - start + 1, 0);
340         if (as->res[as->count] == NULL)
341                 as->error = ENXIO;
342         else
343                 as->count++;
344 }
345
346 static int
347 pcib_alloc_nonisa_ranges(struct pcib_softc *sc, u_long start, u_long end)
348 {
349         struct alloc_state as;
350         int i, new_count;
351
352         /* First, see how many ranges we need. */
353         new_count = 0;
354         pcib_walk_nonisa_ranges(start, end, count_ranges, &new_count);
355
356         /* Second, allocate the ranges. */
357         as.res = malloc(sizeof(struct resource *) * new_count, M_DEVBUF,
358             M_WAITOK);
359         as.sc = sc;
360         as.count = 0;
361         as.error = 0;
362         pcib_walk_nonisa_ranges(start, end, alloc_ranges, &as);
363         if (as.error != 0) {
364                 for (i = 0; i < as.count; i++)
365                         bus_release_resource(sc->dev, SYS_RES_IOPORT,
366                             sc->io.reg, as.res[i]);
367                 free(as.res, M_DEVBUF);
368                 return (as.error);
369         }
370         KASSERT(as.count == new_count, ("%s: count mismatch", __func__));
371
372         /* Third, add the ranges to the window. */
373         pcib_add_window_resources(&sc->io, as.res, as.count);
374         free(as.res, M_DEVBUF);
375         return (0);
376 }
377
378 static void
379 pcib_alloc_window(struct pcib_softc *sc, struct pcib_window *w, int type,
380     int flags, pci_addr_t max_address)
381 {
382         struct resource *res;
383         char buf[64];
384         int error, rid;
385
386         if (max_address != (u_long)max_address)
387                 max_address = ~0ul;
388         w->rman.rm_start = 0;
389         w->rman.rm_end = max_address;
390         w->rman.rm_type = RMAN_ARRAY;
391         snprintf(buf, sizeof(buf), "%s %s window",
392             device_get_nameunit(sc->dev), w->name);
393         w->rman.rm_descr = strdup(buf, M_DEVBUF);
394         error = rman_init(&w->rman);
395         if (error)
396                 panic("Failed to initialize %s %s rman",
397                     device_get_nameunit(sc->dev), w->name);
398
399         if (!pcib_is_window_open(w))
400                 return;
401
402         if (w->base > max_address || w->limit > max_address) {
403                 device_printf(sc->dev,
404                     "initial %s window has too many bits, ignoring\n", w->name);
405                 return;
406         }
407         if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE)
408                 (void)pcib_alloc_nonisa_ranges(sc, w->base, w->limit);
409         else {
410                 rid = w->reg;
411                 res = bus_alloc_resource(sc->dev, type, &rid, w->base, w->limit,
412                     w->limit - w->base + 1, flags);
413                 if (res != NULL)
414                         pcib_add_window_resources(w, &res, 1);
415         }
416         if (w->res == NULL) {
417                 device_printf(sc->dev,
418                     "failed to allocate initial %s window: %#jx-%#jx\n",
419                     w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
420                 w->base = max_address;
421                 w->limit = 0;
422                 pcib_write_windows(sc, w->mask);
423                 return;
424         }
425         pcib_activate_window(sc, type);
426 }
427
428 /*
429  * Initialize I/O windows.
430  */
431 static void
432 pcib_probe_windows(struct pcib_softc *sc)
433 {
434         pci_addr_t max;
435         device_t dev;
436         uint32_t val;
437
438         dev = sc->dev;
439
440         if (pci_clear_pcib) {
441                 pci_write_config(dev, PCIR_IOBASEL_1, 0xff, 1);
442                 pci_write_config(dev, PCIR_IOBASEH_1, 0xffff, 2);
443                 pci_write_config(dev, PCIR_IOLIMITL_1, 0, 1);
444                 pci_write_config(dev, PCIR_IOLIMITH_1, 0, 2);
445                 pci_write_config(dev, PCIR_MEMBASE_1, 0xffff, 2);
446                 pci_write_config(dev, PCIR_MEMLIMIT_1, 0, 2);
447                 pci_write_config(dev, PCIR_PMBASEL_1, 0xffff, 2);
448                 pci_write_config(dev, PCIR_PMBASEH_1, 0xffffffff, 4);
449                 pci_write_config(dev, PCIR_PMLIMITL_1, 0, 2);
450                 pci_write_config(dev, PCIR_PMLIMITH_1, 0, 4);
451         }
452
453         /* Determine if the I/O port window is implemented. */
454         val = pci_read_config(dev, PCIR_IOBASEL_1, 1);
455         if (val == 0) {
456                 /*
457                  * If 'val' is zero, then only 16-bits of I/O space
458                  * are supported.
459                  */
460                 pci_write_config(dev, PCIR_IOBASEL_1, 0xff, 1);
461                 if (pci_read_config(dev, PCIR_IOBASEL_1, 1) != 0) {
462                         sc->io.valid = 1;
463                         pci_write_config(dev, PCIR_IOBASEL_1, 0, 1);
464                 }
465         } else
466                 sc->io.valid = 1;
467
468         /* Read the existing I/O port window. */
469         if (sc->io.valid) {
470                 sc->io.reg = PCIR_IOBASEL_1;
471                 sc->io.step = 12;
472                 sc->io.mask = WIN_IO;
473                 sc->io.name = "I/O port";
474                 if ((val & PCIM_BRIO_MASK) == PCIM_BRIO_32) {
475                         sc->io.base = PCI_PPBIOBASE(
476                             pci_read_config(dev, PCIR_IOBASEH_1, 2), val);
477                         sc->io.limit = PCI_PPBIOLIMIT(
478                             pci_read_config(dev, PCIR_IOLIMITH_1, 2),
479                             pci_read_config(dev, PCIR_IOLIMITL_1, 1));
480                         max = 0xffffffff;
481                 } else {
482                         sc->io.base = PCI_PPBIOBASE(0, val);
483                         sc->io.limit = PCI_PPBIOLIMIT(0,
484                             pci_read_config(dev, PCIR_IOLIMITL_1, 1));
485                         max = 0xffff;
486                 }
487                 pcib_alloc_window(sc, &sc->io, SYS_RES_IOPORT, 0, max);
488         }
489
490         /* Read the existing memory window. */
491         sc->mem.valid = 1;
492         sc->mem.reg = PCIR_MEMBASE_1;
493         sc->mem.step = 20;
494         sc->mem.mask = WIN_MEM;
495         sc->mem.name = "memory";
496         sc->mem.base = PCI_PPBMEMBASE(0,
497             pci_read_config(dev, PCIR_MEMBASE_1, 2));
498         sc->mem.limit = PCI_PPBMEMLIMIT(0,
499             pci_read_config(dev, PCIR_MEMLIMIT_1, 2));
500         pcib_alloc_window(sc, &sc->mem, SYS_RES_MEMORY, 0, 0xffffffff);
501
502         /* Determine if the prefetchable memory window is implemented. */
503         val = pci_read_config(dev, PCIR_PMBASEL_1, 2);
504         if (val == 0) {
505                 /*
506                  * If 'val' is zero, then only 32-bits of memory space
507                  * are supported.
508                  */
509                 pci_write_config(dev, PCIR_PMBASEL_1, 0xffff, 2);
510                 if (pci_read_config(dev, PCIR_PMBASEL_1, 2) != 0) {
511                         sc->pmem.valid = 1;
512                         pci_write_config(dev, PCIR_PMBASEL_1, 0, 2);
513                 }
514         } else
515                 sc->pmem.valid = 1;
516
517         /* Read the existing prefetchable memory window. */
518         if (sc->pmem.valid) {
519                 sc->pmem.reg = PCIR_PMBASEL_1;
520                 sc->pmem.step = 20;
521                 sc->pmem.mask = WIN_PMEM;
522                 sc->pmem.name = "prefetch";
523                 if ((val & PCIM_BRPM_MASK) == PCIM_BRPM_64) {
524                         sc->pmem.base = PCI_PPBMEMBASE(
525                             pci_read_config(dev, PCIR_PMBASEH_1, 4), val);
526                         sc->pmem.limit = PCI_PPBMEMLIMIT(
527                             pci_read_config(dev, PCIR_PMLIMITH_1, 4),
528                             pci_read_config(dev, PCIR_PMLIMITL_1, 2));
529                         max = 0xffffffffffffffff;
530                 } else {
531                         sc->pmem.base = PCI_PPBMEMBASE(0, val);
532                         sc->pmem.limit = PCI_PPBMEMLIMIT(0,
533                             pci_read_config(dev, PCIR_PMLIMITL_1, 2));
534                         max = 0xffffffff;
535                 }
536                 pcib_alloc_window(sc, &sc->pmem, SYS_RES_MEMORY,
537                     RF_PREFETCHABLE, max);
538         }
539 }
540
541 #ifdef PCI_RES_BUS
542 /*
543  * Allocate a suitable secondary bus for this bridge if needed and
544  * initialize the resource manager for the secondary bus range.  Note
545  * that the minimum count is a desired value and this may allocate a
546  * smaller range.
547  */
548 void
549 pcib_setup_secbus(device_t dev, struct pcib_secbus *bus, int min_count)
550 {
551         char buf[64];
552         int error, rid, sec_reg;
553
554         switch (pci_read_config(dev, PCIR_HDRTYPE, 1) & PCIM_HDRTYPE) {
555         case PCIM_HDRTYPE_BRIDGE:
556                 sec_reg = PCIR_SECBUS_1;
557                 bus->sub_reg = PCIR_SUBBUS_1;
558                 break;
559         case PCIM_HDRTYPE_CARDBUS:
560                 sec_reg = PCIR_SECBUS_2;
561                 bus->sub_reg = PCIR_SUBBUS_2;
562                 break;
563         default:
564                 panic("not a PCI bridge");
565         }
566         bus->sec = pci_read_config(dev, sec_reg, 1);
567         bus->sub = pci_read_config(dev, bus->sub_reg, 1);
568         bus->dev = dev;
569         bus->rman.rm_start = 0;
570         bus->rman.rm_end = PCI_BUSMAX;
571         bus->rman.rm_type = RMAN_ARRAY;
572         snprintf(buf, sizeof(buf), "%s bus numbers", device_get_nameunit(dev));
573         bus->rman.rm_descr = strdup(buf, M_DEVBUF);
574         error = rman_init(&bus->rman);
575         if (error)
576                 panic("Failed to initialize %s bus number rman",
577                     device_get_nameunit(dev));
578
579         /*
580          * Allocate a bus range.  This will return an existing bus range
581          * if one exists, or a new bus range if one does not.
582          */
583         rid = 0;
584         bus->res = bus_alloc_resource(dev, PCI_RES_BUS, &rid, 0ul, ~0ul,
585             min_count, 0);
586         if (bus->res == NULL) {
587                 /*
588                  * Fall back to just allocating a range of a single bus
589                  * number.
590                  */
591                 bus->res = bus_alloc_resource(dev, PCI_RES_BUS, &rid, 0ul, ~0ul,
592                     1, 0);
593         } else if (rman_get_size(bus->res) < min_count)
594                 /*
595                  * Attempt to grow the existing range to satisfy the
596                  * minimum desired count.
597                  */
598                 (void)bus_adjust_resource(dev, PCI_RES_BUS, bus->res,
599                     rman_get_start(bus->res), rman_get_start(bus->res) +
600                     min_count - 1);
601
602         /*
603          * Add the initial resource to the rman.
604          */
605         if (bus->res != NULL) {
606                 error = rman_manage_region(&bus->rman, rman_get_start(bus->res),
607                     rman_get_end(bus->res));
608                 if (error)
609                         panic("Failed to add resource to rman");
610                 bus->sec = rman_get_start(bus->res);
611                 bus->sub = rman_get_end(bus->res);
612         }
613 }
614
615 static struct resource *
616 pcib_suballoc_bus(struct pcib_secbus *bus, device_t child, int *rid,
617     u_long start, u_long end, u_long count, u_int flags)
618 {
619         struct resource *res;
620
621         res = rman_reserve_resource(&bus->rman, start, end, count, flags,
622             child);
623         if (res == NULL)
624                 return (NULL);
625
626         if (bootverbose)
627                 device_printf(bus->dev,
628                     "allocated bus range (%lu-%lu) for rid %d of %s\n",
629                     rman_get_start(res), rman_get_end(res), *rid,
630                     pcib_child_name(child));
631         rman_set_rid(res, *rid);
632         return (res);
633 }
634
635 /*
636  * Attempt to grow the secondary bus range.  This is much simpler than
637  * for I/O windows as the range can only be grown by increasing
638  * subbus.
639  */
640 static int
641 pcib_grow_subbus(struct pcib_secbus *bus, u_long new_end)
642 {
643         u_long old_end;
644         int error;
645
646         old_end = rman_get_end(bus->res);
647         KASSERT(new_end > old_end, ("attempt to shrink subbus"));
648         error = bus_adjust_resource(bus->dev, PCI_RES_BUS, bus->res,
649             rman_get_start(bus->res), new_end);
650         if (error)
651                 return (error);
652         if (bootverbose)
653                 device_printf(bus->dev, "grew bus range to %lu-%lu\n",
654                     rman_get_start(bus->res), rman_get_end(bus->res));
655         error = rman_manage_region(&bus->rman, old_end + 1,
656             rman_get_end(bus->res));
657         if (error)
658                 panic("Failed to add resource to rman");
659         bus->sub = rman_get_end(bus->res);
660         pci_write_config(bus->dev, bus->sub_reg, bus->sub, 1);
661         return (0);
662 }
663
664 struct resource *
665 pcib_alloc_subbus(struct pcib_secbus *bus, device_t child, int *rid,
666     u_long start, u_long end, u_long count, u_int flags)
667 {
668         struct resource *res;
669         u_long start_free, end_free, new_end;
670
671         /*
672          * First, see if the request can be satisified by the existing
673          * bus range.
674          */
675         res = pcib_suballoc_bus(bus, child, rid, start, end, count, flags);
676         if (res != NULL)
677                 return (res);
678
679         /*
680          * Figure out a range to grow the bus range.  First, find the
681          * first bus number after the last allocated bus in the rman and
682          * enforce that as a minimum starting point for the range.
683          */
684         if (rman_last_free_region(&bus->rman, &start_free, &end_free) != 0 ||
685             end_free != bus->sub)
686                 start_free = bus->sub + 1;
687         if (start_free < start)
688                 start_free = start;
689         new_end = start_free + count - 1;
690
691         /*
692          * See if this new range would satisfy the request if it
693          * succeeds.
694          */
695         if (new_end > end)
696                 return (NULL);
697
698         /* Finally, attempt to grow the existing resource. */
699         if (bootverbose) {
700                 device_printf(bus->dev,
701                     "attempting to grow bus range for %lu buses\n", count);
702                 printf("\tback candidate range: %lu-%lu\n", start_free,
703                     new_end);
704         }
705         if (pcib_grow_subbus(bus, new_end) == 0)
706                 return (pcib_suballoc_bus(bus, child, rid, start, end, count,
707                     flags));
708         return (NULL);
709 }
710 #endif
711
712 #else
713
714 /*
715  * Is the prefetch window open (eg, can we allocate memory in it?)
716  */
717 static int
718 pcib_is_prefetch_open(struct pcib_softc *sc)
719 {
720         return (sc->pmembase > 0 && sc->pmembase < sc->pmemlimit);
721 }
722
723 /*
724  * Is the nonprefetch window open (eg, can we allocate memory in it?)
725  */
726 static int
727 pcib_is_nonprefetch_open(struct pcib_softc *sc)
728 {
729         return (sc->membase > 0 && sc->membase < sc->memlimit);
730 }
731
732 /*
733  * Is the io window open (eg, can we allocate ports in it?)
734  */
735 static int
736 pcib_is_io_open(struct pcib_softc *sc)
737 {
738         return (sc->iobase > 0 && sc->iobase < sc->iolimit);
739 }
740
741 /*
742  * Get current I/O decode.
743  */
744 static void
745 pcib_get_io_decode(struct pcib_softc *sc)
746 {
747         device_t        dev;
748         uint32_t        iolow;
749
750         dev = sc->dev;
751
752         iolow = pci_read_config(dev, PCIR_IOBASEL_1, 1);
753         if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
754                 sc->iobase = PCI_PPBIOBASE(
755                     pci_read_config(dev, PCIR_IOBASEH_1, 2), iolow);
756         else
757                 sc->iobase = PCI_PPBIOBASE(0, iolow);
758
759         iolow = pci_read_config(dev, PCIR_IOLIMITL_1, 1);
760         if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
761                 sc->iolimit = PCI_PPBIOLIMIT(
762                     pci_read_config(dev, PCIR_IOLIMITH_1, 2), iolow);
763         else
764                 sc->iolimit = PCI_PPBIOLIMIT(0, iolow);
765 }
766
767 /*
768  * Get current memory decode.
769  */
770 static void
771 pcib_get_mem_decode(struct pcib_softc *sc)
772 {
773         device_t        dev;
774         pci_addr_t      pmemlow;
775
776         dev = sc->dev;
777
778         sc->membase = PCI_PPBMEMBASE(0,
779             pci_read_config(dev, PCIR_MEMBASE_1, 2));
780         sc->memlimit = PCI_PPBMEMLIMIT(0,
781             pci_read_config(dev, PCIR_MEMLIMIT_1, 2));
782
783         pmemlow = pci_read_config(dev, PCIR_PMBASEL_1, 2);
784         if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64)
785                 sc->pmembase = PCI_PPBMEMBASE(
786                     pci_read_config(dev, PCIR_PMBASEH_1, 4), pmemlow);
787         else
788                 sc->pmembase = PCI_PPBMEMBASE(0, pmemlow);
789
790         pmemlow = pci_read_config(dev, PCIR_PMLIMITL_1, 2);
791         if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64) 
792                 sc->pmemlimit = PCI_PPBMEMLIMIT(
793                     pci_read_config(dev, PCIR_PMLIMITH_1, 4), pmemlow);
794         else
795                 sc->pmemlimit = PCI_PPBMEMLIMIT(0, pmemlow);
796 }
797
798 /*
799  * Restore previous I/O decode.
800  */
801 static void
802 pcib_set_io_decode(struct pcib_softc *sc)
803 {
804         device_t        dev;
805         uint32_t        iohi;
806
807         dev = sc->dev;
808
809         iohi = sc->iobase >> 16;
810         if (iohi > 0)
811                 pci_write_config(dev, PCIR_IOBASEH_1, iohi, 2);
812         pci_write_config(dev, PCIR_IOBASEL_1, sc->iobase >> 8, 1);
813
814         iohi = sc->iolimit >> 16;
815         if (iohi > 0)
816                 pci_write_config(dev, PCIR_IOLIMITH_1, iohi, 2);
817         pci_write_config(dev, PCIR_IOLIMITL_1, sc->iolimit >> 8, 1);
818 }
819
820 /*
821  * Restore previous memory decode.
822  */
823 static void
824 pcib_set_mem_decode(struct pcib_softc *sc)
825 {
826         device_t        dev;
827         pci_addr_t      pmemhi;
828
829         dev = sc->dev;
830
831         pci_write_config(dev, PCIR_MEMBASE_1, sc->membase >> 16, 2);
832         pci_write_config(dev, PCIR_MEMLIMIT_1, sc->memlimit >> 16, 2);
833
834         pmemhi = sc->pmembase >> 32;
835         if (pmemhi > 0)
836                 pci_write_config(dev, PCIR_PMBASEH_1, pmemhi, 4);
837         pci_write_config(dev, PCIR_PMBASEL_1, sc->pmembase >> 16, 2);
838
839         pmemhi = sc->pmemlimit >> 32;
840         if (pmemhi > 0)
841                 pci_write_config(dev, PCIR_PMLIMITH_1, pmemhi, 4);
842         pci_write_config(dev, PCIR_PMLIMITL_1, sc->pmemlimit >> 16, 2);
843 }
844 #endif
845
846 /*
847  * Get current bridge configuration.
848  */
849 static void
850 pcib_cfg_save(struct pcib_softc *sc)
851 {
852 #ifndef NEW_PCIB
853         device_t        dev;
854         uint16_t command;
855
856         dev = sc->dev;
857
858         command = pci_read_config(dev, PCIR_COMMAND, 2);
859         if (command & PCIM_CMD_PORTEN)
860                 pcib_get_io_decode(sc);
861         if (command & PCIM_CMD_MEMEN)
862                 pcib_get_mem_decode(sc);
863 #endif
864 }
865
866 /*
867  * Restore previous bridge configuration.
868  */
869 static void
870 pcib_cfg_restore(struct pcib_softc *sc)
871 {
872         device_t        dev;
873 #ifndef NEW_PCIB
874         uint16_t command;
875 #endif
876         dev = sc->dev;
877
878 #ifdef NEW_PCIB
879         pcib_write_windows(sc, WIN_IO | WIN_MEM | WIN_PMEM);
880 #else
881         command = pci_read_config(dev, PCIR_COMMAND, 2);
882         if (command & PCIM_CMD_PORTEN)
883                 pcib_set_io_decode(sc);
884         if (command & PCIM_CMD_MEMEN)
885                 pcib_set_mem_decode(sc);
886 #endif
887 }
888
889 /*
890  * Generic device interface
891  */
892 static int
893 pcib_probe(device_t dev)
894 {
895     if ((pci_get_class(dev) == PCIC_BRIDGE) &&
896         (pci_get_subclass(dev) == PCIS_BRIDGE_PCI)) {
897         device_set_desc(dev, "PCI-PCI bridge");
898         return(-10000);
899     }
900     return(ENXIO);
901 }
902
903 void
904 pcib_attach_common(device_t dev)
905 {
906     struct pcib_softc   *sc;
907     struct sysctl_ctx_list *sctx;
908     struct sysctl_oid   *soid;
909     int comma;
910
911     sc = device_get_softc(dev);
912     sc->dev = dev;
913
914     /*
915      * Get current bridge configuration.
916      */
917     sc->domain = pci_get_domain(dev);
918 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
919     sc->bus.sec = pci_read_config(dev, PCIR_SECBUS_1, 1);
920     sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
921 #endif
922     sc->bridgectl = pci_read_config(dev, PCIR_BRIDGECTL_1, 2);
923     pcib_cfg_save(sc);
924
925     /*
926      * The primary bus register should always be the bus of the
927      * parent.
928      */
929     sc->pribus = pci_get_bus(dev);
930     pci_write_config(dev, PCIR_PRIBUS_1, sc->pribus, 1);
931
932     /*
933      * Setup sysctl reporting nodes
934      */
935     sctx = device_get_sysctl_ctx(dev);
936     soid = device_get_sysctl_tree(dev);
937     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "domain",
938       CTLFLAG_RD, &sc->domain, 0, "Domain number");
939     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "pribus",
940       CTLFLAG_RD, &sc->pribus, 0, "Primary bus number");
941     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "secbus",
942       CTLFLAG_RD, &sc->bus.sec, 0, "Secondary bus number");
943     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "subbus",
944       CTLFLAG_RD, &sc->bus.sub, 0, "Subordinate bus number");
945
946     /*
947      * Quirk handling.
948      */
949     switch (pci_get_devid(dev)) {
950 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
951     case 0x12258086:            /* Intel 82454KX/GX (Orion) */
952         {
953             uint8_t     supbus;
954
955             supbus = pci_read_config(dev, 0x41, 1);
956             if (supbus != 0xff) {
957                 sc->bus.sec = supbus + 1;
958                 sc->bus.sub = supbus + 1;
959             }
960             break;
961         }
962 #endif
963
964     /*
965      * The i82380FB mobile docking controller is a PCI-PCI bridge,
966      * and it is a subtractive bridge.  However, the ProgIf is wrong
967      * so the normal setting of PCIB_SUBTRACTIVE bit doesn't
968      * happen.  There's also a Toshiba bridge that behaves this
969      * way.
970      */
971     case 0x124b8086:            /* Intel 82380FB Mobile */
972     case 0x060513d7:            /* Toshiba ???? */
973         sc->flags |= PCIB_SUBTRACTIVE;
974         break;
975
976 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
977     /* Compaq R3000 BIOS sets wrong subordinate bus number. */
978     case 0x00dd10de:
979         {
980             char *cp;
981
982             if ((cp = getenv("smbios.planar.maker")) == NULL)
983                 break;
984             if (strncmp(cp, "Compal", 6) != 0) {
985                 freeenv(cp);
986                 break;
987             }
988             freeenv(cp);
989             if ((cp = getenv("smbios.planar.product")) == NULL)
990                 break;
991             if (strncmp(cp, "08A0", 4) != 0) {
992                 freeenv(cp);
993                 break;
994             }
995             freeenv(cp);
996             if (sc->bus.sub < 0xa) {
997                 pci_write_config(dev, PCIR_SUBBUS_1, 0xa, 1);
998                 sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
999             }
1000             break;
1001         }
1002 #endif
1003     }
1004
1005     if (pci_msi_device_blacklisted(dev))
1006         sc->flags |= PCIB_DISABLE_MSI;
1007
1008     if (pci_msix_device_blacklisted(dev))
1009         sc->flags |= PCIB_DISABLE_MSIX;
1010
1011     /*
1012      * Intel 815, 845 and other chipsets say they are PCI-PCI bridges,
1013      * but have a ProgIF of 0x80.  The 82801 family (AA, AB, BAM/CAM,
1014      * BA/CA/DB and E) PCI bridges are HUB-PCI bridges, in Intelese.
1015      * This means they act as if they were subtractively decoding
1016      * bridges and pass all transactions.  Mark them and real ProgIf 1
1017      * parts as subtractive.
1018      */
1019     if ((pci_get_devid(dev) & 0xff00ffff) == 0x24008086 ||
1020       pci_read_config(dev, PCIR_PROGIF, 1) == PCIP_BRIDGE_PCI_SUBTRACTIVE)
1021         sc->flags |= PCIB_SUBTRACTIVE;
1022
1023 #ifdef NEW_PCIB
1024 #ifdef PCI_RES_BUS
1025     pcib_setup_secbus(dev, &sc->bus, 1);
1026 #endif
1027     pcib_probe_windows(sc);
1028 #endif
1029     if (bootverbose) {
1030         device_printf(dev, "  domain            %d\n", sc->domain);
1031         device_printf(dev, "  secondary bus     %d\n", sc->bus.sec);
1032         device_printf(dev, "  subordinate bus   %d\n", sc->bus.sub);
1033 #ifdef NEW_PCIB
1034         if (pcib_is_window_open(&sc->io))
1035             device_printf(dev, "  I/O decode        0x%jx-0x%jx\n",
1036               (uintmax_t)sc->io.base, (uintmax_t)sc->io.limit);
1037         if (pcib_is_window_open(&sc->mem))
1038             device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1039               (uintmax_t)sc->mem.base, (uintmax_t)sc->mem.limit);
1040         if (pcib_is_window_open(&sc->pmem))
1041             device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1042               (uintmax_t)sc->pmem.base, (uintmax_t)sc->pmem.limit);
1043 #else
1044         if (pcib_is_io_open(sc))
1045             device_printf(dev, "  I/O decode        0x%x-0x%x\n",
1046               sc->iobase, sc->iolimit);
1047         if (pcib_is_nonprefetch_open(sc))
1048             device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1049               (uintmax_t)sc->membase, (uintmax_t)sc->memlimit);
1050         if (pcib_is_prefetch_open(sc))
1051             device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1052               (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
1053 #endif
1054         if (sc->bridgectl & (PCIB_BCR_ISA_ENABLE | PCIB_BCR_VGA_ENABLE) ||
1055             sc->flags & PCIB_SUBTRACTIVE) {
1056                 device_printf(dev, "  special decode    ");
1057                 comma = 0;
1058                 if (sc->bridgectl & PCIB_BCR_ISA_ENABLE) {
1059                         printf("ISA");
1060                         comma = 1;
1061                 }
1062                 if (sc->bridgectl & PCIB_BCR_VGA_ENABLE) {
1063                         printf("%sVGA", comma ? ", " : "");
1064                         comma = 1;
1065                 }
1066                 if (sc->flags & PCIB_SUBTRACTIVE)
1067                         printf("%ssubtractive", comma ? ", " : "");
1068                 printf("\n");
1069         }
1070     }
1071
1072     /*
1073      * Always enable busmastering on bridges so that transactions
1074      * initiated on the secondary bus are passed through to the
1075      * primary bus.
1076      */
1077     pci_enable_busmaster(dev);
1078 }
1079
1080 int
1081 pcib_attach(device_t dev)
1082 {
1083     struct pcib_softc   *sc;
1084     device_t            child;
1085
1086     pcib_attach_common(dev);
1087     sc = device_get_softc(dev);
1088     if (sc->bus.sec != 0) {
1089         child = device_add_child(dev, "pci", sc->bus.sec);
1090         if (child != NULL)
1091             return(bus_generic_attach(dev));
1092     }
1093
1094     /* no secondary bus; we should have fixed this */
1095     return(0);
1096 }
1097
1098 int
1099 pcib_suspend(device_t dev)
1100 {
1101
1102         pcib_cfg_save(device_get_softc(dev));
1103         return (bus_generic_suspend(dev));
1104 }
1105
1106 int
1107 pcib_resume(device_t dev)
1108 {
1109
1110         pcib_cfg_restore(device_get_softc(dev));
1111         return (bus_generic_resume(dev));
1112 }
1113
1114 int
1115 pcib_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1116 {
1117     struct pcib_softc   *sc = device_get_softc(dev);
1118     
1119     switch (which) {
1120     case PCIB_IVAR_DOMAIN:
1121         *result = sc->domain;
1122         return(0);
1123     case PCIB_IVAR_BUS:
1124         *result = sc->bus.sec;
1125         return(0);
1126     }
1127     return(ENOENT);
1128 }
1129
1130 int
1131 pcib_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1132 {
1133
1134     switch (which) {
1135     case PCIB_IVAR_DOMAIN:
1136         return(EINVAL);
1137     case PCIB_IVAR_BUS:
1138         return(EINVAL);
1139     }
1140     return(ENOENT);
1141 }
1142
1143 #ifdef NEW_PCIB
1144 /*
1145  * Attempt to allocate a resource from the existing resources assigned
1146  * to a window.
1147  */
1148 static struct resource *
1149 pcib_suballoc_resource(struct pcib_softc *sc, struct pcib_window *w,
1150     device_t child, int type, int *rid, u_long start, u_long end, u_long count,
1151     u_int flags)
1152 {
1153         struct resource *res;
1154
1155         if (!pcib_is_window_open(w))
1156                 return (NULL);
1157
1158         res = rman_reserve_resource(&w->rman, start, end, count,
1159             flags & ~RF_ACTIVE, child);
1160         if (res == NULL)
1161                 return (NULL);
1162
1163         if (bootverbose)
1164                 device_printf(sc->dev,
1165                     "allocated %s range (%#lx-%#lx) for rid %x of %s\n",
1166                     w->name, rman_get_start(res), rman_get_end(res), *rid,
1167                     pcib_child_name(child));
1168         rman_set_rid(res, *rid);
1169
1170         /*
1171          * If the resource should be active, pass that request up the
1172          * tree.  This assumes the parent drivers can handle
1173          * activating sub-allocated resources.
1174          */
1175         if (flags & RF_ACTIVE) {
1176                 if (bus_activate_resource(child, type, *rid, res) != 0) {
1177                         rman_release_resource(res);
1178                         return (NULL);
1179                 }
1180         }
1181
1182         return (res);
1183 }
1184
1185 /* Allocate a fresh resource range for an unconfigured window. */
1186 static int
1187 pcib_alloc_new_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1188     u_long start, u_long end, u_long count, u_int flags)
1189 {
1190         struct resource *res;
1191         u_long base, limit, wmask;
1192         int rid;
1193
1194         /*
1195          * If this is an I/O window on a bridge with ISA enable set
1196          * and the start address is below 64k, then try to allocate an
1197          * initial window of 0x1000 bytes long starting at address
1198          * 0xf000 and walking down.  Note that if the original request
1199          * was larger than the non-aliased range size of 0x100 our
1200          * caller would have raised the start address up to 64k
1201          * already.
1202          */
1203         if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1204             start < 65536) {
1205                 for (base = 0xf000; (long)base >= 0; base -= 0x1000) {
1206                         limit = base + 0xfff;
1207
1208                         /*
1209                          * Skip ranges that wouldn't work for the
1210                          * original request.  Note that the actual
1211                          * window that overlaps are the non-alias
1212                          * ranges within [base, limit], so this isn't
1213                          * quite a simple comparison.
1214                          */
1215                         if (start + count > limit - 0x400)
1216                                 continue;
1217                         if (base == 0) {
1218                                 /*
1219                                  * The first open region for the window at
1220                                  * 0 is 0x400-0x4ff.
1221                                  */
1222                                 if (end - count + 1 < 0x400)
1223                                         continue;
1224                         } else {
1225                                 if (end - count + 1 < base)
1226                                         continue;
1227                         }
1228
1229                         if (pcib_alloc_nonisa_ranges(sc, base, limit) == 0) {
1230                                 w->base = base;
1231                                 w->limit = limit;
1232                                 return (0);
1233                         }
1234                 }
1235                 return (ENOSPC);                
1236         }
1237         
1238         wmask = (1ul << w->step) - 1;
1239         if (RF_ALIGNMENT(flags) < w->step) {
1240                 flags &= ~RF_ALIGNMENT_MASK;
1241                 flags |= RF_ALIGNMENT_LOG2(w->step);
1242         }
1243         start &= ~wmask;
1244         end |= wmask;
1245         count = roundup2(count, 1ul << w->step);
1246         rid = w->reg;
1247         res = bus_alloc_resource(sc->dev, type, &rid, start, end, count,
1248             flags & ~RF_ACTIVE);
1249         if (res == NULL)
1250                 return (ENOSPC);
1251         pcib_add_window_resources(w, &res, 1);
1252         pcib_activate_window(sc, type);
1253         w->base = rman_get_start(res);
1254         w->limit = rman_get_end(res);
1255         return (0);
1256 }
1257
1258 /* Try to expand an existing window to the requested base and limit. */
1259 static int
1260 pcib_expand_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1261     u_long base, u_long limit)
1262 {
1263         struct resource *res;
1264         int error, i, force_64k_base;
1265
1266         KASSERT(base <= w->base && limit >= w->limit,
1267             ("attempting to shrink window"));
1268
1269         /*
1270          * XXX: pcib_grow_window() doesn't try to do this anyway and
1271          * the error handling for all the edge cases would be tedious.
1272          */
1273         KASSERT(limit == w->limit || base == w->base,
1274             ("attempting to grow both ends of a window"));
1275
1276         /*
1277          * Yet more special handling for requests to expand an I/O
1278          * window behind an ISA-enabled bridge.  Since I/O windows
1279          * have to grow in 0x1000 increments and the end of the 0xffff
1280          * range is an alias, growing a window below 64k will always
1281          * result in allocating new resources and never adjusting an
1282          * existing resource.
1283          */
1284         if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1285             (limit <= 65535 || (base <= 65535 && base != w->base))) {
1286                 KASSERT(limit == w->limit || limit <= 65535,
1287                     ("attempting to grow both ends across 64k ISA alias"));
1288
1289                 if (base != w->base)
1290                         error = pcib_alloc_nonisa_ranges(sc, base, w->base - 1);
1291                 else
1292                         error = pcib_alloc_nonisa_ranges(sc, w->limit + 1,
1293                             limit);
1294                 if (error == 0) {
1295                         w->base = base;
1296                         w->limit = limit;
1297                 }
1298                 return (error);
1299         }
1300
1301         /*
1302          * Find the existing resource to adjust.  Usually there is only one,
1303          * but for an ISA-enabled bridge we might be growing the I/O window
1304          * above 64k and need to find the existing resource that maps all
1305          * of the area above 64k.
1306          */
1307         for (i = 0; i < w->count; i++) {
1308                 if (rman_get_end(w->res[i]) == w->limit)
1309                         break;
1310         }
1311         KASSERT(i != w->count, ("did not find existing resource"));
1312         res = w->res[i];
1313
1314         /*
1315          * Usually the resource we found should match the window's
1316          * existing range.  The one exception is the ISA-enabled case
1317          * mentioned above in which case the resource should start at
1318          * 64k.
1319          */
1320         if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1321             w->base <= 65535) {
1322                 KASSERT(rman_get_start(res) == 65536,
1323                     ("existing resource mismatch"));
1324                 force_64k_base = 1;
1325         } else {
1326                 KASSERT(w->base == rman_get_start(res),
1327                     ("existing resource mismatch"));
1328                 force_64k_base = 0;
1329         }       
1330
1331         error = bus_adjust_resource(sc->dev, type, res, force_64k_base ?
1332             rman_get_start(res) : base, limit);
1333         if (error)
1334                 return (error);
1335
1336         /* Add the newly allocated region to the resource manager. */
1337         if (w->base != base) {
1338                 error = rman_manage_region(&w->rman, base, w->base - 1);
1339                 w->base = base;
1340         } else {
1341                 error = rman_manage_region(&w->rman, w->limit + 1, limit);
1342                 w->limit = limit;
1343         }
1344         if (error) {
1345                 if (bootverbose)
1346                         device_printf(sc->dev,
1347                             "failed to expand %s resource manager\n", w->name);
1348                 (void)bus_adjust_resource(sc->dev, type, res, force_64k_base ?
1349                     rman_get_start(res) : w->base, w->limit);
1350         }
1351         return (error);
1352 }
1353
1354 /*
1355  * Attempt to grow a window to make room for a given resource request.
1356  */
1357 static int
1358 pcib_grow_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1359     u_long start, u_long end, u_long count, u_int flags)
1360 {
1361         u_long align, start_free, end_free, front, back, wmask;
1362         int error;
1363
1364         /*
1365          * Clamp the desired resource range to the maximum address
1366          * this window supports.  Reject impossible requests.
1367          *
1368          * For I/O port requests behind a bridge with the ISA enable
1369          * bit set, force large allocations to start above 64k.
1370          */
1371         if (!w->valid)
1372                 return (EINVAL);
1373         if (sc->bridgectl & PCIB_BCR_ISA_ENABLE && count > 0x100 &&
1374             start < 65536)
1375                 start = 65536;
1376         if (end > w->rman.rm_end)
1377                 end = w->rman.rm_end;
1378         if (start + count - 1 > end || start + count < start)
1379                 return (EINVAL);
1380         wmask = (1ul << w->step) - 1;
1381
1382         /*
1383          * If there is no resource at all, just try to allocate enough
1384          * aligned space for this resource.
1385          */
1386         if (w->res == NULL) {
1387                 error = pcib_alloc_new_window(sc, w, type, start, end, count,
1388                     flags);
1389                 if (error) {
1390                         if (bootverbose)
1391                                 device_printf(sc->dev,
1392                     "failed to allocate initial %s window (%#lx-%#lx,%#lx)\n",
1393                                     w->name, start, end, count);
1394                         return (error);
1395                 }
1396                 if (bootverbose)
1397                         device_printf(sc->dev,
1398                             "allocated initial %s window of %#jx-%#jx\n",
1399                             w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
1400                 goto updatewin;
1401         }
1402
1403         /*
1404          * See if growing the window would help.  Compute the minimum
1405          * amount of address space needed on both the front and back
1406          * ends of the existing window to satisfy the allocation.
1407          *
1408          * For each end, build a candidate region adjusting for the
1409          * required alignment, etc.  If there is a free region at the
1410          * edge of the window, grow from the inner edge of the free
1411          * region.  Otherwise grow from the window boundary.
1412          *
1413          * Growing an I/O window below 64k for a bridge with the ISA
1414          * enable bit doesn't require any special magic as the step
1415          * size of an I/O window (1k) always includes multiple
1416          * non-alias ranges when it is grown in either direction.
1417          *
1418          * XXX: Special case: if w->res is completely empty and the
1419          * request size is larger than w->res, we should find the
1420          * optimal aligned buffer containing w->res and allocate that.
1421          */
1422         if (bootverbose)
1423                 device_printf(sc->dev,
1424                     "attempting to grow %s window for (%#lx-%#lx,%#lx)\n",
1425                     w->name, start, end, count);
1426         align = 1ul << RF_ALIGNMENT(flags);
1427         if (start < w->base) {
1428                 if (rman_first_free_region(&w->rman, &start_free, &end_free) !=
1429                     0 || start_free != w->base)
1430                         end_free = w->base;
1431                 if (end_free > end)
1432                         end_free = end + 1;
1433
1434                 /* Move end_free down until it is properly aligned. */
1435                 end_free &= ~(align - 1);
1436                 end_free--;
1437                 front = end_free - (count - 1);
1438
1439                 /*
1440                  * The resource would now be allocated at (front,
1441                  * end_free).  Ensure that fits in the (start, end)
1442                  * bounds.  end_free is checked above.  If 'front' is
1443                  * ok, ensure it is properly aligned for this window.
1444                  * Also check for underflow.
1445                  */
1446                 if (front >= start && front <= end_free) {
1447                         if (bootverbose)
1448                                 printf("\tfront candidate range: %#lx-%#lx\n",
1449                                     front, end_free);
1450                         front &= ~wmask;
1451                         front = w->base - front;
1452                 } else
1453                         front = 0;
1454         } else
1455                 front = 0;
1456         if (end > w->limit) {
1457                 if (rman_last_free_region(&w->rman, &start_free, &end_free) !=
1458                     0 || end_free != w->limit)
1459                         start_free = w->limit + 1;
1460                 if (start_free < start)
1461                         start_free = start;
1462
1463                 /* Move start_free up until it is properly aligned. */
1464                 start_free = roundup2(start_free, align);
1465                 back = start_free + count - 1;
1466
1467                 /*
1468                  * The resource would now be allocated at (start_free,
1469                  * back).  Ensure that fits in the (start, end)
1470                  * bounds.  start_free is checked above.  If 'back' is
1471                  * ok, ensure it is properly aligned for this window.
1472                  * Also check for overflow.
1473                  */
1474                 if (back <= end && start_free <= back) {
1475                         if (bootverbose)
1476                                 printf("\tback candidate range: %#lx-%#lx\n",
1477                                     start_free, back);
1478                         back |= wmask;
1479                         back -= w->limit;
1480                 } else
1481                         back = 0;
1482         } else
1483                 back = 0;
1484
1485         /*
1486          * Try to allocate the smallest needed region first.
1487          * If that fails, fall back to the other region.
1488          */
1489         error = ENOSPC;
1490         while (front != 0 || back != 0) {
1491                 if (front != 0 && (front <= back || back == 0)) {
1492                         error = pcib_expand_window(sc, w, type, w->base - front,
1493                             w->limit);
1494                         if (error == 0)
1495                                 break;
1496                         front = 0;
1497                 } else {
1498                         error = pcib_expand_window(sc, w, type, w->base,
1499                             w->limit + back);
1500                         if (error == 0)
1501                                 break;
1502                         back = 0;
1503                 }
1504         }
1505
1506         if (error)
1507                 return (error);
1508         if (bootverbose)
1509                 device_printf(sc->dev, "grew %s window to %#jx-%#jx\n",
1510                     w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
1511
1512 updatewin:
1513         /* Write the new window. */
1514         KASSERT((w->base & wmask) == 0, ("start address is not aligned"));
1515         KASSERT((w->limit & wmask) == wmask, ("end address is not aligned"));
1516         pcib_write_windows(sc, w->mask);
1517         return (0);
1518 }
1519
1520 /*
1521  * We have to trap resource allocation requests and ensure that the bridge
1522  * is set up to, or capable of handling them.
1523  */
1524 struct resource *
1525 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid,
1526     u_long start, u_long end, u_long count, u_int flags)
1527 {
1528         struct pcib_softc *sc;
1529         struct resource *r;
1530
1531         sc = device_get_softc(dev);
1532
1533         /*
1534          * VGA resources are decoded iff the VGA enable bit is set in
1535          * the bridge control register.  VGA resources do not fall into
1536          * the resource windows and are passed up to the parent.
1537          */
1538         if ((type == SYS_RES_IOPORT && pci_is_vga_ioport_range(start, end)) ||
1539             (type == SYS_RES_MEMORY && pci_is_vga_memory_range(start, end))) {
1540                 if (sc->bridgectl & PCIB_BCR_VGA_ENABLE)
1541                         return (bus_generic_alloc_resource(dev, child, type,
1542                             rid, start, end, count, flags));
1543                 else
1544                         return (NULL);
1545         }
1546
1547         switch (type) {
1548 #ifdef PCI_RES_BUS
1549         case PCI_RES_BUS:
1550                 return (pcib_alloc_subbus(&sc->bus, child, rid, start, end,
1551                     count, flags));
1552 #endif
1553         case SYS_RES_IOPORT:
1554                 if (pcib_is_isa_range(sc, start, end, count))
1555                         return (NULL);
1556                 r = pcib_suballoc_resource(sc, &sc->io, child, type, rid, start,
1557                     end, count, flags);
1558                 if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
1559                         break;
1560                 if (pcib_grow_window(sc, &sc->io, type, start, end, count,
1561                     flags) == 0)
1562                         r = pcib_suballoc_resource(sc, &sc->io, child, type,
1563                             rid, start, end, count, flags);
1564                 break;
1565         case SYS_RES_MEMORY:
1566                 /*
1567                  * For prefetchable resources, prefer the prefetchable
1568                  * memory window, but fall back to the regular memory
1569                  * window if that fails.  Try both windows before
1570                  * attempting to grow a window in case the firmware
1571                  * has used a range in the regular memory window to
1572                  * map a prefetchable BAR.
1573                  */
1574                 if (flags & RF_PREFETCHABLE) {
1575                         r = pcib_suballoc_resource(sc, &sc->pmem, child, type,
1576                             rid, start, end, count, flags);
1577                         if (r != NULL)
1578                                 break;
1579                 }
1580                 r = pcib_suballoc_resource(sc, &sc->mem, child, type, rid,
1581                     start, end, count, flags);
1582                 if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
1583                         break;
1584                 if (flags & RF_PREFETCHABLE) {
1585                         if (pcib_grow_window(sc, &sc->pmem, type, start, end,
1586                             count, flags) == 0) {
1587                                 r = pcib_suballoc_resource(sc, &sc->pmem, child,
1588                                     type, rid, start, end, count, flags);
1589                                 if (r != NULL)
1590                                         break;
1591                         }
1592                 }
1593                 if (pcib_grow_window(sc, &sc->mem, type, start, end, count,
1594                     flags & ~RF_PREFETCHABLE) == 0)
1595                         r = pcib_suballoc_resource(sc, &sc->mem, child, type,
1596                             rid, start, end, count, flags);
1597                 break;
1598         default:
1599                 return (bus_generic_alloc_resource(dev, child, type, rid,
1600                     start, end, count, flags));
1601         }
1602
1603         /*
1604          * If attempts to suballocate from the window fail but this is a
1605          * subtractive bridge, pass the request up the tree.
1606          */
1607         if (sc->flags & PCIB_SUBTRACTIVE && r == NULL)
1608                 return (bus_generic_alloc_resource(dev, child, type, rid,
1609                     start, end, count, flags));
1610         return (r);
1611 }
1612
1613 int
1614 pcib_adjust_resource(device_t bus, device_t child, int type, struct resource *r,
1615     u_long start, u_long end)
1616 {
1617         struct pcib_softc *sc;
1618
1619         sc = device_get_softc(bus);
1620         if (pcib_is_resource_managed(sc, type, r))
1621                 return (rman_adjust_resource(r, start, end));
1622         return (bus_generic_adjust_resource(bus, child, type, r, start, end));
1623 }
1624
1625 int
1626 pcib_release_resource(device_t dev, device_t child, int type, int rid,
1627     struct resource *r)
1628 {
1629         struct pcib_softc *sc;
1630         int error;
1631
1632         sc = device_get_softc(dev);
1633         if (pcib_is_resource_managed(sc, type, r)) {
1634                 if (rman_get_flags(r) & RF_ACTIVE) {
1635                         error = bus_deactivate_resource(child, type, rid, r);
1636                         if (error)
1637                                 return (error);
1638                 }
1639                 return (rman_release_resource(r));
1640         }
1641         return (bus_generic_release_resource(dev, child, type, rid, r));
1642 }
1643 #else
1644 /*
1645  * We have to trap resource allocation requests and ensure that the bridge
1646  * is set up to, or capable of handling them.
1647  */
1648 struct resource *
1649 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid, 
1650     u_long start, u_long end, u_long count, u_int flags)
1651 {
1652         struct pcib_softc       *sc = device_get_softc(dev);
1653         const char *name, *suffix;
1654         int ok;
1655
1656         /*
1657          * Fail the allocation for this range if it's not supported.
1658          */
1659         name = device_get_nameunit(child);
1660         if (name == NULL) {
1661                 name = "";
1662                 suffix = "";
1663         } else
1664                 suffix = " ";
1665         switch (type) {
1666         case SYS_RES_IOPORT:
1667                 ok = 0;
1668                 if (!pcib_is_io_open(sc))
1669                         break;
1670                 ok = (start >= sc->iobase && end <= sc->iolimit);
1671
1672                 /*
1673                  * Make sure we allow access to VGA I/O addresses when the
1674                  * bridge has the "VGA Enable" bit set.
1675                  */
1676                 if (!ok && pci_is_vga_ioport_range(start, end))
1677                         ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
1678
1679                 if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
1680                         if (!ok) {
1681                                 if (start < sc->iobase)
1682                                         start = sc->iobase;
1683                                 if (end > sc->iolimit)
1684                                         end = sc->iolimit;
1685                                 if (start < end)
1686                                         ok = 1;
1687                         }
1688                 } else {
1689                         ok = 1;
1690 #if 0
1691                         /*
1692                          * If we overlap with the subtractive range, then
1693                          * pick the upper range to use.
1694                          */
1695                         if (start < sc->iolimit && end > sc->iobase)
1696                                 start = sc->iolimit + 1;
1697 #endif
1698                 }
1699                 if (end < start) {
1700                         device_printf(dev, "ioport: end (%lx) < start (%lx)\n",
1701                             end, start);
1702                         start = 0;
1703                         end = 0;
1704                         ok = 0;
1705                 }
1706                 if (!ok) {
1707                         device_printf(dev, "%s%srequested unsupported I/O "
1708                             "range 0x%lx-0x%lx (decoding 0x%x-0x%x)\n",
1709                             name, suffix, start, end, sc->iobase, sc->iolimit);
1710                         return (NULL);
1711                 }
1712                 if (bootverbose)
1713                         device_printf(dev,
1714                             "%s%srequested I/O range 0x%lx-0x%lx: in range\n",
1715                             name, suffix, start, end);
1716                 break;
1717
1718         case SYS_RES_MEMORY:
1719                 ok = 0;
1720                 if (pcib_is_nonprefetch_open(sc))
1721                         ok = ok || (start >= sc->membase && end <= sc->memlimit);
1722                 if (pcib_is_prefetch_open(sc))
1723                         ok = ok || (start >= sc->pmembase && end <= sc->pmemlimit);
1724
1725                 /*
1726                  * Make sure we allow access to VGA memory addresses when the
1727                  * bridge has the "VGA Enable" bit set.
1728                  */
1729                 if (!ok && pci_is_vga_memory_range(start, end))
1730                         ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
1731
1732                 if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
1733                         if (!ok) {
1734                                 ok = 1;
1735                                 if (flags & RF_PREFETCHABLE) {
1736                                         if (pcib_is_prefetch_open(sc)) {
1737                                                 if (start < sc->pmembase)
1738                                                         start = sc->pmembase;
1739                                                 if (end > sc->pmemlimit)
1740                                                         end = sc->pmemlimit;
1741                                         } else {
1742                                                 ok = 0;
1743                                         }
1744                                 } else {        /* non-prefetchable */
1745                                         if (pcib_is_nonprefetch_open(sc)) {
1746                                                 if (start < sc->membase)
1747                                                         start = sc->membase;
1748                                                 if (end > sc->memlimit)
1749                                                         end = sc->memlimit;
1750                                         } else {
1751                                                 ok = 0;
1752                                         }
1753                                 }
1754                         }
1755                 } else if (!ok) {
1756                         ok = 1; /* subtractive bridge: always ok */
1757 #if 0
1758                         if (pcib_is_nonprefetch_open(sc)) {
1759                                 if (start < sc->memlimit && end > sc->membase)
1760                                         start = sc->memlimit + 1;
1761                         }
1762                         if (pcib_is_prefetch_open(sc)) {
1763                                 if (start < sc->pmemlimit && end > sc->pmembase)
1764                                         start = sc->pmemlimit + 1;
1765                         }
1766 #endif
1767                 }
1768                 if (end < start) {
1769                         device_printf(dev, "memory: end (%lx) < start (%lx)\n",
1770                             end, start);
1771                         start = 0;
1772                         end = 0;
1773                         ok = 0;
1774                 }
1775                 if (!ok && bootverbose)
1776                         device_printf(dev,
1777                             "%s%srequested unsupported memory range %#lx-%#lx "
1778                             "(decoding %#jx-%#jx, %#jx-%#jx)\n",
1779                             name, suffix, start, end,
1780                             (uintmax_t)sc->membase, (uintmax_t)sc->memlimit,
1781                             (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
1782                 if (!ok)
1783                         return (NULL);
1784                 if (bootverbose)
1785                         device_printf(dev,"%s%srequested memory range "
1786                             "0x%lx-0x%lx: good\n",
1787                             name, suffix, start, end);
1788                 break;
1789
1790         default:
1791                 break;
1792         }
1793         /*
1794          * Bridge is OK decoding this resource, so pass it up.
1795          */
1796         return (bus_generic_alloc_resource(dev, child, type, rid, start, end,
1797             count, flags));
1798 }
1799 #endif
1800
1801 /*
1802  * If ARI is enabled on this downstream port, translate the function number
1803  * to the non-ARI slot/function.  The downstream port will convert it back in
1804  * hardware.  If ARI is not enabled slot and func are not modified.
1805  */
1806 static __inline void
1807 pcib_xlate_ari(device_t pcib, int bus, int *slot, int *func)
1808 {
1809         struct pcib_softc *sc;
1810         int ari_func;
1811
1812         sc = device_get_softc(pcib);
1813         ari_func = *func;
1814
1815         if (sc->flags & PCIB_ENABLE_ARI) {
1816                 KASSERT(*slot == 0,
1817                     ("Non-zero slot number with ARI enabled!"));
1818                 *slot = PCIE_ARI_SLOT(ari_func);
1819                 *func = PCIE_ARI_FUNC(ari_func);
1820         }
1821 }
1822
1823
1824 static void
1825 pcib_enable_ari(struct pcib_softc *sc, uint32_t pcie_pos)
1826 {
1827         uint32_t ctl2;
1828
1829         ctl2 = pci_read_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, 4);
1830         ctl2 |= PCIEM_CTL2_ARI;
1831         pci_write_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, ctl2, 4);
1832
1833         sc->flags |= PCIB_ENABLE_ARI;
1834 }
1835
1836 /*
1837  * PCIB interface.
1838  */
1839 int
1840 pcib_maxslots(device_t dev)
1841 {
1842         return (PCI_SLOTMAX);
1843 }
1844
1845 static int
1846 pcib_ari_maxslots(device_t dev)
1847 {
1848         struct pcib_softc *sc;
1849
1850         sc = device_get_softc(dev);
1851
1852         if (sc->flags & PCIB_ENABLE_ARI)
1853                 return (PCIE_ARI_SLOTMAX);
1854         else
1855                 return (PCI_SLOTMAX);
1856 }
1857
1858 static int
1859 pcib_ari_maxfuncs(device_t dev)
1860 {
1861         struct pcib_softc *sc;
1862
1863         sc = device_get_softc(dev);
1864
1865         if (sc->flags & PCIB_ENABLE_ARI)
1866                 return (PCIE_ARI_FUNCMAX);
1867         else
1868                 return (PCI_FUNCMAX);
1869 }
1870
1871 /*
1872  * Since we are a child of a PCI bus, its parent must support the pcib interface.
1873  */
1874 static uint32_t
1875 pcib_read_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, int width)
1876 {
1877
1878         pcib_xlate_ari(dev, b, &s, &f);
1879         return(PCIB_READ_CONFIG(device_get_parent(device_get_parent(dev)), b, s,
1880             f, reg, width));
1881 }
1882
1883 static void
1884 pcib_write_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, uint32_t val, int width)
1885 {
1886
1887         pcib_xlate_ari(dev, b, &s, &f);
1888         PCIB_WRITE_CONFIG(device_get_parent(device_get_parent(dev)), b, s, f,
1889             reg, val, width);
1890 }
1891
1892 /*
1893  * Route an interrupt across a PCI bridge.
1894  */
1895 int
1896 pcib_route_interrupt(device_t pcib, device_t dev, int pin)
1897 {
1898     device_t    bus;
1899     int         parent_intpin;
1900     int         intnum;
1901
1902     /*  
1903      *
1904      * The PCI standard defines a swizzle of the child-side device/intpin to
1905      * the parent-side intpin as follows.
1906      *
1907      * device = device on child bus
1908      * child_intpin = intpin on child bus slot (0-3)
1909      * parent_intpin = intpin on parent bus slot (0-3)
1910      *
1911      * parent_intpin = (device + child_intpin) % 4
1912      */
1913     parent_intpin = (pci_get_slot(dev) + (pin - 1)) % 4;
1914
1915     /*
1916      * Our parent is a PCI bus.  Its parent must export the pcib interface
1917      * which includes the ability to route interrupts.
1918      */
1919     bus = device_get_parent(pcib);
1920     intnum = PCIB_ROUTE_INTERRUPT(device_get_parent(bus), pcib, parent_intpin + 1);
1921     if (PCI_INTERRUPT_VALID(intnum) && bootverbose) {
1922         device_printf(pcib, "slot %d INT%c is routed to irq %d\n",
1923             pci_get_slot(dev), 'A' + pin - 1, intnum);
1924     }
1925     return(intnum);
1926 }
1927
1928 /* Pass request to alloc MSI/MSI-X messages up to the parent bridge. */
1929 int
1930 pcib_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
1931 {
1932         struct pcib_softc *sc = device_get_softc(pcib);
1933         device_t bus;
1934
1935         if (sc->flags & PCIB_DISABLE_MSI)
1936                 return (ENXIO);
1937         bus = device_get_parent(pcib);
1938         return (PCIB_ALLOC_MSI(device_get_parent(bus), dev, count, maxcount,
1939             irqs));
1940 }
1941
1942 /* Pass request to release MSI/MSI-X messages up to the parent bridge. */
1943 int
1944 pcib_release_msi(device_t pcib, device_t dev, int count, int *irqs)
1945 {
1946         device_t bus;
1947
1948         bus = device_get_parent(pcib);
1949         return (PCIB_RELEASE_MSI(device_get_parent(bus), dev, count, irqs));
1950 }
1951
1952 /* Pass request to alloc an MSI-X message up to the parent bridge. */
1953 int
1954 pcib_alloc_msix(device_t pcib, device_t dev, int *irq)
1955 {
1956         struct pcib_softc *sc = device_get_softc(pcib);
1957         device_t bus;
1958
1959         if (sc->flags & PCIB_DISABLE_MSIX)
1960                 return (ENXIO);
1961         bus = device_get_parent(pcib);
1962         return (PCIB_ALLOC_MSIX(device_get_parent(bus), dev, irq));
1963 }
1964
1965 /* Pass request to release an MSI-X message up to the parent bridge. */
1966 int
1967 pcib_release_msix(device_t pcib, device_t dev, int irq)
1968 {
1969         device_t bus;
1970
1971         bus = device_get_parent(pcib);
1972         return (PCIB_RELEASE_MSIX(device_get_parent(bus), dev, irq));
1973 }
1974
1975 /* Pass request to map MSI/MSI-X message up to parent bridge. */
1976 int
1977 pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
1978     uint32_t *data)
1979 {
1980         device_t bus;
1981         int error;
1982
1983         bus = device_get_parent(pcib);
1984         error = PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data);
1985         if (error)
1986                 return (error);
1987
1988         pci_ht_map_msi(pcib, *addr);
1989         return (0);
1990 }
1991
1992 /* Pass request for device power state up to parent bridge. */
1993 int
1994 pcib_power_for_sleep(device_t pcib, device_t dev, int *pstate)
1995 {
1996         device_t bus;
1997
1998         bus = device_get_parent(pcib);
1999         return (PCIB_POWER_FOR_SLEEP(bus, dev, pstate));
2000 }
2001
2002 static uint16_t
2003 pcib_ari_get_rid(device_t pcib, device_t dev)
2004 {
2005         struct pcib_softc *sc;
2006         uint8_t bus, slot, func;
2007
2008         sc = device_get_softc(pcib);
2009
2010         if (sc->flags & PCIB_ENABLE_ARI) {
2011                 bus = pci_get_bus(dev);
2012                 func = pci_get_function(dev);
2013
2014                 return (PCI_ARI_RID(bus, func));
2015         } else {
2016                 bus = pci_get_bus(dev);
2017                 slot = pci_get_slot(dev);
2018                 func = pci_get_function(dev);
2019
2020                 return (PCI_RID(bus, slot, func));
2021         }
2022 }
2023
2024 /*
2025  * Check that the downstream port (pcib) and the endpoint device (dev) both
2026  * support ARI.  If so, enable it and return 0, otherwise return an error.
2027  */
2028 static int
2029 pcib_try_enable_ari(device_t pcib, device_t dev)
2030 {
2031         struct pcib_softc *sc;
2032         int error;
2033         uint32_t cap2;
2034         int ari_cap_off;
2035         uint32_t ari_ver;
2036         uint32_t pcie_pos;
2037
2038         sc = device_get_softc(pcib);
2039
2040         /*
2041          * ARI is controlled in a register in the PCIe capability structure.
2042          * If the downstream port does not have the PCIe capability structure
2043          * then it does not support ARI.
2044          */
2045         error = pci_find_cap(pcib, PCIY_EXPRESS, &pcie_pos);
2046         if (error != 0)
2047                 return (ENODEV);
2048
2049         /* Check that the PCIe port advertises ARI support. */
2050         cap2 = pci_read_config(pcib, pcie_pos + PCIER_DEVICE_CAP2, 4);
2051         if (!(cap2 & PCIEM_CAP2_ARI))
2052                 return (ENODEV);
2053
2054         /*
2055          * Check that the endpoint device advertises ARI support via the ARI
2056          * extended capability structure.
2057          */
2058         error = pci_find_extcap(dev, PCIZ_ARI, &ari_cap_off);
2059         if (error != 0)
2060                 return (ENODEV);
2061
2062         /*
2063          * Finally, check that the endpoint device supports the same version
2064          * of ARI that we do.
2065          */
2066         ari_ver = pci_read_config(dev, ari_cap_off, 4);
2067         if (PCI_EXTCAP_VER(ari_ver) != PCIB_SUPPORTED_ARI_VER) {
2068                 if (bootverbose)
2069                         device_printf(pcib,
2070                             "Unsupported version of ARI (%d) detected\n",
2071                             PCI_EXTCAP_VER(ari_ver));
2072
2073                 return (ENXIO);
2074         }
2075
2076         pcib_enable_ari(sc, pcie_pos);
2077
2078         return (0);
2079 }
2080