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