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