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