xref: /freebsd/sys/dev/pci/pci_pci.c (revision 3b8f08459569bf0faa21473e5cec2491e95c9349)
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;
553 
554 	switch (pci_read_config(dev, PCIR_HDRTYPE, 1) & PCIM_HDRTYPE) {
555 	case PCIM_HDRTYPE_BRIDGE:
556 		bus->sub_reg = PCIR_SUBBUS_1;
557 		break;
558 	case PCIM_HDRTYPE_CARDBUS:
559 		bus->sub_reg = PCIR_SUBBUS_2;
560 		break;
561 	default:
562 		panic("not a PCI bridge");
563 	}
564 	bus->dev = dev;
565 	bus->rman.rm_start = 0;
566 	bus->rman.rm_end = PCI_BUSMAX;
567 	bus->rman.rm_type = RMAN_ARRAY;
568 	snprintf(buf, sizeof(buf), "%s bus numbers", device_get_nameunit(dev));
569 	bus->rman.rm_descr = strdup(buf, M_DEVBUF);
570 	error = rman_init(&bus->rman);
571 	if (error)
572 		panic("Failed to initialize %s bus number rman",
573 		    device_get_nameunit(dev));
574 
575 	/*
576 	 * Allocate a bus range.  This will return an existing bus range
577 	 * if one exists, or a new bus range if one does not.
578 	 */
579 	rid = 0;
580 	bus->res = bus_alloc_resource(dev, PCI_RES_BUS, &rid, 0ul, ~0ul,
581 	    min_count, 0);
582 	if (bus->res == NULL) {
583 		/*
584 		 * Fall back to just allocating a range of a single bus
585 		 * number.
586 		 */
587 		bus->res = bus_alloc_resource(dev, PCI_RES_BUS, &rid, 0ul, ~0ul,
588 		    1, 0);
589 	} else if (rman_get_size(bus->res) < min_count)
590 		/*
591 		 * Attempt to grow the existing range to satisfy the
592 		 * minimum desired count.
593 		 */
594 		(void)bus_adjust_resource(dev, PCI_RES_BUS, bus->res,
595 		    rman_get_start(bus->res), rman_get_start(bus->res) +
596 		    min_count - 1);
597 
598 	/*
599 	 * Add the initial resource to the rman.
600 	 */
601 	if (bus->res != NULL) {
602 		error = rman_manage_region(&bus->rman, rman_get_start(bus->res),
603 		    rman_get_end(bus->res));
604 		if (error)
605 			panic("Failed to add resource to rman");
606 		bus->sec = rman_get_start(bus->res);
607 		bus->sub = rman_get_end(bus->res);
608 	}
609 }
610 
611 static struct resource *
612 pcib_suballoc_bus(struct pcib_secbus *bus, device_t child, int *rid,
613     u_long start, u_long end, u_long count, u_int flags)
614 {
615 	struct resource *res;
616 
617 	res = rman_reserve_resource(&bus->rman, start, end, count, flags,
618 	    child);
619 	if (res == NULL)
620 		return (NULL);
621 
622 	if (bootverbose)
623 		device_printf(bus->dev,
624 		    "allocated bus range (%lu-%lu) for rid %d of %s\n",
625 		    rman_get_start(res), rman_get_end(res), *rid,
626 		    pcib_child_name(child));
627 	rman_set_rid(res, *rid);
628 	return (res);
629 }
630 
631 /*
632  * Attempt to grow the secondary bus range.  This is much simpler than
633  * for I/O windows as the range can only be grown by increasing
634  * subbus.
635  */
636 static int
637 pcib_grow_subbus(struct pcib_secbus *bus, u_long new_end)
638 {
639 	u_long old_end;
640 	int error;
641 
642 	old_end = rman_get_end(bus->res);
643 	KASSERT(new_end > old_end, ("attempt to shrink subbus"));
644 	error = bus_adjust_resource(bus->dev, PCI_RES_BUS, bus->res,
645 	    rman_get_start(bus->res), new_end);
646 	if (error)
647 		return (error);
648 	if (bootverbose)
649 		device_printf(bus->dev, "grew bus range to %lu-%lu\n",
650 		    rman_get_start(bus->res), rman_get_end(bus->res));
651 	error = rman_manage_region(&bus->rman, old_end + 1,
652 	    rman_get_end(bus->res));
653 	if (error)
654 		panic("Failed to add resource to rman");
655 	bus->sub = rman_get_end(bus->res);
656 	pci_write_config(bus->dev, bus->sub_reg, bus->sub, 1);
657 	return (0);
658 }
659 
660 struct resource *
661 pcib_alloc_subbus(struct pcib_secbus *bus, device_t child, int *rid,
662     u_long start, u_long end, u_long count, u_int flags)
663 {
664 	struct resource *res;
665 	u_long start_free, end_free, new_end;
666 
667 	/*
668 	 * First, see if the request can be satisified by the existing
669 	 * bus range.
670 	 */
671 	res = pcib_suballoc_bus(bus, child, rid, start, end, count, flags);
672 	if (res != NULL)
673 		return (res);
674 
675 	/*
676 	 * Figure out a range to grow the bus range.  First, find the
677 	 * first bus number after the last allocated bus in the rman and
678 	 * enforce that as a minimum starting point for the range.
679 	 */
680 	if (rman_last_free_region(&bus->rman, &start_free, &end_free) != 0 ||
681 	    end_free != bus->sub)
682 		start_free = bus->sub + 1;
683 	if (start_free < start)
684 		start_free = start;
685 	new_end = start_free + count - 1;
686 
687 	/*
688 	 * See if this new range would satisfy the request if it
689 	 * succeeds.
690 	 */
691 	if (new_end > end)
692 		return (NULL);
693 
694 	/* Finally, attempt to grow the existing resource. */
695 	if (bootverbose) {
696 		device_printf(bus->dev,
697 		    "attempting to grow bus range for %lu buses\n", count);
698 		printf("\tback candidate range: %lu-%lu\n", start_free,
699 		    new_end);
700 	}
701 	if (pcib_grow_subbus(bus, new_end) == 0)
702 		return (pcib_suballoc_bus(bus, child, rid, start, end, count,
703 		    flags));
704 	return (NULL);
705 }
706 #endif
707 
708 #else
709 
710 /*
711  * Is the prefetch window open (eg, can we allocate memory in it?)
712  */
713 static int
714 pcib_is_prefetch_open(struct pcib_softc *sc)
715 {
716 	return (sc->pmembase > 0 && sc->pmembase < sc->pmemlimit);
717 }
718 
719 /*
720  * Is the nonprefetch window open (eg, can we allocate memory in it?)
721  */
722 static int
723 pcib_is_nonprefetch_open(struct pcib_softc *sc)
724 {
725 	return (sc->membase > 0 && sc->membase < sc->memlimit);
726 }
727 
728 /*
729  * Is the io window open (eg, can we allocate ports in it?)
730  */
731 static int
732 pcib_is_io_open(struct pcib_softc *sc)
733 {
734 	return (sc->iobase > 0 && sc->iobase < sc->iolimit);
735 }
736 
737 /*
738  * Get current I/O decode.
739  */
740 static void
741 pcib_get_io_decode(struct pcib_softc *sc)
742 {
743 	device_t	dev;
744 	uint32_t	iolow;
745 
746 	dev = sc->dev;
747 
748 	iolow = pci_read_config(dev, PCIR_IOBASEL_1, 1);
749 	if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
750 		sc->iobase = PCI_PPBIOBASE(
751 		    pci_read_config(dev, PCIR_IOBASEH_1, 2), iolow);
752 	else
753 		sc->iobase = PCI_PPBIOBASE(0, iolow);
754 
755 	iolow = pci_read_config(dev, PCIR_IOLIMITL_1, 1);
756 	if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
757 		sc->iolimit = PCI_PPBIOLIMIT(
758 		    pci_read_config(dev, PCIR_IOLIMITH_1, 2), iolow);
759 	else
760 		sc->iolimit = PCI_PPBIOLIMIT(0, iolow);
761 }
762 
763 /*
764  * Get current memory decode.
765  */
766 static void
767 pcib_get_mem_decode(struct pcib_softc *sc)
768 {
769 	device_t	dev;
770 	pci_addr_t	pmemlow;
771 
772 	dev = sc->dev;
773 
774 	sc->membase = PCI_PPBMEMBASE(0,
775 	    pci_read_config(dev, PCIR_MEMBASE_1, 2));
776 	sc->memlimit = PCI_PPBMEMLIMIT(0,
777 	    pci_read_config(dev, PCIR_MEMLIMIT_1, 2));
778 
779 	pmemlow = pci_read_config(dev, PCIR_PMBASEL_1, 2);
780 	if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64)
781 		sc->pmembase = PCI_PPBMEMBASE(
782 		    pci_read_config(dev, PCIR_PMBASEH_1, 4), pmemlow);
783 	else
784 		sc->pmembase = PCI_PPBMEMBASE(0, pmemlow);
785 
786 	pmemlow = pci_read_config(dev, PCIR_PMLIMITL_1, 2);
787 	if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64)
788 		sc->pmemlimit = PCI_PPBMEMLIMIT(
789 		    pci_read_config(dev, PCIR_PMLIMITH_1, 4), pmemlow);
790 	else
791 		sc->pmemlimit = PCI_PPBMEMLIMIT(0, pmemlow);
792 }
793 
794 /*
795  * Restore previous I/O decode.
796  */
797 static void
798 pcib_set_io_decode(struct pcib_softc *sc)
799 {
800 	device_t	dev;
801 	uint32_t	iohi;
802 
803 	dev = sc->dev;
804 
805 	iohi = sc->iobase >> 16;
806 	if (iohi > 0)
807 		pci_write_config(dev, PCIR_IOBASEH_1, iohi, 2);
808 	pci_write_config(dev, PCIR_IOBASEL_1, sc->iobase >> 8, 1);
809 
810 	iohi = sc->iolimit >> 16;
811 	if (iohi > 0)
812 		pci_write_config(dev, PCIR_IOLIMITH_1, iohi, 2);
813 	pci_write_config(dev, PCIR_IOLIMITL_1, sc->iolimit >> 8, 1);
814 }
815 
816 /*
817  * Restore previous memory decode.
818  */
819 static void
820 pcib_set_mem_decode(struct pcib_softc *sc)
821 {
822 	device_t	dev;
823 	pci_addr_t	pmemhi;
824 
825 	dev = sc->dev;
826 
827 	pci_write_config(dev, PCIR_MEMBASE_1, sc->membase >> 16, 2);
828 	pci_write_config(dev, PCIR_MEMLIMIT_1, sc->memlimit >> 16, 2);
829 
830 	pmemhi = sc->pmembase >> 32;
831 	if (pmemhi > 0)
832 		pci_write_config(dev, PCIR_PMBASEH_1, pmemhi, 4);
833 	pci_write_config(dev, PCIR_PMBASEL_1, sc->pmembase >> 16, 2);
834 
835 	pmemhi = sc->pmemlimit >> 32;
836 	if (pmemhi > 0)
837 		pci_write_config(dev, PCIR_PMLIMITH_1, pmemhi, 4);
838 	pci_write_config(dev, PCIR_PMLIMITL_1, sc->pmemlimit >> 16, 2);
839 }
840 #endif
841 
842 /*
843  * Get current bridge configuration.
844  */
845 static void
846 pcib_cfg_save(struct pcib_softc *sc)
847 {
848 	device_t	dev;
849 
850 	dev = sc->dev;
851 
852 	sc->command = pci_read_config(dev, PCIR_COMMAND, 2);
853 	sc->pribus = pci_read_config(dev, PCIR_PRIBUS_1, 1);
854 	sc->bus.sec = pci_read_config(dev, PCIR_SECBUS_1, 1);
855 	sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
856 	sc->bridgectl = pci_read_config(dev, PCIR_BRIDGECTL_1, 2);
857 	sc->seclat = pci_read_config(dev, PCIR_SECLAT_1, 1);
858 #ifndef NEW_PCIB
859 	if (sc->command & PCIM_CMD_PORTEN)
860 		pcib_get_io_decode(sc);
861 	if (sc->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 
874 	dev = sc->dev;
875 
876 	pci_write_config(dev, PCIR_COMMAND, sc->command, 2);
877 	pci_write_config(dev, PCIR_PRIBUS_1, sc->pribus, 1);
878 	pci_write_config(dev, PCIR_SECBUS_1, sc->bus.sec, 1);
879 	pci_write_config(dev, PCIR_SUBBUS_1, sc->bus.sub, 1);
880 	pci_write_config(dev, PCIR_BRIDGECTL_1, sc->bridgectl, 2);
881 	pci_write_config(dev, PCIR_SECLAT_1, sc->seclat, 1);
882 #ifdef NEW_PCIB
883 	pcib_write_windows(sc, WIN_IO | WIN_MEM | WIN_PMEM);
884 #else
885 	if (sc->command & PCIM_CMD_PORTEN)
886 		pcib_set_io_decode(sc);
887 	if (sc->command & PCIM_CMD_MEMEN)
888 		pcib_set_mem_decode(sc);
889 #endif
890 }
891 
892 /*
893  * Generic device interface
894  */
895 static int
896 pcib_probe(device_t dev)
897 {
898     if ((pci_get_class(dev) == PCIC_BRIDGE) &&
899 	(pci_get_subclass(dev) == PCIS_BRIDGE_PCI)) {
900 	device_set_desc(dev, "PCI-PCI bridge");
901 	return(-10000);
902     }
903     return(ENXIO);
904 }
905 
906 void
907 pcib_attach_common(device_t dev)
908 {
909     struct pcib_softc	*sc;
910     struct sysctl_ctx_list *sctx;
911     struct sysctl_oid	*soid;
912     int comma;
913 
914     sc = device_get_softc(dev);
915     sc->dev = dev;
916 
917     /*
918      * Get current bridge configuration.
919      */
920     sc->domain = pci_get_domain(dev);
921     sc->secstat = pci_read_config(dev, PCIR_SECSTAT_1, 2);
922     pcib_cfg_save(sc);
923 
924     /*
925      * The primary bus register should always be the bus of the
926      * parent.
927      */
928     sc->pribus = pci_get_bus(dev);
929     pci_write_config(dev, PCIR_PRIBUS_1, sc->pribus, 1);
930 
931     /*
932      * Setup sysctl reporting nodes
933      */
934     sctx = device_get_sysctl_ctx(dev);
935     soid = device_get_sysctl_tree(dev);
936     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "domain",
937       CTLFLAG_RD, &sc->domain, 0, "Domain number");
938     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "pribus",
939       CTLFLAG_RD, &sc->pribus, 0, "Primary bus number");
940     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "secbus",
941       CTLFLAG_RD, &sc->bus.sec, 0, "Secondary bus number");
942     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "subbus",
943       CTLFLAG_RD, &sc->bus.sub, 0, "Subordinate bus number");
944 
945     /*
946      * Quirk handling.
947      */
948     switch (pci_get_devid(dev)) {
949 #if !defined(NEW_PCIB) && !defined(PCI_RES_BUS)
950     case 0x12258086:		/* Intel 82454KX/GX (Orion) */
951 	{
952 	    uint8_t	supbus;
953 
954 	    supbus = pci_read_config(dev, 0x41, 1);
955 	    if (supbus != 0xff) {
956 		sc->bus.sec = supbus + 1;
957 		sc->bus.sub = supbus + 1;
958 	    }
959 	    break;
960 	}
961 #endif
962 
963     /*
964      * The i82380FB mobile docking controller is a PCI-PCI bridge,
965      * and it is a subtractive bridge.  However, the ProgIf is wrong
966      * so the normal setting of PCIB_SUBTRACTIVE bit doesn't
967      * happen.  There's also a Toshiba bridge that behaves this
968      * way.
969      */
970     case 0x124b8086:		/* Intel 82380FB Mobile */
971     case 0x060513d7:		/* Toshiba ???? */
972 	sc->flags |= PCIB_SUBTRACTIVE;
973 	break;
974 
975 #if !defined(NEW_PCIB) && !defined(PCI_RES_BUS)
976     /* Compaq R3000 BIOS sets wrong subordinate bus number. */
977     case 0x00dd10de:
978 	{
979 	    char *cp;
980 
981 	    if ((cp = getenv("smbios.planar.maker")) == NULL)
982 		break;
983 	    if (strncmp(cp, "Compal", 6) != 0) {
984 		freeenv(cp);
985 		break;
986 	    }
987 	    freeenv(cp);
988 	    if ((cp = getenv("smbios.planar.product")) == NULL)
989 		break;
990 	    if (strncmp(cp, "08A0", 4) != 0) {
991 		freeenv(cp);
992 		break;
993 	    }
994 	    freeenv(cp);
995 	    if (sc->bus.sub < 0xa) {
996 		pci_write_config(dev, PCIR_SUBBUS_1, 0xa, 1);
997 		sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
998 	    }
999 	    break;
1000 	}
1001 #endif
1002     }
1003 
1004     if (pci_msi_device_blacklisted(dev))
1005 	sc->flags |= PCIB_DISABLE_MSI;
1006 
1007     if (pci_msix_device_blacklisted(dev))
1008 	sc->flags |= PCIB_DISABLE_MSIX;
1009 
1010     /*
1011      * Intel 815, 845 and other chipsets say they are PCI-PCI bridges,
1012      * but have a ProgIF of 0x80.  The 82801 family (AA, AB, BAM/CAM,
1013      * BA/CA/DB and E) PCI bridges are HUB-PCI bridges, in Intelese.
1014      * This means they act as if they were subtractively decoding
1015      * bridges and pass all transactions.  Mark them and real ProgIf 1
1016      * parts as subtractive.
1017      */
1018     if ((pci_get_devid(dev) & 0xff00ffff) == 0x24008086 ||
1019       pci_read_config(dev, PCIR_PROGIF, 1) == PCIP_BRIDGE_PCI_SUBTRACTIVE)
1020 	sc->flags |= PCIB_SUBTRACTIVE;
1021 
1022 #ifdef NEW_PCIB
1023 #ifdef PCI_RES_BUS
1024     pcib_setup_secbus(dev, &sc->bus, 1);
1025 #endif
1026     pcib_probe_windows(sc);
1027 #endif
1028     if (bootverbose) {
1029 	device_printf(dev, "  domain            %d\n", sc->domain);
1030 	device_printf(dev, "  secondary bus     %d\n", sc->bus.sec);
1031 	device_printf(dev, "  subordinate bus   %d\n", sc->bus.sub);
1032 #ifdef NEW_PCIB
1033 	if (pcib_is_window_open(&sc->io))
1034 	    device_printf(dev, "  I/O decode        0x%jx-0x%jx\n",
1035 	      (uintmax_t)sc->io.base, (uintmax_t)sc->io.limit);
1036 	if (pcib_is_window_open(&sc->mem))
1037 	    device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1038 	      (uintmax_t)sc->mem.base, (uintmax_t)sc->mem.limit);
1039 	if (pcib_is_window_open(&sc->pmem))
1040 	    device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1041 	      (uintmax_t)sc->pmem.base, (uintmax_t)sc->pmem.limit);
1042 #else
1043 	if (pcib_is_io_open(sc))
1044 	    device_printf(dev, "  I/O decode        0x%x-0x%x\n",
1045 	      sc->iobase, sc->iolimit);
1046 	if (pcib_is_nonprefetch_open(sc))
1047 	    device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1048 	      (uintmax_t)sc->membase, (uintmax_t)sc->memlimit);
1049 	if (pcib_is_prefetch_open(sc))
1050 	    device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1051 	      (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
1052 #endif
1053 	if (sc->bridgectl & (PCIB_BCR_ISA_ENABLE | PCIB_BCR_VGA_ENABLE) ||
1054 	    sc->flags & PCIB_SUBTRACTIVE) {
1055 		device_printf(dev, "  special decode    ");
1056 		comma = 0;
1057 		if (sc->bridgectl & PCIB_BCR_ISA_ENABLE) {
1058 			printf("ISA");
1059 			comma = 1;
1060 		}
1061 		if (sc->bridgectl & PCIB_BCR_VGA_ENABLE) {
1062 			printf("%sVGA", comma ? ", " : "");
1063 			comma = 1;
1064 		}
1065 		if (sc->flags & PCIB_SUBTRACTIVE)
1066 			printf("%ssubtractive", comma ? ", " : "");
1067 		printf("\n");
1068 	}
1069     }
1070 
1071     /*
1072      * Always enable busmastering on bridges so that transactions
1073      * initiated on the secondary bus are passed through to the
1074      * primary bus.
1075      */
1076     pci_enable_busmaster(dev);
1077 }
1078 
1079 int
1080 pcib_attach(device_t dev)
1081 {
1082     struct pcib_softc	*sc;
1083     device_t		child;
1084 
1085     pcib_attach_common(dev);
1086     sc = device_get_softc(dev);
1087     if (sc->bus.sec != 0) {
1088 	child = device_add_child(dev, "pci", sc->bus.sec);
1089 	if (child != NULL)
1090 	    return(bus_generic_attach(dev));
1091     }
1092 
1093     /* no secondary bus; we should have fixed this */
1094     return(0);
1095 }
1096 
1097 int
1098 pcib_suspend(device_t dev)
1099 {
1100 	device_t	pcib;
1101 	int		dstate, error;
1102 
1103 	pcib_cfg_save(device_get_softc(dev));
1104 	error = bus_generic_suspend(dev);
1105 	if (error == 0 && pci_do_power_suspend) {
1106 		dstate = PCI_POWERSTATE_D3;
1107 		pcib = device_get_parent(device_get_parent(dev));
1108 		if (PCIB_POWER_FOR_SLEEP(pcib, dev, &dstate) == 0)
1109 			pci_set_powerstate(dev, dstate);
1110 	}
1111 	return (error);
1112 }
1113 
1114 int
1115 pcib_resume(device_t dev)
1116 {
1117 	device_t	pcib;
1118 
1119 	if (pci_do_power_resume) {
1120 		pcib = device_get_parent(device_get_parent(dev));
1121 		if (PCIB_POWER_FOR_SLEEP(pcib, dev, NULL) == 0)
1122 			pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1123 	}
1124 	pcib_cfg_restore(device_get_softc(dev));
1125 	return (bus_generic_resume(dev));
1126 }
1127 
1128 int
1129 pcib_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1130 {
1131     struct pcib_softc	*sc = device_get_softc(dev);
1132 
1133     switch (which) {
1134     case PCIB_IVAR_DOMAIN:
1135 	*result = sc->domain;
1136 	return(0);
1137     case PCIB_IVAR_BUS:
1138 	*result = sc->bus.sec;
1139 	return(0);
1140     }
1141     return(ENOENT);
1142 }
1143 
1144 int
1145 pcib_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1146 {
1147 
1148     switch (which) {
1149     case PCIB_IVAR_DOMAIN:
1150 	return(EINVAL);
1151     case PCIB_IVAR_BUS:
1152 	return(EINVAL);
1153     }
1154     return(ENOENT);
1155 }
1156 
1157 #ifdef NEW_PCIB
1158 /*
1159  * Attempt to allocate a resource from the existing resources assigned
1160  * to a window.
1161  */
1162 static struct resource *
1163 pcib_suballoc_resource(struct pcib_softc *sc, struct pcib_window *w,
1164     device_t child, int type, int *rid, u_long start, u_long end, u_long count,
1165     u_int flags)
1166 {
1167 	struct resource *res;
1168 
1169 	if (!pcib_is_window_open(w))
1170 		return (NULL);
1171 
1172 	res = rman_reserve_resource(&w->rman, start, end, count,
1173 	    flags & ~RF_ACTIVE, child);
1174 	if (res == NULL)
1175 		return (NULL);
1176 
1177 	if (bootverbose)
1178 		device_printf(sc->dev,
1179 		    "allocated %s range (%#lx-%#lx) for rid %x of %s\n",
1180 		    w->name, rman_get_start(res), rman_get_end(res), *rid,
1181 		    pcib_child_name(child));
1182 	rman_set_rid(res, *rid);
1183 
1184 	/*
1185 	 * If the resource should be active, pass that request up the
1186 	 * tree.  This assumes the parent drivers can handle
1187 	 * activating sub-allocated resources.
1188 	 */
1189 	if (flags & RF_ACTIVE) {
1190 		if (bus_activate_resource(child, type, *rid, res) != 0) {
1191 			rman_release_resource(res);
1192 			return (NULL);
1193 		}
1194 	}
1195 
1196 	return (res);
1197 }
1198 
1199 /* Allocate a fresh resource range for an unconfigured window. */
1200 static int
1201 pcib_alloc_new_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1202     u_long start, u_long end, u_long count, u_int flags)
1203 {
1204 	struct resource *res;
1205 	u_long base, limit, wmask;
1206 	int rid;
1207 
1208 	/*
1209 	 * If this is an I/O window on a bridge with ISA enable set
1210 	 * and the start address is below 64k, then try to allocate an
1211 	 * initial window of 0x1000 bytes long starting at address
1212 	 * 0xf000 and walking down.  Note that if the original request
1213 	 * was larger than the non-aliased range size of 0x100 our
1214 	 * caller would have raised the start address up to 64k
1215 	 * already.
1216 	 */
1217 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1218 	    start < 65536) {
1219 		for (base = 0xf000; (long)base >= 0; base -= 0x1000) {
1220 			limit = base + 0xfff;
1221 
1222 			/*
1223 			 * Skip ranges that wouldn't work for the
1224 			 * original request.  Note that the actual
1225 			 * window that overlaps are the non-alias
1226 			 * ranges within [base, limit], so this isn't
1227 			 * quite a simple comparison.
1228 			 */
1229 			if (start + count > limit - 0x400)
1230 				continue;
1231 			if (base == 0) {
1232 				/*
1233 				 * The first open region for the window at
1234 				 * 0 is 0x400-0x4ff.
1235 				 */
1236 				if (end - count + 1 < 0x400)
1237 					continue;
1238 			} else {
1239 				if (end - count + 1 < base)
1240 					continue;
1241 			}
1242 
1243 			if (pcib_alloc_nonisa_ranges(sc, base, limit) == 0) {
1244 				w->base = base;
1245 				w->limit = limit;
1246 				return (0);
1247 			}
1248 		}
1249 		return (ENOSPC);
1250 	}
1251 
1252 	wmask = (1ul << w->step) - 1;
1253 	if (RF_ALIGNMENT(flags) < w->step) {
1254 		flags &= ~RF_ALIGNMENT_MASK;
1255 		flags |= RF_ALIGNMENT_LOG2(w->step);
1256 	}
1257 	start &= ~wmask;
1258 	end |= wmask;
1259 	count = roundup2(count, 1ul << w->step);
1260 	rid = w->reg;
1261 	res = bus_alloc_resource(sc->dev, type, &rid, start, end, count,
1262 	    flags & ~RF_ACTIVE);
1263 	if (res == NULL)
1264 		return (ENOSPC);
1265 	pcib_add_window_resources(w, &res, 1);
1266 	pcib_activate_window(sc, type);
1267 	w->base = rman_get_start(res);
1268 	w->limit = rman_get_end(res);
1269 	return (0);
1270 }
1271 
1272 /* Try to expand an existing window to the requested base and limit. */
1273 static int
1274 pcib_expand_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1275     u_long base, u_long limit)
1276 {
1277 	struct resource *res;
1278 	int error, i, force_64k_base;
1279 
1280 	KASSERT(base <= w->base && limit >= w->limit,
1281 	    ("attempting to shrink window"));
1282 
1283 	/*
1284 	 * XXX: pcib_grow_window() doesn't try to do this anyway and
1285 	 * the error handling for all the edge cases would be tedious.
1286 	 */
1287 	KASSERT(limit == w->limit || base == w->base,
1288 	    ("attempting to grow both ends of a window"));
1289 
1290 	/*
1291 	 * Yet more special handling for requests to expand an I/O
1292 	 * window behind an ISA-enabled bridge.  Since I/O windows
1293 	 * have to grow in 0x1000 increments and the end of the 0xffff
1294 	 * range is an alias, growing a window below 64k will always
1295 	 * result in allocating new resources and never adjusting an
1296 	 * existing resource.
1297 	 */
1298 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1299 	    (limit <= 65535 || (base <= 65535 && base != w->base))) {
1300 		KASSERT(limit == w->limit || limit <= 65535,
1301 		    ("attempting to grow both ends across 64k ISA alias"));
1302 
1303 		if (base != w->base)
1304 			error = pcib_alloc_nonisa_ranges(sc, base, w->base - 1);
1305 		else
1306 			error = pcib_alloc_nonisa_ranges(sc, w->limit + 1,
1307 			    limit);
1308 		if (error == 0) {
1309 			w->base = base;
1310 			w->limit = limit;
1311 		}
1312 		return (error);
1313 	}
1314 
1315 	/*
1316 	 * Find the existing resource to adjust.  Usually there is only one,
1317 	 * but for an ISA-enabled bridge we might be growing the I/O window
1318 	 * above 64k and need to find the existing resource that maps all
1319 	 * of the area above 64k.
1320 	 */
1321 	for (i = 0; i < w->count; i++) {
1322 		if (rman_get_end(w->res[i]) == w->limit)
1323 			break;
1324 	}
1325 	KASSERT(i != w->count, ("did not find existing resource"));
1326 	res = w->res[i];
1327 
1328 	/*
1329 	 * Usually the resource we found should match the window's
1330 	 * existing range.  The one exception is the ISA-enabled case
1331 	 * mentioned above in which case the resource should start at
1332 	 * 64k.
1333 	 */
1334 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1335 	    w->base <= 65535) {
1336 		KASSERT(rman_get_start(res) == 65536,
1337 		    ("existing resource mismatch"));
1338 		force_64k_base = 1;
1339 	} else {
1340 		KASSERT(w->base == rman_get_start(res),
1341 		    ("existing resource mismatch"));
1342 		force_64k_base = 0;
1343 	}
1344 
1345 	error = bus_adjust_resource(sc->dev, type, res, force_64k_base ?
1346 	    rman_get_start(res) : base, limit);
1347 	if (error)
1348 		return (error);
1349 
1350 	/* Add the newly allocated region to the resource manager. */
1351 	if (w->base != base) {
1352 		error = rman_manage_region(&w->rman, base, w->base - 1);
1353 		w->base = base;
1354 	} else {
1355 		error = rman_manage_region(&w->rman, w->limit + 1, limit);
1356 		w->limit = limit;
1357 	}
1358 	if (error) {
1359 		if (bootverbose)
1360 			device_printf(sc->dev,
1361 			    "failed to expand %s resource manager\n", w->name);
1362 		(void)bus_adjust_resource(sc->dev, type, res, force_64k_base ?
1363 		    rman_get_start(res) : w->base, w->limit);
1364 	}
1365 	return (error);
1366 }
1367 
1368 /*
1369  * Attempt to grow a window to make room for a given resource request.
1370  */
1371 static int
1372 pcib_grow_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1373     u_long start, u_long end, u_long count, u_int flags)
1374 {
1375 	u_long align, start_free, end_free, front, back, wmask;
1376 	int error;
1377 
1378 	/*
1379 	 * Clamp the desired resource range to the maximum address
1380 	 * this window supports.  Reject impossible requests.
1381 	 *
1382 	 * For I/O port requests behind a bridge with the ISA enable
1383 	 * bit set, force large allocations to start above 64k.
1384 	 */
1385 	if (!w->valid)
1386 		return (EINVAL);
1387 	if (sc->bridgectl & PCIB_BCR_ISA_ENABLE && count > 0x100 &&
1388 	    start < 65536)
1389 		start = 65536;
1390 	if (end > w->rman.rm_end)
1391 		end = w->rman.rm_end;
1392 	if (start + count - 1 > end || start + count < start)
1393 		return (EINVAL);
1394 	wmask = (1ul << w->step) - 1;
1395 
1396 	/*
1397 	 * If there is no resource at all, just try to allocate enough
1398 	 * aligned space for this resource.
1399 	 */
1400 	if (w->res == NULL) {
1401 		error = pcib_alloc_new_window(sc, w, type, start, end, count,
1402 		    flags);
1403 		if (error) {
1404 			if (bootverbose)
1405 				device_printf(sc->dev,
1406 		    "failed to allocate initial %s window (%#lx-%#lx,%#lx)\n",
1407 				    w->name, start, end, count);
1408 			return (error);
1409 		}
1410 		if (bootverbose)
1411 			device_printf(sc->dev,
1412 			    "allocated initial %s window of %#jx-%#jx\n",
1413 			    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
1414 		goto updatewin;
1415 	}
1416 
1417 	/*
1418 	 * See if growing the window would help.  Compute the minimum
1419 	 * amount of address space needed on both the front and back
1420 	 * ends of the existing window to satisfy the allocation.
1421 	 *
1422 	 * For each end, build a candidate region adjusting for the
1423 	 * required alignment, etc.  If there is a free region at the
1424 	 * edge of the window, grow from the inner edge of the free
1425 	 * region.  Otherwise grow from the window boundary.
1426 	 *
1427 	 * Growing an I/O window below 64k for a bridge with the ISA
1428 	 * enable bit doesn't require any special magic as the step
1429 	 * size of an I/O window (1k) always includes multiple
1430 	 * non-alias ranges when it is grown in either direction.
1431 	 *
1432 	 * XXX: Special case: if w->res is completely empty and the
1433 	 * request size is larger than w->res, we should find the
1434 	 * optimal aligned buffer containing w->res and allocate that.
1435 	 */
1436 	if (bootverbose)
1437 		device_printf(sc->dev,
1438 		    "attempting to grow %s window for (%#lx-%#lx,%#lx)\n",
1439 		    w->name, start, end, count);
1440 	align = 1ul << RF_ALIGNMENT(flags);
1441 	if (start < w->base) {
1442 		if (rman_first_free_region(&w->rman, &start_free, &end_free) !=
1443 		    0 || start_free != w->base)
1444 			end_free = w->base;
1445 		if (end_free > end)
1446 			end_free = end + 1;
1447 
1448 		/* Move end_free down until it is properly aligned. */
1449 		end_free &= ~(align - 1);
1450 		end_free--;
1451 		front = end_free - (count - 1);
1452 
1453 		/*
1454 		 * The resource would now be allocated at (front,
1455 		 * end_free).  Ensure that fits in the (start, end)
1456 		 * bounds.  end_free is checked above.  If 'front' is
1457 		 * ok, ensure it is properly aligned for this window.
1458 		 * Also check for underflow.
1459 		 */
1460 		if (front >= start && front <= end_free) {
1461 			if (bootverbose)
1462 				printf("\tfront candidate range: %#lx-%#lx\n",
1463 				    front, end_free);
1464 			front &= ~wmask;
1465 			front = w->base - front;
1466 		} else
1467 			front = 0;
1468 	} else
1469 		front = 0;
1470 	if (end > w->limit) {
1471 		if (rman_last_free_region(&w->rman, &start_free, &end_free) !=
1472 		    0 || end_free != w->limit)
1473 			start_free = w->limit + 1;
1474 		if (start_free < start)
1475 			start_free = start;
1476 
1477 		/* Move start_free up until it is properly aligned. */
1478 		start_free = roundup2(start_free, align);
1479 		back = start_free + count - 1;
1480 
1481 		/*
1482 		 * The resource would now be allocated at (start_free,
1483 		 * back).  Ensure that fits in the (start, end)
1484 		 * bounds.  start_free is checked above.  If 'back' is
1485 		 * ok, ensure it is properly aligned for this window.
1486 		 * Also check for overflow.
1487 		 */
1488 		if (back <= end && start_free <= back) {
1489 			if (bootverbose)
1490 				printf("\tback candidate range: %#lx-%#lx\n",
1491 				    start_free, back);
1492 			back |= wmask;
1493 			back -= w->limit;
1494 		} else
1495 			back = 0;
1496 	} else
1497 		back = 0;
1498 
1499 	/*
1500 	 * Try to allocate the smallest needed region first.
1501 	 * If that fails, fall back to the other region.
1502 	 */
1503 	error = ENOSPC;
1504 	while (front != 0 || back != 0) {
1505 		if (front != 0 && (front <= back || back == 0)) {
1506 			error = pcib_expand_window(sc, w, type, w->base - front,
1507 			    w->limit);
1508 			if (error == 0)
1509 				break;
1510 			front = 0;
1511 		} else {
1512 			error = pcib_expand_window(sc, w, type, w->base,
1513 			    w->limit + back);
1514 			if (error == 0)
1515 				break;
1516 			back = 0;
1517 		}
1518 	}
1519 
1520 	if (error)
1521 		return (error);
1522 	if (bootverbose)
1523 		device_printf(sc->dev, "grew %s window to %#jx-%#jx\n",
1524 		    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
1525 
1526 updatewin:
1527 	/* Write the new window. */
1528 	KASSERT((w->base & wmask) == 0, ("start address is not aligned"));
1529 	KASSERT((w->limit & wmask) == wmask, ("end address is not aligned"));
1530 	pcib_write_windows(sc, w->mask);
1531 	return (0);
1532 }
1533 
1534 /*
1535  * We have to trap resource allocation requests and ensure that the bridge
1536  * is set up to, or capable of handling them.
1537  */
1538 struct resource *
1539 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid,
1540     u_long start, u_long end, u_long count, u_int flags)
1541 {
1542 	struct pcib_softc *sc;
1543 	struct resource *r;
1544 
1545 	sc = device_get_softc(dev);
1546 
1547 	/*
1548 	 * VGA resources are decoded iff the VGA enable bit is set in
1549 	 * the bridge control register.  VGA resources do not fall into
1550 	 * the resource windows and are passed up to the parent.
1551 	 */
1552 	if ((type == SYS_RES_IOPORT && pci_is_vga_ioport_range(start, end)) ||
1553 	    (type == SYS_RES_MEMORY && pci_is_vga_memory_range(start, end))) {
1554 		if (sc->bridgectl & PCIB_BCR_VGA_ENABLE)
1555 			return (bus_generic_alloc_resource(dev, child, type,
1556 			    rid, start, end, count, flags));
1557 		else
1558 			return (NULL);
1559 	}
1560 
1561 	switch (type) {
1562 #ifdef PCI_RES_BUS
1563 	case PCI_RES_BUS:
1564 		return (pcib_alloc_subbus(&sc->bus, child, rid, start, end,
1565 		    count, flags));
1566 #endif
1567 	case SYS_RES_IOPORT:
1568 		if (pcib_is_isa_range(sc, start, end, count))
1569 			return (NULL);
1570 		r = pcib_suballoc_resource(sc, &sc->io, child, type, rid, start,
1571 		    end, count, flags);
1572 		if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
1573 			break;
1574 		if (pcib_grow_window(sc, &sc->io, type, start, end, count,
1575 		    flags) == 0)
1576 			r = pcib_suballoc_resource(sc, &sc->io, child, type,
1577 			    rid, start, end, count, flags);
1578 		break;
1579 	case SYS_RES_MEMORY:
1580 		/*
1581 		 * For prefetchable resources, prefer the prefetchable
1582 		 * memory window, but fall back to the regular memory
1583 		 * window if that fails.  Try both windows before
1584 		 * attempting to grow a window in case the firmware
1585 		 * has used a range in the regular memory window to
1586 		 * map a prefetchable BAR.
1587 		 */
1588 		if (flags & RF_PREFETCHABLE) {
1589 			r = pcib_suballoc_resource(sc, &sc->pmem, child, type,
1590 			    rid, start, end, count, flags);
1591 			if (r != NULL)
1592 				break;
1593 		}
1594 		r = pcib_suballoc_resource(sc, &sc->mem, child, type, rid,
1595 		    start, end, count, flags);
1596 		if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
1597 			break;
1598 		if (flags & RF_PREFETCHABLE) {
1599 			if (pcib_grow_window(sc, &sc->pmem, type, start, end,
1600 			    count, flags) == 0) {
1601 				r = pcib_suballoc_resource(sc, &sc->pmem, child,
1602 				    type, rid, start, end, count, flags);
1603 				if (r != NULL)
1604 					break;
1605 			}
1606 		}
1607 		if (pcib_grow_window(sc, &sc->mem, type, start, end, count,
1608 		    flags & ~RF_PREFETCHABLE) == 0)
1609 			r = pcib_suballoc_resource(sc, &sc->mem, child, type,
1610 			    rid, start, end, count, flags);
1611 		break;
1612 	default:
1613 		return (bus_generic_alloc_resource(dev, child, type, rid,
1614 		    start, end, count, flags));
1615 	}
1616 
1617 	/*
1618 	 * If attempts to suballocate from the window fail but this is a
1619 	 * subtractive bridge, pass the request up the tree.
1620 	 */
1621 	if (sc->flags & PCIB_SUBTRACTIVE && r == NULL)
1622 		return (bus_generic_alloc_resource(dev, child, type, rid,
1623 		    start, end, count, flags));
1624 	return (r);
1625 }
1626 
1627 int
1628 pcib_adjust_resource(device_t bus, device_t child, int type, struct resource *r,
1629     u_long start, u_long end)
1630 {
1631 	struct pcib_softc *sc;
1632 
1633 	sc = device_get_softc(bus);
1634 	if (pcib_is_resource_managed(sc, type, r))
1635 		return (rman_adjust_resource(r, start, end));
1636 	return (bus_generic_adjust_resource(bus, child, type, r, start, end));
1637 }
1638 
1639 int
1640 pcib_release_resource(device_t dev, device_t child, int type, int rid,
1641     struct resource *r)
1642 {
1643 	struct pcib_softc *sc;
1644 	int error;
1645 
1646 	sc = device_get_softc(dev);
1647 	if (pcib_is_resource_managed(sc, type, r)) {
1648 		if (rman_get_flags(r) & RF_ACTIVE) {
1649 			error = bus_deactivate_resource(child, type, rid, r);
1650 			if (error)
1651 				return (error);
1652 		}
1653 		return (rman_release_resource(r));
1654 	}
1655 	return (bus_generic_release_resource(dev, child, type, rid, r));
1656 }
1657 #else
1658 /*
1659  * We have to trap resource allocation requests and ensure that the bridge
1660  * is set up to, or capable of handling them.
1661  */
1662 struct resource *
1663 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid,
1664     u_long start, u_long end, u_long count, u_int flags)
1665 {
1666 	struct pcib_softc	*sc = device_get_softc(dev);
1667 	const char *name, *suffix;
1668 	int ok;
1669 
1670 	/*
1671 	 * Fail the allocation for this range if it's not supported.
1672 	 */
1673 	name = device_get_nameunit(child);
1674 	if (name == NULL) {
1675 		name = "";
1676 		suffix = "";
1677 	} else
1678 		suffix = " ";
1679 	switch (type) {
1680 	case SYS_RES_IOPORT:
1681 		ok = 0;
1682 		if (!pcib_is_io_open(sc))
1683 			break;
1684 		ok = (start >= sc->iobase && end <= sc->iolimit);
1685 
1686 		/*
1687 		 * Make sure we allow access to VGA I/O addresses when the
1688 		 * bridge has the "VGA Enable" bit set.
1689 		 */
1690 		if (!ok && pci_is_vga_ioport_range(start, end))
1691 			ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
1692 
1693 		if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
1694 			if (!ok) {
1695 				if (start < sc->iobase)
1696 					start = sc->iobase;
1697 				if (end > sc->iolimit)
1698 					end = sc->iolimit;
1699 				if (start < end)
1700 					ok = 1;
1701 			}
1702 		} else {
1703 			ok = 1;
1704 #if 0
1705 			/*
1706 			 * If we overlap with the subtractive range, then
1707 			 * pick the upper range to use.
1708 			 */
1709 			if (start < sc->iolimit && end > sc->iobase)
1710 				start = sc->iolimit + 1;
1711 #endif
1712 		}
1713 		if (end < start) {
1714 			device_printf(dev, "ioport: end (%lx) < start (%lx)\n",
1715 			    end, start);
1716 			start = 0;
1717 			end = 0;
1718 			ok = 0;
1719 		}
1720 		if (!ok) {
1721 			device_printf(dev, "%s%srequested unsupported I/O "
1722 			    "range 0x%lx-0x%lx (decoding 0x%x-0x%x)\n",
1723 			    name, suffix, start, end, sc->iobase, sc->iolimit);
1724 			return (NULL);
1725 		}
1726 		if (bootverbose)
1727 			device_printf(dev,
1728 			    "%s%srequested I/O range 0x%lx-0x%lx: in range\n",
1729 			    name, suffix, start, end);
1730 		break;
1731 
1732 	case SYS_RES_MEMORY:
1733 		ok = 0;
1734 		if (pcib_is_nonprefetch_open(sc))
1735 			ok = ok || (start >= sc->membase && end <= sc->memlimit);
1736 		if (pcib_is_prefetch_open(sc))
1737 			ok = ok || (start >= sc->pmembase && end <= sc->pmemlimit);
1738 
1739 		/*
1740 		 * Make sure we allow access to VGA memory addresses when the
1741 		 * bridge has the "VGA Enable" bit set.
1742 		 */
1743 		if (!ok && pci_is_vga_memory_range(start, end))
1744 			ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
1745 
1746 		if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
1747 			if (!ok) {
1748 				ok = 1;
1749 				if (flags & RF_PREFETCHABLE) {
1750 					if (pcib_is_prefetch_open(sc)) {
1751 						if (start < sc->pmembase)
1752 							start = sc->pmembase;
1753 						if (end > sc->pmemlimit)
1754 							end = sc->pmemlimit;
1755 					} else {
1756 						ok = 0;
1757 					}
1758 				} else {	/* non-prefetchable */
1759 					if (pcib_is_nonprefetch_open(sc)) {
1760 						if (start < sc->membase)
1761 							start = sc->membase;
1762 						if (end > sc->memlimit)
1763 							end = sc->memlimit;
1764 					} else {
1765 						ok = 0;
1766 					}
1767 				}
1768 			}
1769 		} else if (!ok) {
1770 			ok = 1;	/* subtractive bridge: always ok */
1771 #if 0
1772 			if (pcib_is_nonprefetch_open(sc)) {
1773 				if (start < sc->memlimit && end > sc->membase)
1774 					start = sc->memlimit + 1;
1775 			}
1776 			if (pcib_is_prefetch_open(sc)) {
1777 				if (start < sc->pmemlimit && end > sc->pmembase)
1778 					start = sc->pmemlimit + 1;
1779 			}
1780 #endif
1781 		}
1782 		if (end < start) {
1783 			device_printf(dev, "memory: end (%lx) < start (%lx)\n",
1784 			    end, start);
1785 			start = 0;
1786 			end = 0;
1787 			ok = 0;
1788 		}
1789 		if (!ok && bootverbose)
1790 			device_printf(dev,
1791 			    "%s%srequested unsupported memory range %#lx-%#lx "
1792 			    "(decoding %#jx-%#jx, %#jx-%#jx)\n",
1793 			    name, suffix, start, end,
1794 			    (uintmax_t)sc->membase, (uintmax_t)sc->memlimit,
1795 			    (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
1796 		if (!ok)
1797 			return (NULL);
1798 		if (bootverbose)
1799 			device_printf(dev,"%s%srequested memory range "
1800 			    "0x%lx-0x%lx: good\n",
1801 			    name, suffix, start, end);
1802 		break;
1803 
1804 	default:
1805 		break;
1806 	}
1807 	/*
1808 	 * Bridge is OK decoding this resource, so pass it up.
1809 	 */
1810 	return (bus_generic_alloc_resource(dev, child, type, rid, start, end,
1811 	    count, flags));
1812 }
1813 #endif
1814 
1815 /*
1816  * If ARI is enabled on this downstream port, translate the function number
1817  * to the non-ARI slot/function.  The downstream port will convert it back in
1818  * hardware.  If ARI is not enabled slot and func are not modified.
1819  */
1820 static __inline void
1821 pcib_xlate_ari(device_t pcib, int bus, int *slot, int *func)
1822 {
1823 	struct pcib_softc *sc;
1824 	int ari_func;
1825 
1826 	sc = device_get_softc(pcib);
1827 	ari_func = *func;
1828 
1829 	if (sc->flags & PCIB_ENABLE_ARI) {
1830 		KASSERT(*slot == 0,
1831 		    ("Non-zero slot number with ARI enabled!"));
1832 		*slot = PCIE_ARI_SLOT(ari_func);
1833 		*func = PCIE_ARI_FUNC(ari_func);
1834 	}
1835 }
1836 
1837 
1838 static void
1839 pcib_enable_ari(struct pcib_softc *sc, uint32_t pcie_pos)
1840 {
1841 	uint32_t ctl2;
1842 
1843 	ctl2 = pci_read_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, 4);
1844 	ctl2 |= PCIEM_CTL2_ARI;
1845 	pci_write_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, ctl2, 4);
1846 
1847 	sc->flags |= PCIB_ENABLE_ARI;
1848 }
1849 
1850 /*
1851  * PCIB interface.
1852  */
1853 int
1854 pcib_maxslots(device_t dev)
1855 {
1856 	return (PCI_SLOTMAX);
1857 }
1858 
1859 static int
1860 pcib_ari_maxslots(device_t dev)
1861 {
1862 	struct pcib_softc *sc;
1863 
1864 	sc = device_get_softc(dev);
1865 
1866 	if (sc->flags & PCIB_ENABLE_ARI)
1867 		return (PCIE_ARI_SLOTMAX);
1868 	else
1869 		return (PCI_SLOTMAX);
1870 }
1871 
1872 static int
1873 pcib_ari_maxfuncs(device_t dev)
1874 {
1875 	struct pcib_softc *sc;
1876 
1877 	sc = device_get_softc(dev);
1878 
1879 	if (sc->flags & PCIB_ENABLE_ARI)
1880 		return (PCIE_ARI_FUNCMAX);
1881 	else
1882 		return (PCI_FUNCMAX);
1883 }
1884 
1885 /*
1886  * Since we are a child of a PCI bus, its parent must support the pcib interface.
1887  */
1888 static uint32_t
1889 pcib_read_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, int width)
1890 {
1891 
1892 	pcib_xlate_ari(dev, b, &s, &f);
1893 	return(PCIB_READ_CONFIG(device_get_parent(device_get_parent(dev)), b, s,
1894 	    f, reg, width));
1895 }
1896 
1897 static void
1898 pcib_write_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, uint32_t val, int width)
1899 {
1900 
1901 	pcib_xlate_ari(dev, b, &s, &f);
1902 	PCIB_WRITE_CONFIG(device_get_parent(device_get_parent(dev)), b, s, f,
1903 	    reg, val, width);
1904 }
1905 
1906 /*
1907  * Route an interrupt across a PCI bridge.
1908  */
1909 int
1910 pcib_route_interrupt(device_t pcib, device_t dev, int pin)
1911 {
1912     device_t	bus;
1913     int		parent_intpin;
1914     int		intnum;
1915 
1916     /*
1917      *
1918      * The PCI standard defines a swizzle of the child-side device/intpin to
1919      * the parent-side intpin as follows.
1920      *
1921      * device = device on child bus
1922      * child_intpin = intpin on child bus slot (0-3)
1923      * parent_intpin = intpin on parent bus slot (0-3)
1924      *
1925      * parent_intpin = (device + child_intpin) % 4
1926      */
1927     parent_intpin = (pci_get_slot(dev) + (pin - 1)) % 4;
1928 
1929     /*
1930      * Our parent is a PCI bus.  Its parent must export the pcib interface
1931      * which includes the ability to route interrupts.
1932      */
1933     bus = device_get_parent(pcib);
1934     intnum = PCIB_ROUTE_INTERRUPT(device_get_parent(bus), pcib, parent_intpin + 1);
1935     if (PCI_INTERRUPT_VALID(intnum) && bootverbose) {
1936 	device_printf(pcib, "slot %d INT%c is routed to irq %d\n",
1937 	    pci_get_slot(dev), 'A' + pin - 1, intnum);
1938     }
1939     return(intnum);
1940 }
1941 
1942 /* Pass request to alloc MSI/MSI-X messages up to the parent bridge. */
1943 int
1944 pcib_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
1945 {
1946 	struct pcib_softc *sc = device_get_softc(pcib);
1947 	device_t bus;
1948 
1949 	if (sc->flags & PCIB_DISABLE_MSI)
1950 		return (ENXIO);
1951 	bus = device_get_parent(pcib);
1952 	return (PCIB_ALLOC_MSI(device_get_parent(bus), dev, count, maxcount,
1953 	    irqs));
1954 }
1955 
1956 /* Pass request to release MSI/MSI-X messages up to the parent bridge. */
1957 int
1958 pcib_release_msi(device_t pcib, device_t dev, int count, int *irqs)
1959 {
1960 	device_t bus;
1961 
1962 	bus = device_get_parent(pcib);
1963 	return (PCIB_RELEASE_MSI(device_get_parent(bus), dev, count, irqs));
1964 }
1965 
1966 /* Pass request to alloc an MSI-X message up to the parent bridge. */
1967 int
1968 pcib_alloc_msix(device_t pcib, device_t dev, int *irq)
1969 {
1970 	struct pcib_softc *sc = device_get_softc(pcib);
1971 	device_t bus;
1972 
1973 	if (sc->flags & PCIB_DISABLE_MSIX)
1974 		return (ENXIO);
1975 	bus = device_get_parent(pcib);
1976 	return (PCIB_ALLOC_MSIX(device_get_parent(bus), dev, irq));
1977 }
1978 
1979 /* Pass request to release an MSI-X message up to the parent bridge. */
1980 int
1981 pcib_release_msix(device_t pcib, device_t dev, int irq)
1982 {
1983 	device_t bus;
1984 
1985 	bus = device_get_parent(pcib);
1986 	return (PCIB_RELEASE_MSIX(device_get_parent(bus), dev, irq));
1987 }
1988 
1989 /* Pass request to map MSI/MSI-X message up to parent bridge. */
1990 int
1991 pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
1992     uint32_t *data)
1993 {
1994 	device_t bus;
1995 	int error;
1996 
1997 	bus = device_get_parent(pcib);
1998 	error = PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data);
1999 	if (error)
2000 		return (error);
2001 
2002 	pci_ht_map_msi(pcib, *addr);
2003 	return (0);
2004 }
2005 
2006 /* Pass request for device power state up to parent bridge. */
2007 int
2008 pcib_power_for_sleep(device_t pcib, device_t dev, int *pstate)
2009 {
2010 	device_t bus;
2011 
2012 	bus = device_get_parent(pcib);
2013 	return (PCIB_POWER_FOR_SLEEP(bus, dev, pstate));
2014 }
2015 
2016 static uint16_t
2017 pcib_ari_get_rid(device_t pcib, device_t dev)
2018 {
2019 	struct pcib_softc *sc;
2020 	uint8_t bus, slot, func;
2021 
2022 	sc = device_get_softc(pcib);
2023 
2024 	if (sc->flags & PCIB_ENABLE_ARI) {
2025 		bus = pci_get_bus(dev);
2026 		func = pci_get_function(dev);
2027 
2028 		return (PCI_ARI_RID(bus, func));
2029 	} else {
2030 		bus = pci_get_bus(dev);
2031 		slot = pci_get_slot(dev);
2032 		func = pci_get_function(dev);
2033 
2034 		return (PCI_RID(bus, slot, func));
2035 	}
2036 }
2037 
2038 /*
2039  * Check that the downstream port (pcib) and the endpoint device (dev) both
2040  * support ARI.  If so, enable it and return 0, otherwise return an error.
2041  */
2042 static int
2043 pcib_try_enable_ari(device_t pcib, device_t dev)
2044 {
2045 	struct pcib_softc *sc;
2046 	int error;
2047 	uint32_t cap2;
2048 	int ari_cap_off;
2049 	uint32_t ari_ver;
2050 	uint32_t pcie_pos;
2051 
2052 	sc = device_get_softc(pcib);
2053 
2054 	/*
2055 	 * ARI is controlled in a register in the PCIe capability structure.
2056 	 * If the downstream port does not have the PCIe capability structure
2057 	 * then it does not support ARI.
2058 	 */
2059 	error = pci_find_cap(pcib, PCIY_EXPRESS, &pcie_pos);
2060 	if (error != 0)
2061 		return (ENODEV);
2062 
2063 	/* Check that the PCIe port advertises ARI support. */
2064 	cap2 = pci_read_config(pcib, pcie_pos + PCIER_DEVICE_CAP2, 4);
2065 	if (!(cap2 & PCIEM_CAP2_ARI))
2066 		return (ENODEV);
2067 
2068 	/*
2069 	 * Check that the endpoint device advertises ARI support via the ARI
2070 	 * extended capability structure.
2071 	 */
2072 	error = pci_find_extcap(dev, PCIZ_ARI, &ari_cap_off);
2073 	if (error != 0)
2074 		return (ENODEV);
2075 
2076 	/*
2077 	 * Finally, check that the endpoint device supports the same version
2078 	 * of ARI that we do.
2079 	 */
2080 	ari_ver = pci_read_config(dev, ari_cap_off, 4);
2081 	if (PCI_EXTCAP_VER(ari_ver) != PCIB_SUPPORTED_ARI_VER) {
2082 		if (bootverbose)
2083 			device_printf(pcib,
2084 			    "Unsupported version of ARI (%d) detected\n",
2085 			    PCI_EXTCAP_VER(ari_ver));
2086 
2087 		return (ENXIO);
2088 	}
2089 
2090 	pcib_enable_ari(sc, pcie_pos);
2091 
2092 	return (0);
2093 }
2094 
2095