xref: /freebsd/sys/dev/pci/pci_pci.c (revision 18849b5da0c5eaa88500b457be05b038813b51b1)
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 "opt_pci.h"
39 
40 #include <sys/param.h>
41 #include <sys/bus.h>
42 #include <sys/kernel.h>
43 #include <sys/malloc.h>
44 #include <sys/module.h>
45 #include <sys/rman.h>
46 #include <sys/sysctl.h>
47 #include <sys/systm.h>
48 #include <sys/taskqueue.h>
49 
50 #include <dev/pci/pcivar.h>
51 #include <dev/pci/pcireg.h>
52 #include <dev/pci/pci_private.h>
53 #include <dev/pci/pcib_private.h>
54 
55 #include "pcib_if.h"
56 
57 static int		pcib_probe(device_t dev);
58 static int		pcib_suspend(device_t dev);
59 static int		pcib_resume(device_t dev);
60 static int		pcib_power_for_sleep(device_t pcib, device_t dev,
61 			    int *pstate);
62 static int		pcib_ari_get_id(device_t pcib, device_t dev,
63     enum pci_id_type type, uintptr_t *id);
64 static uint32_t		pcib_read_config(device_t dev, u_int b, u_int s,
65     u_int f, u_int reg, int width);
66 static void		pcib_write_config(device_t dev, u_int b, u_int s,
67     u_int f, u_int reg, uint32_t val, int width);
68 static int		pcib_ari_maxslots(device_t dev);
69 static int		pcib_ari_maxfuncs(device_t dev);
70 static int		pcib_try_enable_ari(device_t pcib, device_t dev);
71 static int		pcib_ari_enabled(device_t pcib);
72 static void		pcib_ari_decode_rid(device_t pcib, uint16_t rid,
73 			    int *bus, int *slot, int *func);
74 #ifdef PCI_HP
75 static void		pcib_pcie_ab_timeout(void *arg);
76 static void		pcib_pcie_cc_timeout(void *arg);
77 static void		pcib_pcie_dll_timeout(void *arg);
78 #endif
79 
80 static device_method_t pcib_methods[] = {
81     /* Device interface */
82     DEVMETHOD(device_probe,		pcib_probe),
83     DEVMETHOD(device_attach,		pcib_attach),
84     DEVMETHOD(device_detach,		bus_generic_detach),
85     DEVMETHOD(device_shutdown,		bus_generic_shutdown),
86     DEVMETHOD(device_suspend,		pcib_suspend),
87     DEVMETHOD(device_resume,		pcib_resume),
88 
89     /* Bus interface */
90     DEVMETHOD(bus_child_present,	pcib_child_present),
91     DEVMETHOD(bus_read_ivar,		pcib_read_ivar),
92     DEVMETHOD(bus_write_ivar,		pcib_write_ivar),
93     DEVMETHOD(bus_alloc_resource,	pcib_alloc_resource),
94 #ifdef NEW_PCIB
95     DEVMETHOD(bus_adjust_resource,	pcib_adjust_resource),
96     DEVMETHOD(bus_release_resource,	pcib_release_resource),
97 #else
98     DEVMETHOD(bus_adjust_resource,	bus_generic_adjust_resource),
99     DEVMETHOD(bus_release_resource,	bus_generic_release_resource),
100 #endif
101     DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
102     DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
103     DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
104     DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
105 
106     /* pcib interface */
107     DEVMETHOD(pcib_maxslots,		pcib_ari_maxslots),
108     DEVMETHOD(pcib_maxfuncs,		pcib_ari_maxfuncs),
109     DEVMETHOD(pcib_read_config,		pcib_read_config),
110     DEVMETHOD(pcib_write_config,	pcib_write_config),
111     DEVMETHOD(pcib_route_interrupt,	pcib_route_interrupt),
112     DEVMETHOD(pcib_alloc_msi,		pcib_alloc_msi),
113     DEVMETHOD(pcib_release_msi,		pcib_release_msi),
114     DEVMETHOD(pcib_alloc_msix,		pcib_alloc_msix),
115     DEVMETHOD(pcib_release_msix,	pcib_release_msix),
116     DEVMETHOD(pcib_map_msi,		pcib_map_msi),
117     DEVMETHOD(pcib_power_for_sleep,	pcib_power_for_sleep),
118     DEVMETHOD(pcib_get_id,		pcib_ari_get_id),
119     DEVMETHOD(pcib_try_enable_ari,	pcib_try_enable_ari),
120     DEVMETHOD(pcib_ari_enabled,		pcib_ari_enabled),
121     DEVMETHOD(pcib_decode_rid,		pcib_ari_decode_rid),
122 
123     DEVMETHOD_END
124 };
125 
126 static devclass_t pcib_devclass;
127 
128 DEFINE_CLASS_0(pcib, pcib_driver, pcib_methods, sizeof(struct pcib_softc));
129 DRIVER_MODULE(pcib, pci, pcib_driver, pcib_devclass, NULL, NULL);
130 
131 #ifdef NEW_PCIB
132 SYSCTL_DECL(_hw_pci);
133 
134 static int pci_clear_pcib;
135 SYSCTL_INT(_hw_pci, OID_AUTO, clear_pcib, CTLFLAG_RDTUN, &pci_clear_pcib, 0,
136     "Clear firmware-assigned resources for PCI-PCI bridge I/O windows.");
137 
138 /*
139  * Is a resource from a child device sub-allocated from one of our
140  * resource managers?
141  */
142 static int
143 pcib_is_resource_managed(struct pcib_softc *sc, int type, struct resource *r)
144 {
145 
146 	switch (type) {
147 #ifdef PCI_RES_BUS
148 	case PCI_RES_BUS:
149 		return (rman_is_region_manager(r, &sc->bus.rman));
150 #endif
151 	case SYS_RES_IOPORT:
152 		return (rman_is_region_manager(r, &sc->io.rman));
153 	case SYS_RES_MEMORY:
154 		/* Prefetchable resources may live in either memory rman. */
155 		if (rman_get_flags(r) & RF_PREFETCHABLE &&
156 		    rman_is_region_manager(r, &sc->pmem.rman))
157 			return (1);
158 		return (rman_is_region_manager(r, &sc->mem.rman));
159 	}
160 	return (0);
161 }
162 
163 static int
164 pcib_is_window_open(struct pcib_window *pw)
165 {
166 
167 	return (pw->valid && pw->base < pw->limit);
168 }
169 
170 /*
171  * XXX: If RF_ACTIVE did not also imply allocating a bus space tag and
172  * handle for the resource, we could pass RF_ACTIVE up to the PCI bus
173  * when allocating the resource windows and rely on the PCI bus driver
174  * to do this for us.
175  */
176 static void
177 pcib_activate_window(struct pcib_softc *sc, int type)
178 {
179 
180 	PCI_ENABLE_IO(device_get_parent(sc->dev), sc->dev, type);
181 }
182 
183 static void
184 pcib_write_windows(struct pcib_softc *sc, int mask)
185 {
186 	device_t dev;
187 	uint32_t val;
188 
189 	dev = sc->dev;
190 	if (sc->io.valid && mask & WIN_IO) {
191 		val = pci_read_config(dev, PCIR_IOBASEL_1, 1);
192 		if ((val & PCIM_BRIO_MASK) == PCIM_BRIO_32) {
193 			pci_write_config(dev, PCIR_IOBASEH_1,
194 			    sc->io.base >> 16, 2);
195 			pci_write_config(dev, PCIR_IOLIMITH_1,
196 			    sc->io.limit >> 16, 2);
197 		}
198 		pci_write_config(dev, PCIR_IOBASEL_1, sc->io.base >> 8, 1);
199 		pci_write_config(dev, PCIR_IOLIMITL_1, sc->io.limit >> 8, 1);
200 	}
201 
202 	if (mask & WIN_MEM) {
203 		pci_write_config(dev, PCIR_MEMBASE_1, sc->mem.base >> 16, 2);
204 		pci_write_config(dev, PCIR_MEMLIMIT_1, sc->mem.limit >> 16, 2);
205 	}
206 
207 	if (sc->pmem.valid && mask & WIN_PMEM) {
208 		val = pci_read_config(dev, PCIR_PMBASEL_1, 2);
209 		if ((val & PCIM_BRPM_MASK) == PCIM_BRPM_64) {
210 			pci_write_config(dev, PCIR_PMBASEH_1,
211 			    sc->pmem.base >> 32, 4);
212 			pci_write_config(dev, PCIR_PMLIMITH_1,
213 			    sc->pmem.limit >> 32, 4);
214 		}
215 		pci_write_config(dev, PCIR_PMBASEL_1, sc->pmem.base >> 16, 2);
216 		pci_write_config(dev, PCIR_PMLIMITL_1, sc->pmem.limit >> 16, 2);
217 	}
218 }
219 
220 /*
221  * This is used to reject I/O port allocations that conflict with an
222  * ISA alias range.
223  */
224 static int
225 pcib_is_isa_range(struct pcib_softc *sc, rman_res_t start, rman_res_t end,
226     rman_res_t count)
227 {
228 	rman_res_t next_alias;
229 
230 	if (!(sc->bridgectl & PCIB_BCR_ISA_ENABLE))
231 		return (0);
232 
233 	/* Only check fixed ranges for overlap. */
234 	if (start + count - 1 != end)
235 		return (0);
236 
237 	/* ISA aliases are only in the lower 64KB of I/O space. */
238 	if (start >= 65536)
239 		return (0);
240 
241 	/* Check for overlap with 0x000 - 0x0ff as a special case. */
242 	if (start < 0x100)
243 		goto alias;
244 
245 	/*
246 	 * If the start address is an alias, the range is an alias.
247 	 * Otherwise, compute the start of the next alias range and
248 	 * check if it is before the end of the candidate range.
249 	 */
250 	if ((start & 0x300) != 0)
251 		goto alias;
252 	next_alias = (start & ~0x3fful) | 0x100;
253 	if (next_alias <= end)
254 		goto alias;
255 	return (0);
256 
257 alias:
258 	if (bootverbose)
259 		device_printf(sc->dev,
260 		    "I/O range %#jx-%#jx overlaps with an ISA alias\n", start,
261 		    end);
262 	return (1);
263 }
264 
265 static void
266 pcib_add_window_resources(struct pcib_window *w, struct resource **res,
267     int count)
268 {
269 	struct resource **newarray;
270 	int error, i;
271 
272 	newarray = malloc(sizeof(struct resource *) * (w->count + count),
273 	    M_DEVBUF, M_WAITOK);
274 	if (w->res != NULL)
275 		bcopy(w->res, newarray, sizeof(struct resource *) * w->count);
276 	bcopy(res, newarray + w->count, sizeof(struct resource *) * count);
277 	free(w->res, M_DEVBUF);
278 	w->res = newarray;
279 	w->count += count;
280 
281 	for (i = 0; i < count; i++) {
282 		error = rman_manage_region(&w->rman, rman_get_start(res[i]),
283 		    rman_get_end(res[i]));
284 		if (error)
285 			panic("Failed to add resource to rman");
286 	}
287 }
288 
289 typedef void (nonisa_callback)(rman_res_t start, rman_res_t end, void *arg);
290 
291 static void
292 pcib_walk_nonisa_ranges(rman_res_t start, rman_res_t end, nonisa_callback *cb,
293     void *arg)
294 {
295 	rman_res_t next_end;
296 
297 	/*
298 	 * If start is within an ISA alias range, move up to the start
299 	 * of the next non-alias range.  As a special case, addresses
300 	 * in the range 0x000 - 0x0ff should also be skipped since
301 	 * those are used for various system I/O devices in ISA
302 	 * systems.
303 	 */
304 	if (start <= 65535) {
305 		if (start < 0x100 || (start & 0x300) != 0) {
306 			start &= ~0x3ff;
307 			start += 0x400;
308 		}
309 	}
310 
311 	/* ISA aliases are only in the lower 64KB of I/O space. */
312 	while (start <= MIN(end, 65535)) {
313 		next_end = MIN(start | 0xff, end);
314 		cb(start, next_end, arg);
315 		start += 0x400;
316 	}
317 
318 	if (start <= end)
319 		cb(start, end, arg);
320 }
321 
322 static void
323 count_ranges(rman_res_t start, rman_res_t end, void *arg)
324 {
325 	int *countp;
326 
327 	countp = arg;
328 	(*countp)++;
329 }
330 
331 struct alloc_state {
332 	struct resource **res;
333 	struct pcib_softc *sc;
334 	int count, error;
335 };
336 
337 static void
338 alloc_ranges(rman_res_t start, rman_res_t end, void *arg)
339 {
340 	struct alloc_state *as;
341 	struct pcib_window *w;
342 	int rid;
343 
344 	as = arg;
345 	if (as->error != 0)
346 		return;
347 
348 	w = &as->sc->io;
349 	rid = w->reg;
350 	if (bootverbose)
351 		device_printf(as->sc->dev,
352 		    "allocating non-ISA range %#jx-%#jx\n", start, end);
353 	as->res[as->count] = bus_alloc_resource(as->sc->dev, SYS_RES_IOPORT,
354 	    &rid, start, end, end - start + 1, 0);
355 	if (as->res[as->count] == NULL)
356 		as->error = ENXIO;
357 	else
358 		as->count++;
359 }
360 
361 static int
362 pcib_alloc_nonisa_ranges(struct pcib_softc *sc, rman_res_t start, rman_res_t end)
363 {
364 	struct alloc_state as;
365 	int i, new_count;
366 
367 	/* First, see how many ranges we need. */
368 	new_count = 0;
369 	pcib_walk_nonisa_ranges(start, end, count_ranges, &new_count);
370 
371 	/* Second, allocate the ranges. */
372 	as.res = malloc(sizeof(struct resource *) * new_count, M_DEVBUF,
373 	    M_WAITOK);
374 	as.sc = sc;
375 	as.count = 0;
376 	as.error = 0;
377 	pcib_walk_nonisa_ranges(start, end, alloc_ranges, &as);
378 	if (as.error != 0) {
379 		for (i = 0; i < as.count; i++)
380 			bus_release_resource(sc->dev, SYS_RES_IOPORT,
381 			    sc->io.reg, as.res[i]);
382 		free(as.res, M_DEVBUF);
383 		return (as.error);
384 	}
385 	KASSERT(as.count == new_count, ("%s: count mismatch", __func__));
386 
387 	/* Third, add the ranges to the window. */
388 	pcib_add_window_resources(&sc->io, as.res, as.count);
389 	free(as.res, M_DEVBUF);
390 	return (0);
391 }
392 
393 static void
394 pcib_alloc_window(struct pcib_softc *sc, struct pcib_window *w, int type,
395     int flags, pci_addr_t max_address)
396 {
397 	struct resource *res;
398 	char buf[64];
399 	int error, rid;
400 
401 	if (max_address != (rman_res_t)max_address)
402 		max_address = ~0;
403 	w->rman.rm_start = 0;
404 	w->rman.rm_end = max_address;
405 	w->rman.rm_type = RMAN_ARRAY;
406 	snprintf(buf, sizeof(buf), "%s %s window",
407 	    device_get_nameunit(sc->dev), w->name);
408 	w->rman.rm_descr = strdup(buf, M_DEVBUF);
409 	error = rman_init(&w->rman);
410 	if (error)
411 		panic("Failed to initialize %s %s rman",
412 		    device_get_nameunit(sc->dev), w->name);
413 
414 	if (!pcib_is_window_open(w))
415 		return;
416 
417 	if (w->base > max_address || w->limit > max_address) {
418 		device_printf(sc->dev,
419 		    "initial %s window has too many bits, ignoring\n", w->name);
420 		return;
421 	}
422 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE)
423 		(void)pcib_alloc_nonisa_ranges(sc, w->base, w->limit);
424 	else {
425 		rid = w->reg;
426 		res = bus_alloc_resource(sc->dev, type, &rid, w->base, w->limit,
427 		    w->limit - w->base + 1, flags);
428 		if (res != NULL)
429 			pcib_add_window_resources(w, &res, 1);
430 	}
431 	if (w->res == NULL) {
432 		device_printf(sc->dev,
433 		    "failed to allocate initial %s window: %#jx-%#jx\n",
434 		    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
435 		w->base = max_address;
436 		w->limit = 0;
437 		pcib_write_windows(sc, w->mask);
438 		return;
439 	}
440 	pcib_activate_window(sc, type);
441 }
442 
443 /*
444  * Initialize I/O windows.
445  */
446 static void
447 pcib_probe_windows(struct pcib_softc *sc)
448 {
449 	pci_addr_t max;
450 	device_t dev;
451 	uint32_t val;
452 
453 	dev = sc->dev;
454 
455 	if (pci_clear_pcib) {
456 		pcib_bridge_init(dev);
457 	}
458 
459 	/* Determine if the I/O port window is implemented. */
460 	val = pci_read_config(dev, PCIR_IOBASEL_1, 1);
461 	if (val == 0) {
462 		/*
463 		 * If 'val' is zero, then only 16-bits of I/O space
464 		 * are supported.
465 		 */
466 		pci_write_config(dev, PCIR_IOBASEL_1, 0xff, 1);
467 		if (pci_read_config(dev, PCIR_IOBASEL_1, 1) != 0) {
468 			sc->io.valid = 1;
469 			pci_write_config(dev, PCIR_IOBASEL_1, 0, 1);
470 		}
471 	} else
472 		sc->io.valid = 1;
473 
474 	/* Read the existing I/O port window. */
475 	if (sc->io.valid) {
476 		sc->io.reg = PCIR_IOBASEL_1;
477 		sc->io.step = 12;
478 		sc->io.mask = WIN_IO;
479 		sc->io.name = "I/O port";
480 		if ((val & PCIM_BRIO_MASK) == PCIM_BRIO_32) {
481 			sc->io.base = PCI_PPBIOBASE(
482 			    pci_read_config(dev, PCIR_IOBASEH_1, 2), val);
483 			sc->io.limit = PCI_PPBIOLIMIT(
484 			    pci_read_config(dev, PCIR_IOLIMITH_1, 2),
485 			    pci_read_config(dev, PCIR_IOLIMITL_1, 1));
486 			max = 0xffffffff;
487 		} else {
488 			sc->io.base = PCI_PPBIOBASE(0, val);
489 			sc->io.limit = PCI_PPBIOLIMIT(0,
490 			    pci_read_config(dev, PCIR_IOLIMITL_1, 1));
491 			max = 0xffff;
492 		}
493 		pcib_alloc_window(sc, &sc->io, SYS_RES_IOPORT, 0, max);
494 	}
495 
496 	/* Read the existing memory window. */
497 	sc->mem.valid = 1;
498 	sc->mem.reg = PCIR_MEMBASE_1;
499 	sc->mem.step = 20;
500 	sc->mem.mask = WIN_MEM;
501 	sc->mem.name = "memory";
502 	sc->mem.base = PCI_PPBMEMBASE(0,
503 	    pci_read_config(dev, PCIR_MEMBASE_1, 2));
504 	sc->mem.limit = PCI_PPBMEMLIMIT(0,
505 	    pci_read_config(dev, PCIR_MEMLIMIT_1, 2));
506 	pcib_alloc_window(sc, &sc->mem, SYS_RES_MEMORY, 0, 0xffffffff);
507 
508 	/* Determine if the prefetchable memory window is implemented. */
509 	val = pci_read_config(dev, PCIR_PMBASEL_1, 2);
510 	if (val == 0) {
511 		/*
512 		 * If 'val' is zero, then only 32-bits of memory space
513 		 * are supported.
514 		 */
515 		pci_write_config(dev, PCIR_PMBASEL_1, 0xffff, 2);
516 		if (pci_read_config(dev, PCIR_PMBASEL_1, 2) != 0) {
517 			sc->pmem.valid = 1;
518 			pci_write_config(dev, PCIR_PMBASEL_1, 0, 2);
519 		}
520 	} else
521 		sc->pmem.valid = 1;
522 
523 	/* Read the existing prefetchable memory window. */
524 	if (sc->pmem.valid) {
525 		sc->pmem.reg = PCIR_PMBASEL_1;
526 		sc->pmem.step = 20;
527 		sc->pmem.mask = WIN_PMEM;
528 		sc->pmem.name = "prefetch";
529 		if ((val & PCIM_BRPM_MASK) == PCIM_BRPM_64) {
530 			sc->pmem.base = PCI_PPBMEMBASE(
531 			    pci_read_config(dev, PCIR_PMBASEH_1, 4), val);
532 			sc->pmem.limit = PCI_PPBMEMLIMIT(
533 			    pci_read_config(dev, PCIR_PMLIMITH_1, 4),
534 			    pci_read_config(dev, PCIR_PMLIMITL_1, 2));
535 			max = 0xffffffffffffffff;
536 		} else {
537 			sc->pmem.base = PCI_PPBMEMBASE(0, val);
538 			sc->pmem.limit = PCI_PPBMEMLIMIT(0,
539 			    pci_read_config(dev, PCIR_PMLIMITL_1, 2));
540 			max = 0xffffffff;
541 		}
542 		pcib_alloc_window(sc, &sc->pmem, SYS_RES_MEMORY,
543 		    RF_PREFETCHABLE, max);
544 	}
545 }
546 
547 #ifdef PCI_RES_BUS
548 /*
549  * Allocate a suitable secondary bus for this bridge if needed and
550  * initialize the resource manager for the secondary bus range.  Note
551  * that the minimum count is a desired value and this may allocate a
552  * smaller range.
553  */
554 void
555 pcib_setup_secbus(device_t dev, struct pcib_secbus *bus, int min_count)
556 {
557 	char buf[64];
558 	int error, rid, sec_reg;
559 
560 	switch (pci_read_config(dev, PCIR_HDRTYPE, 1) & PCIM_HDRTYPE) {
561 	case PCIM_HDRTYPE_BRIDGE:
562 		sec_reg = PCIR_SECBUS_1;
563 		bus->sub_reg = PCIR_SUBBUS_1;
564 		break;
565 	case PCIM_HDRTYPE_CARDBUS:
566 		sec_reg = PCIR_SECBUS_2;
567 		bus->sub_reg = PCIR_SUBBUS_2;
568 		break;
569 	default:
570 		panic("not a PCI bridge");
571 	}
572 	bus->sec = pci_read_config(dev, sec_reg, 1);
573 	bus->sub = pci_read_config(dev, bus->sub_reg, 1);
574 	bus->dev = dev;
575 	bus->rman.rm_start = 0;
576 	bus->rman.rm_end = PCI_BUSMAX;
577 	bus->rman.rm_type = RMAN_ARRAY;
578 	snprintf(buf, sizeof(buf), "%s bus numbers", device_get_nameunit(dev));
579 	bus->rman.rm_descr = strdup(buf, M_DEVBUF);
580 	error = rman_init(&bus->rman);
581 	if (error)
582 		panic("Failed to initialize %s bus number rman",
583 		    device_get_nameunit(dev));
584 
585 	/*
586 	 * Allocate a bus range.  This will return an existing bus range
587 	 * if one exists, or a new bus range if one does not.
588 	 */
589 	rid = 0;
590 	bus->res = bus_alloc_resource_anywhere(dev, PCI_RES_BUS, &rid,
591 	    min_count, 0);
592 	if (bus->res == NULL) {
593 		/*
594 		 * Fall back to just allocating a range of a single bus
595 		 * number.
596 		 */
597 		bus->res = bus_alloc_resource_anywhere(dev, PCI_RES_BUS, &rid,
598 		    1, 0);
599 	} else if (rman_get_size(bus->res) < min_count)
600 		/*
601 		 * Attempt to grow the existing range to satisfy the
602 		 * minimum desired count.
603 		 */
604 		(void)bus_adjust_resource(dev, PCI_RES_BUS, bus->res,
605 		    rman_get_start(bus->res), rman_get_start(bus->res) +
606 		    min_count - 1);
607 
608 	/*
609 	 * Add the initial resource to the rman.
610 	 */
611 	if (bus->res != NULL) {
612 		error = rman_manage_region(&bus->rman, rman_get_start(bus->res),
613 		    rman_get_end(bus->res));
614 		if (error)
615 			panic("Failed to add resource to rman");
616 		bus->sec = rman_get_start(bus->res);
617 		bus->sub = rman_get_end(bus->res);
618 	}
619 }
620 
621 static struct resource *
622 pcib_suballoc_bus(struct pcib_secbus *bus, device_t child, int *rid,
623     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
624 {
625 	struct resource *res;
626 
627 	res = rman_reserve_resource(&bus->rman, start, end, count, flags,
628 	    child);
629 	if (res == NULL)
630 		return (NULL);
631 
632 	if (bootverbose)
633 		device_printf(bus->dev,
634 		    "allocated bus range (%ju-%ju) for rid %d of %s\n",
635 		    rman_get_start(res), rman_get_end(res), *rid,
636 		    pcib_child_name(child));
637 	rman_set_rid(res, *rid);
638 	return (res);
639 }
640 
641 /*
642  * Attempt to grow the secondary bus range.  This is much simpler than
643  * for I/O windows as the range can only be grown by increasing
644  * subbus.
645  */
646 static int
647 pcib_grow_subbus(struct pcib_secbus *bus, rman_res_t new_end)
648 {
649 	rman_res_t old_end;
650 	int error;
651 
652 	old_end = rman_get_end(bus->res);
653 	KASSERT(new_end > old_end, ("attempt to shrink subbus"));
654 	error = bus_adjust_resource(bus->dev, PCI_RES_BUS, bus->res,
655 	    rman_get_start(bus->res), new_end);
656 	if (error)
657 		return (error);
658 	if (bootverbose)
659 		device_printf(bus->dev, "grew bus range to %ju-%ju\n",
660 		    rman_get_start(bus->res), rman_get_end(bus->res));
661 	error = rman_manage_region(&bus->rman, old_end + 1,
662 	    rman_get_end(bus->res));
663 	if (error)
664 		panic("Failed to add resource to rman");
665 	bus->sub = rman_get_end(bus->res);
666 	pci_write_config(bus->dev, bus->sub_reg, bus->sub, 1);
667 	return (0);
668 }
669 
670 struct resource *
671 pcib_alloc_subbus(struct pcib_secbus *bus, device_t child, int *rid,
672     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
673 {
674 	struct resource *res;
675 	rman_res_t start_free, end_free, new_end;
676 
677 	/*
678 	 * First, see if the request can be satisified by the existing
679 	 * bus range.
680 	 */
681 	res = pcib_suballoc_bus(bus, child, rid, start, end, count, flags);
682 	if (res != NULL)
683 		return (res);
684 
685 	/*
686 	 * Figure out a range to grow the bus range.  First, find the
687 	 * first bus number after the last allocated bus in the rman and
688 	 * enforce that as a minimum starting point for the range.
689 	 */
690 	if (rman_last_free_region(&bus->rman, &start_free, &end_free) != 0 ||
691 	    end_free != bus->sub)
692 		start_free = bus->sub + 1;
693 	if (start_free < start)
694 		start_free = start;
695 	new_end = start_free + count - 1;
696 
697 	/*
698 	 * See if this new range would satisfy the request if it
699 	 * succeeds.
700 	 */
701 	if (new_end > end)
702 		return (NULL);
703 
704 	/* Finally, attempt to grow the existing resource. */
705 	if (bootverbose) {
706 		device_printf(bus->dev,
707 		    "attempting to grow bus range for %ju buses\n", count);
708 		printf("\tback candidate range: %ju-%ju\n", start_free,
709 		    new_end);
710 	}
711 	if (pcib_grow_subbus(bus, new_end) == 0)
712 		return (pcib_suballoc_bus(bus, child, rid, start, end, count,
713 		    flags));
714 	return (NULL);
715 }
716 #endif
717 
718 #else
719 
720 /*
721  * Is the prefetch window open (eg, can we allocate memory in it?)
722  */
723 static int
724 pcib_is_prefetch_open(struct pcib_softc *sc)
725 {
726 	return (sc->pmembase > 0 && sc->pmembase < sc->pmemlimit);
727 }
728 
729 /*
730  * Is the nonprefetch window open (eg, can we allocate memory in it?)
731  */
732 static int
733 pcib_is_nonprefetch_open(struct pcib_softc *sc)
734 {
735 	return (sc->membase > 0 && sc->membase < sc->memlimit);
736 }
737 
738 /*
739  * Is the io window open (eg, can we allocate ports in it?)
740  */
741 static int
742 pcib_is_io_open(struct pcib_softc *sc)
743 {
744 	return (sc->iobase > 0 && sc->iobase < sc->iolimit);
745 }
746 
747 /*
748  * Get current I/O decode.
749  */
750 static void
751 pcib_get_io_decode(struct pcib_softc *sc)
752 {
753 	device_t	dev;
754 	uint32_t	iolow;
755 
756 	dev = sc->dev;
757 
758 	iolow = pci_read_config(dev, PCIR_IOBASEL_1, 1);
759 	if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
760 		sc->iobase = PCI_PPBIOBASE(
761 		    pci_read_config(dev, PCIR_IOBASEH_1, 2), iolow);
762 	else
763 		sc->iobase = PCI_PPBIOBASE(0, iolow);
764 
765 	iolow = pci_read_config(dev, PCIR_IOLIMITL_1, 1);
766 	if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
767 		sc->iolimit = PCI_PPBIOLIMIT(
768 		    pci_read_config(dev, PCIR_IOLIMITH_1, 2), iolow);
769 	else
770 		sc->iolimit = PCI_PPBIOLIMIT(0, iolow);
771 }
772 
773 /*
774  * Get current memory decode.
775  */
776 static void
777 pcib_get_mem_decode(struct pcib_softc *sc)
778 {
779 	device_t	dev;
780 	pci_addr_t	pmemlow;
781 
782 	dev = sc->dev;
783 
784 	sc->membase = PCI_PPBMEMBASE(0,
785 	    pci_read_config(dev, PCIR_MEMBASE_1, 2));
786 	sc->memlimit = PCI_PPBMEMLIMIT(0,
787 	    pci_read_config(dev, PCIR_MEMLIMIT_1, 2));
788 
789 	pmemlow = pci_read_config(dev, PCIR_PMBASEL_1, 2);
790 	if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64)
791 		sc->pmembase = PCI_PPBMEMBASE(
792 		    pci_read_config(dev, PCIR_PMBASEH_1, 4), pmemlow);
793 	else
794 		sc->pmembase = PCI_PPBMEMBASE(0, pmemlow);
795 
796 	pmemlow = pci_read_config(dev, PCIR_PMLIMITL_1, 2);
797 	if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64)
798 		sc->pmemlimit = PCI_PPBMEMLIMIT(
799 		    pci_read_config(dev, PCIR_PMLIMITH_1, 4), pmemlow);
800 	else
801 		sc->pmemlimit = PCI_PPBMEMLIMIT(0, pmemlow);
802 }
803 
804 /*
805  * Restore previous I/O decode.
806  */
807 static void
808 pcib_set_io_decode(struct pcib_softc *sc)
809 {
810 	device_t	dev;
811 	uint32_t	iohi;
812 
813 	dev = sc->dev;
814 
815 	iohi = sc->iobase >> 16;
816 	if (iohi > 0)
817 		pci_write_config(dev, PCIR_IOBASEH_1, iohi, 2);
818 	pci_write_config(dev, PCIR_IOBASEL_1, sc->iobase >> 8, 1);
819 
820 	iohi = sc->iolimit >> 16;
821 	if (iohi > 0)
822 		pci_write_config(dev, PCIR_IOLIMITH_1, iohi, 2);
823 	pci_write_config(dev, PCIR_IOLIMITL_1, sc->iolimit >> 8, 1);
824 }
825 
826 /*
827  * Restore previous memory decode.
828  */
829 static void
830 pcib_set_mem_decode(struct pcib_softc *sc)
831 {
832 	device_t	dev;
833 	pci_addr_t	pmemhi;
834 
835 	dev = sc->dev;
836 
837 	pci_write_config(dev, PCIR_MEMBASE_1, sc->membase >> 16, 2);
838 	pci_write_config(dev, PCIR_MEMLIMIT_1, sc->memlimit >> 16, 2);
839 
840 	pmemhi = sc->pmembase >> 32;
841 	if (pmemhi > 0)
842 		pci_write_config(dev, PCIR_PMBASEH_1, pmemhi, 4);
843 	pci_write_config(dev, PCIR_PMBASEL_1, sc->pmembase >> 16, 2);
844 
845 	pmemhi = sc->pmemlimit >> 32;
846 	if (pmemhi > 0)
847 		pci_write_config(dev, PCIR_PMLIMITH_1, pmemhi, 4);
848 	pci_write_config(dev, PCIR_PMLIMITL_1, sc->pmemlimit >> 16, 2);
849 }
850 #endif
851 
852 #ifdef PCI_HP
853 /*
854  * PCI-express HotPlug support.
855  */
856 static void
857 pcib_probe_hotplug(struct pcib_softc *sc)
858 {
859 	device_t dev;
860 
861 	dev = sc->dev;
862 	if (pci_find_cap(dev, PCIY_EXPRESS, NULL) != 0)
863 		return;
864 
865 	if (!(pcie_read_config(dev, PCIER_FLAGS, 2) & PCIEM_FLAGS_SLOT))
866 		return;
867 
868 	sc->pcie_link_cap = pcie_read_config(dev, PCIER_LINK_CAP, 4);
869 	sc->pcie_slot_cap = pcie_read_config(dev, PCIER_SLOT_CAP, 4);
870 
871 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_HPC)
872 		sc->flags |= PCIB_HOTPLUG;
873 }
874 
875 /*
876  * Send a HotPlug command to the slot control register.  If this slot
877  * uses command completion interrupts and a previous command is still
878  * in progress, then the command is dropped.  Once the previous
879  * command completes or times out, pcib_pcie_hotplug_update() will be
880  * invoked to post a new command based on the slot's state at that
881  * time.
882  */
883 static void
884 pcib_pcie_hotplug_command(struct pcib_softc *sc, uint16_t val, uint16_t mask)
885 {
886 	device_t dev;
887 	uint16_t ctl, new;
888 
889 	dev = sc->dev;
890 
891 	if (sc->flags & PCIB_HOTPLUG_CMD_PENDING)
892 		return;
893 
894 	ctl = pcie_read_config(dev, PCIER_SLOT_CTL, 2);
895 	new = (ctl & ~mask) | val;
896 	if (new == ctl)
897 		return;
898 	pcie_write_config(dev, PCIER_SLOT_CTL, new, 2);
899 	if (!(sc->pcie_slot_cap & PCIEM_SLOT_CAP_NCCS)) {
900 		sc->flags |= PCIB_HOTPLUG_CMD_PENDING;
901 		if (!cold)
902 			callout_reset(&sc->pcie_cc_timer, hz,
903 			    pcib_pcie_cc_timeout, sc);
904 	}
905 }
906 
907 static void
908 pcib_pcie_hotplug_command_completed(struct pcib_softc *sc)
909 {
910 	device_t dev;
911 
912 	dev = sc->dev;
913 
914 	if (bootverbose)
915 		device_printf(dev, "Command Completed\n");
916 	if (!(sc->flags & PCIB_HOTPLUG_CMD_PENDING))
917 		return;
918 	callout_stop(&sc->pcie_cc_timer);
919 	sc->flags &= ~PCIB_HOTPLUG_CMD_PENDING;
920 }
921 
922 /*
923  * Returns true if a card is fully inserted from the user's
924  * perspective.  It may not yet be ready for access, but the driver
925  * can now start enabling access if necessary.
926  */
927 static bool
928 pcib_hotplug_inserted(struct pcib_softc *sc)
929 {
930 
931 	/* Pretend the card isn't present if a detach is forced. */
932 	if (sc->flags & PCIB_DETACHING)
933 		return (false);
934 
935 	/* Card must be present in the slot. */
936 	if ((sc->pcie_slot_sta & PCIEM_SLOT_STA_PDS) == 0)
937 		return (false);
938 
939 	/* A power fault implicitly turns off power to the slot. */
940 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_PFD)
941 		return (false);
942 
943 	/* If the MRL is disengaged, the slot is powered off. */
944 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_MRLSP &&
945 	    (sc->pcie_slot_sta & PCIEM_SLOT_STA_MRLSS) != 0)
946 		return (false);
947 
948 	return (true);
949 }
950 
951 /*
952  * Returns -1 if the card is fully inserted, powered, and ready for
953  * access.  Otherwise, returns 0.
954  */
955 static int
956 pcib_hotplug_present(struct pcib_softc *sc)
957 {
958 	device_t dev;
959 
960 	dev = sc->dev;
961 
962 	/* Card must be inserted. */
963 	if (!pcib_hotplug_inserted(sc))
964 		return (0);
965 
966 	/*
967 	 * Require the Electromechanical Interlock to be engaged if
968 	 * present.
969 	 */
970 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_EIP &&
971 	    (sc->pcie_slot_sta & PCIEM_SLOT_STA_EIS) == 0)
972 		return (0);
973 
974 	/* Require the Data Link Layer to be active. */
975 	if (sc->pcie_link_cap & PCIEM_LINK_CAP_DL_ACTIVE) {
976 		if (!(sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE))
977 			return (0);
978 	}
979 
980 	return (-1);
981 }
982 
983 static void
984 pcib_pcie_hotplug_update(struct pcib_softc *sc, uint16_t val, uint16_t mask,
985     bool schedule_task)
986 {
987 	bool card_inserted;
988 
989 	/* Clear DETACHING if Present Detect has cleared. */
990 	if ((sc->pcie_slot_sta & (PCIEM_SLOT_STA_PDC | PCIEM_SLOT_STA_PDS)) ==
991 	    PCIEM_SLOT_STA_PDC)
992 		sc->flags &= ~PCIB_DETACHING;
993 
994 	card_inserted = pcib_hotplug_inserted(sc);
995 
996 	/* Turn the power indicator on if a card is inserted. */
997 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PIP) {
998 		mask |= PCIEM_SLOT_CTL_PIC;
999 		if (card_inserted)
1000 			val |= PCIEM_SLOT_CTL_PI_ON;
1001 		else if (sc->flags & PCIB_DETACH_PENDING)
1002 			val |= PCIEM_SLOT_CTL_PI_BLINK;
1003 		else
1004 			val |= PCIEM_SLOT_CTL_PI_OFF;
1005 	}
1006 
1007 	/* Turn the power on via the Power Controller if a card is inserted. */
1008 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PCP) {
1009 		mask |= PCIEM_SLOT_CTL_PCC;
1010 		if (card_inserted)
1011 			val |= PCIEM_SLOT_CTL_PC_ON;
1012 		else
1013 			val |= PCIEM_SLOT_CTL_PC_OFF;
1014 	}
1015 
1016 	/*
1017 	 * If a card is inserted, enable the Electromechanical
1018 	 * Interlock.  If a card is not inserted (or we are in the
1019 	 * process of detaching), disable the Electromechanical
1020 	 * Interlock.
1021 	 */
1022 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_EIP) {
1023 		mask |= PCIEM_SLOT_CTL_EIC;
1024 		if (card_inserted !=
1025 		    !(sc->pcie_slot_sta & PCIEM_SLOT_STA_EIS))
1026 			val |= PCIEM_SLOT_CTL_EIC;
1027 	}
1028 
1029 	/*
1030 	 * Start a timer to see if the Data Link Layer times out.
1031 	 * Note that we only start the timer if Presence Detect
1032 	 * changed on this interrupt.  Stop any scheduled timer if
1033 	 * the Data Link Layer is active.
1034 	 */
1035 	if (sc->pcie_link_cap & PCIEM_LINK_CAP_DL_ACTIVE) {
1036 		if (card_inserted &&
1037 		    !(sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE) &&
1038 		    sc->pcie_slot_sta & PCIEM_SLOT_STA_PDC) {
1039 			if (cold)
1040 				device_printf(sc->dev,
1041 				    "Data Link Layer inactive\n");
1042 			else
1043 				callout_reset(&sc->pcie_dll_timer, hz,
1044 				    pcib_pcie_dll_timeout, sc);
1045 		} else if (sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE)
1046 			callout_stop(&sc->pcie_dll_timer);
1047 	}
1048 
1049 	pcib_pcie_hotplug_command(sc, val, mask);
1050 
1051 	/*
1052 	 * During attach the child "pci" device is added sychronously;
1053 	 * otherwise, the task is scheduled to manage the child
1054 	 * device.
1055 	 */
1056 	if (schedule_task &&
1057 	    (pcib_hotplug_present(sc) != 0) != (sc->child != NULL))
1058 		taskqueue_enqueue(taskqueue_thread, &sc->pcie_hp_task);
1059 }
1060 
1061 static void
1062 pcib_pcie_intr(void *arg)
1063 {
1064 	struct pcib_softc *sc;
1065 	device_t dev;
1066 
1067 	sc = arg;
1068 	dev = sc->dev;
1069 	sc->pcie_slot_sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
1070 
1071 	/* Clear the events just reported. */
1072 	pcie_write_config(dev, PCIER_SLOT_STA, sc->pcie_slot_sta, 2);
1073 
1074 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_ABP) {
1075 		if (sc->flags & PCIB_DETACH_PENDING) {
1076 			device_printf(dev,
1077 			    "Attention Button Pressed: Detach Cancelled\n");
1078 			sc->flags &= ~PCIB_DETACH_PENDING;
1079 			callout_stop(&sc->pcie_ab_timer);
1080 		} else {
1081 			device_printf(dev,
1082 		    "Attention Button Pressed: Detaching in 5 seconds\n");
1083 			sc->flags |= PCIB_DETACH_PENDING;
1084 			callout_reset(&sc->pcie_ab_timer, 5 * hz,
1085 			    pcib_pcie_ab_timeout, sc);
1086 		}
1087 	}
1088 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_PFD)
1089 		device_printf(dev, "Power Fault Detected\n");
1090 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_MRLSC)
1091 		device_printf(dev, "MRL Sensor Changed to %s\n",
1092 		    sc->pcie_slot_sta & PCIEM_SLOT_STA_MRLSS ? "open" :
1093 		    "closed");
1094 	if (bootverbose && sc->pcie_slot_sta & PCIEM_SLOT_STA_PDC)
1095 		device_printf(dev, "Present Detect Changed to %s\n",
1096 		    sc->pcie_slot_sta & PCIEM_SLOT_STA_PDS ? "card present" :
1097 		    "empty");
1098 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_CC)
1099 		pcib_pcie_hotplug_command_completed(sc);
1100 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_DLLSC) {
1101 		sc->pcie_link_sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
1102 		if (bootverbose)
1103 			device_printf(dev,
1104 			    "Data Link Layer State Changed to %s\n",
1105 			    sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE ?
1106 			    "active" : "inactive");
1107 	}
1108 
1109 	pcib_pcie_hotplug_update(sc, 0, 0, true);
1110 }
1111 
1112 static void
1113 pcib_pcie_hotplug_task(void *context, int pending)
1114 {
1115 	struct pcib_softc *sc;
1116 	device_t dev;
1117 
1118 	sc = context;
1119 	mtx_lock(&Giant);
1120 	dev = sc->dev;
1121 	if (pcib_hotplug_present(sc) != 0) {
1122 		if (sc->child == NULL) {
1123 			sc->child = device_add_child(dev, "pci", -1);
1124 			bus_generic_attach(dev);
1125 		}
1126 	} else {
1127 		if (sc->child != NULL) {
1128 			if (device_delete_child(dev, sc->child) == 0)
1129 				sc->child = NULL;
1130 		}
1131 	}
1132 	mtx_unlock(&Giant);
1133 }
1134 
1135 static void
1136 pcib_pcie_ab_timeout(void *arg)
1137 {
1138 	struct pcib_softc *sc;
1139 	device_t dev;
1140 
1141 	sc = arg;
1142 	dev = sc->dev;
1143 	mtx_assert(&Giant, MA_OWNED);
1144 	if (sc->flags & PCIB_DETACH_PENDING) {
1145 		sc->flags |= PCIB_DETACHING;
1146 		sc->flags &= ~PCIB_DETACH_PENDING;
1147 		pcib_pcie_hotplug_update(sc, 0, 0, true);
1148 	}
1149 }
1150 
1151 static void
1152 pcib_pcie_cc_timeout(void *arg)
1153 {
1154 	struct pcib_softc *sc;
1155 	device_t dev;
1156 
1157 	sc = arg;
1158 	dev = sc->dev;
1159 	mtx_assert(&Giant, MA_OWNED);
1160 	if (sc->flags & PCIB_HOTPLUG_CMD_PENDING) {
1161 		device_printf(dev,
1162 		    "Hotplug Command Timed Out - forcing detach\n");
1163 		sc->flags &= ~(PCIB_HOTPLUG_CMD_PENDING | PCIB_DETACH_PENDING);
1164 		sc->flags |= PCIB_DETACHING;
1165 		pcib_pcie_hotplug_update(sc, 0, 0, true);
1166 	}
1167 }
1168 
1169 static void
1170 pcib_pcie_dll_timeout(void *arg)
1171 {
1172 	struct pcib_softc *sc;
1173 	device_t dev;
1174 	uint16_t sta;
1175 
1176 	sc = arg;
1177 	dev = sc->dev;
1178 	mtx_assert(&Giant, MA_OWNED);
1179 	sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
1180 	if (!(sta & PCIEM_LINK_STA_DL_ACTIVE)) {
1181 		device_printf(dev,
1182 		    "Timed out waiting for Data Link Layer Active\n");
1183 		sc->flags |= PCIB_DETACHING;
1184 		pcib_pcie_hotplug_update(sc, 0, 0, true);
1185 	} else if (sta != sc->pcie_link_sta) {
1186 		device_printf(dev,
1187 		    "Missed HotPlug interrupt waiting for DLL Active\n");
1188 		pcib_pcie_intr(sc);
1189 	}
1190 }
1191 
1192 static int
1193 pcib_alloc_pcie_irq(struct pcib_softc *sc)
1194 {
1195 	device_t dev;
1196 	int count, error, rid;
1197 
1198 	rid = -1;
1199 	dev = sc->dev;
1200 
1201 	/*
1202 	 * For simplicity, only use MSI-X if there is a single message.
1203 	 * To support a device with multiple messages we would have to
1204 	 * use remap intr if the MSI number is not 0.
1205 	 */
1206 	count = pci_msix_count(dev);
1207 	if (count == 1) {
1208 		error = pci_alloc_msix(dev, &count);
1209 		if (error == 0)
1210 			rid = 1;
1211 	}
1212 
1213 	if (rid < 0 && pci_msi_count(dev) > 0) {
1214 		count = 1;
1215 		error = pci_alloc_msi(dev, &count);
1216 		if (error == 0)
1217 			rid = 1;
1218 	}
1219 
1220 	if (rid < 0)
1221 		rid = 0;
1222 
1223 	sc->pcie_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1224 	    RF_ACTIVE);
1225 	if (sc->pcie_irq == NULL) {
1226 		device_printf(dev,
1227 		    "Failed to allocate interrupt for PCI-e events\n");
1228 		if (rid > 0)
1229 			pci_release_msi(dev);
1230 		return (ENXIO);
1231 	}
1232 
1233 	error = bus_setup_intr(dev, sc->pcie_irq, INTR_TYPE_MISC,
1234 	    NULL, pcib_pcie_intr, sc, &sc->pcie_ihand);
1235 	if (error) {
1236 		device_printf(dev, "Failed to setup PCI-e interrupt handler\n");
1237 		bus_release_resource(dev, SYS_RES_IRQ, rid, sc->pcie_irq);
1238 		if (rid > 0)
1239 			pci_release_msi(dev);
1240 		return (error);
1241 	}
1242 	return (0);
1243 }
1244 
1245 static void
1246 pcib_setup_hotplug(struct pcib_softc *sc)
1247 {
1248 	device_t dev;
1249 	uint16_t mask, val;
1250 
1251 	dev = sc->dev;
1252 	callout_init(&sc->pcie_ab_timer, 0);
1253 	callout_init(&sc->pcie_cc_timer, 0);
1254 	callout_init(&sc->pcie_dll_timer, 0);
1255 	TASK_INIT(&sc->pcie_hp_task, 0, pcib_pcie_hotplug_task, sc);
1256 
1257 	/* Allocate IRQ. */
1258 	if (pcib_alloc_pcie_irq(sc) != 0)
1259 		return;
1260 
1261 	sc->pcie_link_sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
1262 	sc->pcie_slot_sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
1263 
1264 	/* Enable HotPlug events. */
1265 	mask = PCIEM_SLOT_CTL_DLLSCE | PCIEM_SLOT_CTL_HPIE |
1266 	    PCIEM_SLOT_CTL_CCIE | PCIEM_SLOT_CTL_PDCE | PCIEM_SLOT_CTL_MRLSCE |
1267 	    PCIEM_SLOT_CTL_PFDE | PCIEM_SLOT_CTL_ABPE;
1268 	val = PCIEM_SLOT_CTL_PDCE | PCIEM_SLOT_CTL_HPIE;
1269 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_APB)
1270 		val |= PCIEM_SLOT_CTL_ABPE;
1271 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PCP)
1272 		val |= PCIEM_SLOT_CTL_PFDE;
1273 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_MRLSP)
1274 		val |= PCIEM_SLOT_CTL_MRLSCE;
1275 	if (!(sc->pcie_slot_cap & PCIEM_SLOT_CAP_NCCS))
1276 		val |= PCIEM_SLOT_CTL_CCIE;
1277 	if (sc->pcie_link_cap & PCIEM_LINK_CAP_DL_ACTIVE)
1278 		val |= PCIEM_SLOT_CTL_DLLSCE;
1279 
1280 	/* Turn the attention indicator off. */
1281 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_AIP) {
1282 		mask |= PCIEM_SLOT_CTL_AIC;
1283 		val |= PCIEM_SLOT_CTL_AI_OFF;
1284 	}
1285 
1286 	pcib_pcie_hotplug_update(sc, val, mask, false);
1287 }
1288 #endif
1289 
1290 /*
1291  * Get current bridge configuration.
1292  */
1293 static void
1294 pcib_cfg_save(struct pcib_softc *sc)
1295 {
1296 #ifndef NEW_PCIB
1297 	device_t	dev;
1298 	uint16_t command;
1299 
1300 	dev = sc->dev;
1301 
1302 	command = pci_read_config(dev, PCIR_COMMAND, 2);
1303 	if (command & PCIM_CMD_PORTEN)
1304 		pcib_get_io_decode(sc);
1305 	if (command & PCIM_CMD_MEMEN)
1306 		pcib_get_mem_decode(sc);
1307 #endif
1308 }
1309 
1310 /*
1311  * Restore previous bridge configuration.
1312  */
1313 static void
1314 pcib_cfg_restore(struct pcib_softc *sc)
1315 {
1316 	device_t	dev;
1317 #ifndef NEW_PCIB
1318 	uint16_t command;
1319 #endif
1320 	dev = sc->dev;
1321 
1322 #ifdef NEW_PCIB
1323 	pcib_write_windows(sc, WIN_IO | WIN_MEM | WIN_PMEM);
1324 #else
1325 	command = pci_read_config(dev, PCIR_COMMAND, 2);
1326 	if (command & PCIM_CMD_PORTEN)
1327 		pcib_set_io_decode(sc);
1328 	if (command & PCIM_CMD_MEMEN)
1329 		pcib_set_mem_decode(sc);
1330 #endif
1331 }
1332 
1333 /*
1334  * Generic device interface
1335  */
1336 static int
1337 pcib_probe(device_t dev)
1338 {
1339     if ((pci_get_class(dev) == PCIC_BRIDGE) &&
1340 	(pci_get_subclass(dev) == PCIS_BRIDGE_PCI)) {
1341 	device_set_desc(dev, "PCI-PCI bridge");
1342 	return(-10000);
1343     }
1344     return(ENXIO);
1345 }
1346 
1347 void
1348 pcib_attach_common(device_t dev)
1349 {
1350     struct pcib_softc	*sc;
1351     struct sysctl_ctx_list *sctx;
1352     struct sysctl_oid	*soid;
1353     int comma;
1354 
1355     sc = device_get_softc(dev);
1356     sc->dev = dev;
1357 
1358     /*
1359      * Get current bridge configuration.
1360      */
1361     sc->domain = pci_get_domain(dev);
1362 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
1363     sc->bus.sec = pci_read_config(dev, PCIR_SECBUS_1, 1);
1364     sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
1365 #endif
1366     sc->bridgectl = pci_read_config(dev, PCIR_BRIDGECTL_1, 2);
1367     pcib_cfg_save(sc);
1368 
1369     /*
1370      * The primary bus register should always be the bus of the
1371      * parent.
1372      */
1373     sc->pribus = pci_get_bus(dev);
1374     pci_write_config(dev, PCIR_PRIBUS_1, sc->pribus, 1);
1375 
1376     /*
1377      * Setup sysctl reporting nodes
1378      */
1379     sctx = device_get_sysctl_ctx(dev);
1380     soid = device_get_sysctl_tree(dev);
1381     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "domain",
1382       CTLFLAG_RD, &sc->domain, 0, "Domain number");
1383     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "pribus",
1384       CTLFLAG_RD, &sc->pribus, 0, "Primary bus number");
1385     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "secbus",
1386       CTLFLAG_RD, &sc->bus.sec, 0, "Secondary bus number");
1387     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "subbus",
1388       CTLFLAG_RD, &sc->bus.sub, 0, "Subordinate bus number");
1389 
1390     /*
1391      * Quirk handling.
1392      */
1393     switch (pci_get_devid(dev)) {
1394 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
1395     case 0x12258086:		/* Intel 82454KX/GX (Orion) */
1396 	{
1397 	    uint8_t	supbus;
1398 
1399 	    supbus = pci_read_config(dev, 0x41, 1);
1400 	    if (supbus != 0xff) {
1401 		sc->bus.sec = supbus + 1;
1402 		sc->bus.sub = supbus + 1;
1403 	    }
1404 	    break;
1405 	}
1406 #endif
1407 
1408     /*
1409      * The i82380FB mobile docking controller is a PCI-PCI bridge,
1410      * and it is a subtractive bridge.  However, the ProgIf is wrong
1411      * so the normal setting of PCIB_SUBTRACTIVE bit doesn't
1412      * happen.  There are also Toshiba and Cavium ThunderX bridges
1413      * that behave this way.
1414      */
1415     case 0xa002177d:		/* Cavium ThunderX */
1416     case 0x124b8086:		/* Intel 82380FB Mobile */
1417     case 0x060513d7:		/* Toshiba ???? */
1418 	sc->flags |= PCIB_SUBTRACTIVE;
1419 	break;
1420 
1421 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
1422     /* Compaq R3000 BIOS sets wrong subordinate bus number. */
1423     case 0x00dd10de:
1424 	{
1425 	    char *cp;
1426 
1427 	    if ((cp = kern_getenv("smbios.planar.maker")) == NULL)
1428 		break;
1429 	    if (strncmp(cp, "Compal", 6) != 0) {
1430 		freeenv(cp);
1431 		break;
1432 	    }
1433 	    freeenv(cp);
1434 	    if ((cp = kern_getenv("smbios.planar.product")) == NULL)
1435 		break;
1436 	    if (strncmp(cp, "08A0", 4) != 0) {
1437 		freeenv(cp);
1438 		break;
1439 	    }
1440 	    freeenv(cp);
1441 	    if (sc->bus.sub < 0xa) {
1442 		pci_write_config(dev, PCIR_SUBBUS_1, 0xa, 1);
1443 		sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
1444 	    }
1445 	    break;
1446 	}
1447 #endif
1448     }
1449 
1450     if (pci_msi_device_blacklisted(dev))
1451 	sc->flags |= PCIB_DISABLE_MSI;
1452 
1453     if (pci_msix_device_blacklisted(dev))
1454 	sc->flags |= PCIB_DISABLE_MSIX;
1455 
1456     /*
1457      * Intel 815, 845 and other chipsets say they are PCI-PCI bridges,
1458      * but have a ProgIF of 0x80.  The 82801 family (AA, AB, BAM/CAM,
1459      * BA/CA/DB and E) PCI bridges are HUB-PCI bridges, in Intelese.
1460      * This means they act as if they were subtractively decoding
1461      * bridges and pass all transactions.  Mark them and real ProgIf 1
1462      * parts as subtractive.
1463      */
1464     if ((pci_get_devid(dev) & 0xff00ffff) == 0x24008086 ||
1465       pci_read_config(dev, PCIR_PROGIF, 1) == PCIP_BRIDGE_PCI_SUBTRACTIVE)
1466 	sc->flags |= PCIB_SUBTRACTIVE;
1467 
1468 #ifdef PCI_HP
1469     pcib_probe_hotplug(sc);
1470 #endif
1471 #ifdef NEW_PCIB
1472 #ifdef PCI_RES_BUS
1473     pcib_setup_secbus(dev, &sc->bus, 1);
1474 #endif
1475     pcib_probe_windows(sc);
1476 #endif
1477 #ifdef PCI_HP
1478     if (sc->flags & PCIB_HOTPLUG)
1479 	    pcib_setup_hotplug(sc);
1480 #endif
1481     if (bootverbose) {
1482 	device_printf(dev, "  domain            %d\n", sc->domain);
1483 	device_printf(dev, "  secondary bus     %d\n", sc->bus.sec);
1484 	device_printf(dev, "  subordinate bus   %d\n", sc->bus.sub);
1485 #ifdef NEW_PCIB
1486 	if (pcib_is_window_open(&sc->io))
1487 	    device_printf(dev, "  I/O decode        0x%jx-0x%jx\n",
1488 	      (uintmax_t)sc->io.base, (uintmax_t)sc->io.limit);
1489 	if (pcib_is_window_open(&sc->mem))
1490 	    device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1491 	      (uintmax_t)sc->mem.base, (uintmax_t)sc->mem.limit);
1492 	if (pcib_is_window_open(&sc->pmem))
1493 	    device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1494 	      (uintmax_t)sc->pmem.base, (uintmax_t)sc->pmem.limit);
1495 #else
1496 	if (pcib_is_io_open(sc))
1497 	    device_printf(dev, "  I/O decode        0x%x-0x%x\n",
1498 	      sc->iobase, sc->iolimit);
1499 	if (pcib_is_nonprefetch_open(sc))
1500 	    device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1501 	      (uintmax_t)sc->membase, (uintmax_t)sc->memlimit);
1502 	if (pcib_is_prefetch_open(sc))
1503 	    device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1504 	      (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
1505 #endif
1506 	if (sc->bridgectl & (PCIB_BCR_ISA_ENABLE | PCIB_BCR_VGA_ENABLE) ||
1507 	    sc->flags & PCIB_SUBTRACTIVE) {
1508 		device_printf(dev, "  special decode    ");
1509 		comma = 0;
1510 		if (sc->bridgectl & PCIB_BCR_ISA_ENABLE) {
1511 			printf("ISA");
1512 			comma = 1;
1513 		}
1514 		if (sc->bridgectl & PCIB_BCR_VGA_ENABLE) {
1515 			printf("%sVGA", comma ? ", " : "");
1516 			comma = 1;
1517 		}
1518 		if (sc->flags & PCIB_SUBTRACTIVE)
1519 			printf("%ssubtractive", comma ? ", " : "");
1520 		printf("\n");
1521 	}
1522     }
1523 
1524     /*
1525      * Always enable busmastering on bridges so that transactions
1526      * initiated on the secondary bus are passed through to the
1527      * primary bus.
1528      */
1529     pci_enable_busmaster(dev);
1530 }
1531 
1532 #ifdef PCI_HP
1533 static int
1534 pcib_present(struct pcib_softc *sc)
1535 {
1536 
1537 	if (sc->flags & PCIB_HOTPLUG)
1538 		return (pcib_hotplug_present(sc) != 0);
1539 	return (1);
1540 }
1541 #endif
1542 
1543 int
1544 pcib_attach_child(device_t dev)
1545 {
1546 	struct pcib_softc *sc;
1547 
1548 	sc = device_get_softc(dev);
1549 	if (sc->bus.sec == 0) {
1550 		/* no secondary bus; we should have fixed this */
1551 		return(0);
1552 	}
1553 
1554 #ifdef PCI_HP
1555 	if (!pcib_present(sc)) {
1556 		/* An empty HotPlug slot, so don't add a PCI bus yet. */
1557 		return (0);
1558 	}
1559 #endif
1560 
1561 	sc->child = device_add_child(dev, "pci", -1);
1562 	return (bus_generic_attach(dev));
1563 }
1564 
1565 int
1566 pcib_attach(device_t dev)
1567 {
1568 
1569     pcib_attach_common(dev);
1570     return (pcib_attach_child(dev));
1571 }
1572 
1573 int
1574 pcib_suspend(device_t dev)
1575 {
1576 
1577 	pcib_cfg_save(device_get_softc(dev));
1578 	return (bus_generic_suspend(dev));
1579 }
1580 
1581 int
1582 pcib_resume(device_t dev)
1583 {
1584 
1585 	pcib_cfg_restore(device_get_softc(dev));
1586 	return (bus_generic_resume(dev));
1587 }
1588 
1589 void
1590 pcib_bridge_init(device_t dev)
1591 {
1592 	pci_write_config(dev, PCIR_IOBASEL_1, 0xff, 1);
1593 	pci_write_config(dev, PCIR_IOBASEH_1, 0xffff, 2);
1594 	pci_write_config(dev, PCIR_IOLIMITL_1, 0, 1);
1595 	pci_write_config(dev, PCIR_IOLIMITH_1, 0, 2);
1596 	pci_write_config(dev, PCIR_MEMBASE_1, 0xffff, 2);
1597 	pci_write_config(dev, PCIR_MEMLIMIT_1, 0, 2);
1598 	pci_write_config(dev, PCIR_PMBASEL_1, 0xffff, 2);
1599 	pci_write_config(dev, PCIR_PMBASEH_1, 0xffffffff, 4);
1600 	pci_write_config(dev, PCIR_PMLIMITL_1, 0, 2);
1601 	pci_write_config(dev, PCIR_PMLIMITH_1, 0, 4);
1602 }
1603 
1604 int
1605 pcib_child_present(device_t dev, device_t child)
1606 {
1607 #ifdef PCI_HP
1608 	struct pcib_softc *sc = device_get_softc(dev);
1609 	int retval;
1610 
1611 	retval = bus_child_present(dev);
1612 	if (retval != 0 && sc->flags & PCIB_HOTPLUG)
1613 		retval = pcib_hotplug_present(sc);
1614 	return (retval);
1615 #else
1616 	return (bus_child_present(dev));
1617 #endif
1618 }
1619 
1620 int
1621 pcib_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1622 {
1623     struct pcib_softc	*sc = device_get_softc(dev);
1624 
1625     switch (which) {
1626     case PCIB_IVAR_DOMAIN:
1627 	*result = sc->domain;
1628 	return(0);
1629     case PCIB_IVAR_BUS:
1630 	*result = sc->bus.sec;
1631 	return(0);
1632     }
1633     return(ENOENT);
1634 }
1635 
1636 int
1637 pcib_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1638 {
1639 
1640     switch (which) {
1641     case PCIB_IVAR_DOMAIN:
1642 	return(EINVAL);
1643     case PCIB_IVAR_BUS:
1644 	return(EINVAL);
1645     }
1646     return(ENOENT);
1647 }
1648 
1649 #ifdef NEW_PCIB
1650 /*
1651  * Attempt to allocate a resource from the existing resources assigned
1652  * to a window.
1653  */
1654 static struct resource *
1655 pcib_suballoc_resource(struct pcib_softc *sc, struct pcib_window *w,
1656     device_t child, int type, int *rid, rman_res_t start, rman_res_t end,
1657     rman_res_t count, u_int flags)
1658 {
1659 	struct resource *res;
1660 
1661 	if (!pcib_is_window_open(w))
1662 		return (NULL);
1663 
1664 	res = rman_reserve_resource(&w->rman, start, end, count,
1665 	    flags & ~RF_ACTIVE, child);
1666 	if (res == NULL)
1667 		return (NULL);
1668 
1669 	if (bootverbose)
1670 		device_printf(sc->dev,
1671 		    "allocated %s range (%#jx-%#jx) for rid %x of %s\n",
1672 		    w->name, rman_get_start(res), rman_get_end(res), *rid,
1673 		    pcib_child_name(child));
1674 	rman_set_rid(res, *rid);
1675 
1676 	/*
1677 	 * If the resource should be active, pass that request up the
1678 	 * tree.  This assumes the parent drivers can handle
1679 	 * activating sub-allocated resources.
1680 	 */
1681 	if (flags & RF_ACTIVE) {
1682 		if (bus_activate_resource(child, type, *rid, res) != 0) {
1683 			rman_release_resource(res);
1684 			return (NULL);
1685 		}
1686 	}
1687 
1688 	return (res);
1689 }
1690 
1691 /* Allocate a fresh resource range for an unconfigured window. */
1692 static int
1693 pcib_alloc_new_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1694     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1695 {
1696 	struct resource *res;
1697 	rman_res_t base, limit, wmask;
1698 	int rid;
1699 
1700 	/*
1701 	 * If this is an I/O window on a bridge with ISA enable set
1702 	 * and the start address is below 64k, then try to allocate an
1703 	 * initial window of 0x1000 bytes long starting at address
1704 	 * 0xf000 and walking down.  Note that if the original request
1705 	 * was larger than the non-aliased range size of 0x100 our
1706 	 * caller would have raised the start address up to 64k
1707 	 * already.
1708 	 */
1709 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1710 	    start < 65536) {
1711 		for (base = 0xf000; (long)base >= 0; base -= 0x1000) {
1712 			limit = base + 0xfff;
1713 
1714 			/*
1715 			 * Skip ranges that wouldn't work for the
1716 			 * original request.  Note that the actual
1717 			 * window that overlaps are the non-alias
1718 			 * ranges within [base, limit], so this isn't
1719 			 * quite a simple comparison.
1720 			 */
1721 			if (start + count > limit - 0x400)
1722 				continue;
1723 			if (base == 0) {
1724 				/*
1725 				 * The first open region for the window at
1726 				 * 0 is 0x400-0x4ff.
1727 				 */
1728 				if (end - count + 1 < 0x400)
1729 					continue;
1730 			} else {
1731 				if (end - count + 1 < base)
1732 					continue;
1733 			}
1734 
1735 			if (pcib_alloc_nonisa_ranges(sc, base, limit) == 0) {
1736 				w->base = base;
1737 				w->limit = limit;
1738 				return (0);
1739 			}
1740 		}
1741 		return (ENOSPC);
1742 	}
1743 
1744 	wmask = ((rman_res_t)1 << w->step) - 1;
1745 	if (RF_ALIGNMENT(flags) < w->step) {
1746 		flags &= ~RF_ALIGNMENT_MASK;
1747 		flags |= RF_ALIGNMENT_LOG2(w->step);
1748 	}
1749 	start &= ~wmask;
1750 	end |= wmask;
1751 	count = roundup2(count, (rman_res_t)1 << w->step);
1752 	rid = w->reg;
1753 	res = bus_alloc_resource(sc->dev, type, &rid, start, end, count,
1754 	    flags & ~RF_ACTIVE);
1755 	if (res == NULL)
1756 		return (ENOSPC);
1757 	pcib_add_window_resources(w, &res, 1);
1758 	pcib_activate_window(sc, type);
1759 	w->base = rman_get_start(res);
1760 	w->limit = rman_get_end(res);
1761 	return (0);
1762 }
1763 
1764 /* Try to expand an existing window to the requested base and limit. */
1765 static int
1766 pcib_expand_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1767     rman_res_t base, rman_res_t limit)
1768 {
1769 	struct resource *res;
1770 	int error, i, force_64k_base;
1771 
1772 	KASSERT(base <= w->base && limit >= w->limit,
1773 	    ("attempting to shrink window"));
1774 
1775 	/*
1776 	 * XXX: pcib_grow_window() doesn't try to do this anyway and
1777 	 * the error handling for all the edge cases would be tedious.
1778 	 */
1779 	KASSERT(limit == w->limit || base == w->base,
1780 	    ("attempting to grow both ends of a window"));
1781 
1782 	/*
1783 	 * Yet more special handling for requests to expand an I/O
1784 	 * window behind an ISA-enabled bridge.  Since I/O windows
1785 	 * have to grow in 0x1000 increments and the end of the 0xffff
1786 	 * range is an alias, growing a window below 64k will always
1787 	 * result in allocating new resources and never adjusting an
1788 	 * existing resource.
1789 	 */
1790 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1791 	    (limit <= 65535 || (base <= 65535 && base != w->base))) {
1792 		KASSERT(limit == w->limit || limit <= 65535,
1793 		    ("attempting to grow both ends across 64k ISA alias"));
1794 
1795 		if (base != w->base)
1796 			error = pcib_alloc_nonisa_ranges(sc, base, w->base - 1);
1797 		else
1798 			error = pcib_alloc_nonisa_ranges(sc, w->limit + 1,
1799 			    limit);
1800 		if (error == 0) {
1801 			w->base = base;
1802 			w->limit = limit;
1803 		}
1804 		return (error);
1805 	}
1806 
1807 	/*
1808 	 * Find the existing resource to adjust.  Usually there is only one,
1809 	 * but for an ISA-enabled bridge we might be growing the I/O window
1810 	 * above 64k and need to find the existing resource that maps all
1811 	 * of the area above 64k.
1812 	 */
1813 	for (i = 0; i < w->count; i++) {
1814 		if (rman_get_end(w->res[i]) == w->limit)
1815 			break;
1816 	}
1817 	KASSERT(i != w->count, ("did not find existing resource"));
1818 	res = w->res[i];
1819 
1820 	/*
1821 	 * Usually the resource we found should match the window's
1822 	 * existing range.  The one exception is the ISA-enabled case
1823 	 * mentioned above in which case the resource should start at
1824 	 * 64k.
1825 	 */
1826 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1827 	    w->base <= 65535) {
1828 		KASSERT(rman_get_start(res) == 65536,
1829 		    ("existing resource mismatch"));
1830 		force_64k_base = 1;
1831 	} else {
1832 		KASSERT(w->base == rman_get_start(res),
1833 		    ("existing resource mismatch"));
1834 		force_64k_base = 0;
1835 	}
1836 
1837 	error = bus_adjust_resource(sc->dev, type, res, force_64k_base ?
1838 	    rman_get_start(res) : base, limit);
1839 	if (error)
1840 		return (error);
1841 
1842 	/* Add the newly allocated region to the resource manager. */
1843 	if (w->base != base) {
1844 		error = rman_manage_region(&w->rman, base, w->base - 1);
1845 		w->base = base;
1846 	} else {
1847 		error = rman_manage_region(&w->rman, w->limit + 1, limit);
1848 		w->limit = limit;
1849 	}
1850 	if (error) {
1851 		if (bootverbose)
1852 			device_printf(sc->dev,
1853 			    "failed to expand %s resource manager\n", w->name);
1854 		(void)bus_adjust_resource(sc->dev, type, res, force_64k_base ?
1855 		    rman_get_start(res) : w->base, w->limit);
1856 	}
1857 	return (error);
1858 }
1859 
1860 /*
1861  * Attempt to grow a window to make room for a given resource request.
1862  */
1863 static int
1864 pcib_grow_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1865     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1866 {
1867 	rman_res_t align, start_free, end_free, front, back, wmask;
1868 	int error;
1869 
1870 	/*
1871 	 * Clamp the desired resource range to the maximum address
1872 	 * this window supports.  Reject impossible requests.
1873 	 *
1874 	 * For I/O port requests behind a bridge with the ISA enable
1875 	 * bit set, force large allocations to start above 64k.
1876 	 */
1877 	if (!w->valid)
1878 		return (EINVAL);
1879 	if (sc->bridgectl & PCIB_BCR_ISA_ENABLE && count > 0x100 &&
1880 	    start < 65536)
1881 		start = 65536;
1882 	if (end > w->rman.rm_end)
1883 		end = w->rman.rm_end;
1884 	if (start + count - 1 > end || start + count < start)
1885 		return (EINVAL);
1886 	wmask = ((rman_res_t)1 << w->step) - 1;
1887 
1888 	/*
1889 	 * If there is no resource at all, just try to allocate enough
1890 	 * aligned space for this resource.
1891 	 */
1892 	if (w->res == NULL) {
1893 		error = pcib_alloc_new_window(sc, w, type, start, end, count,
1894 		    flags);
1895 		if (error) {
1896 			if (bootverbose)
1897 				device_printf(sc->dev,
1898 		    "failed to allocate initial %s window (%#jx-%#jx,%#jx)\n",
1899 				    w->name, start, end, count);
1900 			return (error);
1901 		}
1902 		if (bootverbose)
1903 			device_printf(sc->dev,
1904 			    "allocated initial %s window of %#jx-%#jx\n",
1905 			    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
1906 		goto updatewin;
1907 	}
1908 
1909 	/*
1910 	 * See if growing the window would help.  Compute the minimum
1911 	 * amount of address space needed on both the front and back
1912 	 * ends of the existing window to satisfy the allocation.
1913 	 *
1914 	 * For each end, build a candidate region adjusting for the
1915 	 * required alignment, etc.  If there is a free region at the
1916 	 * edge of the window, grow from the inner edge of the free
1917 	 * region.  Otherwise grow from the window boundary.
1918 	 *
1919 	 * Growing an I/O window below 64k for a bridge with the ISA
1920 	 * enable bit doesn't require any special magic as the step
1921 	 * size of an I/O window (1k) always includes multiple
1922 	 * non-alias ranges when it is grown in either direction.
1923 	 *
1924 	 * XXX: Special case: if w->res is completely empty and the
1925 	 * request size is larger than w->res, we should find the
1926 	 * optimal aligned buffer containing w->res and allocate that.
1927 	 */
1928 	if (bootverbose)
1929 		device_printf(sc->dev,
1930 		    "attempting to grow %s window for (%#jx-%#jx,%#jx)\n",
1931 		    w->name, start, end, count);
1932 	align = (rman_res_t)1 << RF_ALIGNMENT(flags);
1933 	if (start < w->base) {
1934 		if (rman_first_free_region(&w->rman, &start_free, &end_free) !=
1935 		    0 || start_free != w->base)
1936 			end_free = w->base;
1937 		if (end_free > end)
1938 			end_free = end + 1;
1939 
1940 		/* Move end_free down until it is properly aligned. */
1941 		end_free &= ~(align - 1);
1942 		end_free--;
1943 		front = end_free - (count - 1);
1944 
1945 		/*
1946 		 * The resource would now be allocated at (front,
1947 		 * end_free).  Ensure that fits in the (start, end)
1948 		 * bounds.  end_free is checked above.  If 'front' is
1949 		 * ok, ensure it is properly aligned for this window.
1950 		 * Also check for underflow.
1951 		 */
1952 		if (front >= start && front <= end_free) {
1953 			if (bootverbose)
1954 				printf("\tfront candidate range: %#jx-%#jx\n",
1955 				    front, end_free);
1956 			front &= ~wmask;
1957 			front = w->base - front;
1958 		} else
1959 			front = 0;
1960 	} else
1961 		front = 0;
1962 	if (end > w->limit) {
1963 		if (rman_last_free_region(&w->rman, &start_free, &end_free) !=
1964 		    0 || end_free != w->limit)
1965 			start_free = w->limit + 1;
1966 		if (start_free < start)
1967 			start_free = start;
1968 
1969 		/* Move start_free up until it is properly aligned. */
1970 		start_free = roundup2(start_free, align);
1971 		back = start_free + count - 1;
1972 
1973 		/*
1974 		 * The resource would now be allocated at (start_free,
1975 		 * back).  Ensure that fits in the (start, end)
1976 		 * bounds.  start_free is checked above.  If 'back' is
1977 		 * ok, ensure it is properly aligned for this window.
1978 		 * Also check for overflow.
1979 		 */
1980 		if (back <= end && start_free <= back) {
1981 			if (bootverbose)
1982 				printf("\tback candidate range: %#jx-%#jx\n",
1983 				    start_free, back);
1984 			back |= wmask;
1985 			back -= w->limit;
1986 		} else
1987 			back = 0;
1988 	} else
1989 		back = 0;
1990 
1991 	/*
1992 	 * Try to allocate the smallest needed region first.
1993 	 * If that fails, fall back to the other region.
1994 	 */
1995 	error = ENOSPC;
1996 	while (front != 0 || back != 0) {
1997 		if (front != 0 && (front <= back || back == 0)) {
1998 			error = pcib_expand_window(sc, w, type, w->base - front,
1999 			    w->limit);
2000 			if (error == 0)
2001 				break;
2002 			front = 0;
2003 		} else {
2004 			error = pcib_expand_window(sc, w, type, w->base,
2005 			    w->limit + back);
2006 			if (error == 0)
2007 				break;
2008 			back = 0;
2009 		}
2010 	}
2011 
2012 	if (error)
2013 		return (error);
2014 	if (bootverbose)
2015 		device_printf(sc->dev, "grew %s window to %#jx-%#jx\n",
2016 		    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
2017 
2018 updatewin:
2019 	/* Write the new window. */
2020 	KASSERT((w->base & wmask) == 0, ("start address is not aligned"));
2021 	KASSERT((w->limit & wmask) == wmask, ("end address is not aligned"));
2022 	pcib_write_windows(sc, w->mask);
2023 	return (0);
2024 }
2025 
2026 /*
2027  * We have to trap resource allocation requests and ensure that the bridge
2028  * is set up to, or capable of handling them.
2029  */
2030 struct resource *
2031 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid,
2032     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
2033 {
2034 	struct pcib_softc *sc;
2035 	struct resource *r;
2036 
2037 	sc = device_get_softc(dev);
2038 
2039 	/*
2040 	 * VGA resources are decoded iff the VGA enable bit is set in
2041 	 * the bridge control register.  VGA resources do not fall into
2042 	 * the resource windows and are passed up to the parent.
2043 	 */
2044 	if ((type == SYS_RES_IOPORT && pci_is_vga_ioport_range(start, end)) ||
2045 	    (type == SYS_RES_MEMORY && pci_is_vga_memory_range(start, end))) {
2046 		if (sc->bridgectl & PCIB_BCR_VGA_ENABLE)
2047 			return (bus_generic_alloc_resource(dev, child, type,
2048 			    rid, start, end, count, flags));
2049 		else
2050 			return (NULL);
2051 	}
2052 
2053 	switch (type) {
2054 #ifdef PCI_RES_BUS
2055 	case PCI_RES_BUS:
2056 		return (pcib_alloc_subbus(&sc->bus, child, rid, start, end,
2057 		    count, flags));
2058 #endif
2059 	case SYS_RES_IOPORT:
2060 		if (pcib_is_isa_range(sc, start, end, count))
2061 			return (NULL);
2062 		r = pcib_suballoc_resource(sc, &sc->io, child, type, rid, start,
2063 		    end, count, flags);
2064 		if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
2065 			break;
2066 		if (pcib_grow_window(sc, &sc->io, type, start, end, count,
2067 		    flags) == 0)
2068 			r = pcib_suballoc_resource(sc, &sc->io, child, type,
2069 			    rid, start, end, count, flags);
2070 		break;
2071 	case SYS_RES_MEMORY:
2072 		/*
2073 		 * For prefetchable resources, prefer the prefetchable
2074 		 * memory window, but fall back to the regular memory
2075 		 * window if that fails.  Try both windows before
2076 		 * attempting to grow a window in case the firmware
2077 		 * has used a range in the regular memory window to
2078 		 * map a prefetchable BAR.
2079 		 */
2080 		if (flags & RF_PREFETCHABLE) {
2081 			r = pcib_suballoc_resource(sc, &sc->pmem, child, type,
2082 			    rid, start, end, count, flags);
2083 			if (r != NULL)
2084 				break;
2085 		}
2086 		r = pcib_suballoc_resource(sc, &sc->mem, child, type, rid,
2087 		    start, end, count, flags);
2088 		if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
2089 			break;
2090 		if (flags & RF_PREFETCHABLE) {
2091 			if (pcib_grow_window(sc, &sc->pmem, type, start, end,
2092 			    count, flags) == 0) {
2093 				r = pcib_suballoc_resource(sc, &sc->pmem, child,
2094 				    type, rid, start, end, count, flags);
2095 				if (r != NULL)
2096 					break;
2097 			}
2098 		}
2099 		if (pcib_grow_window(sc, &sc->mem, type, start, end, count,
2100 		    flags & ~RF_PREFETCHABLE) == 0)
2101 			r = pcib_suballoc_resource(sc, &sc->mem, child, type,
2102 			    rid, start, end, count, flags);
2103 		break;
2104 	default:
2105 		return (bus_generic_alloc_resource(dev, child, type, rid,
2106 		    start, end, count, flags));
2107 	}
2108 
2109 	/*
2110 	 * If attempts to suballocate from the window fail but this is a
2111 	 * subtractive bridge, pass the request up the tree.
2112 	 */
2113 	if (sc->flags & PCIB_SUBTRACTIVE && r == NULL)
2114 		return (bus_generic_alloc_resource(dev, child, type, rid,
2115 		    start, end, count, flags));
2116 	return (r);
2117 }
2118 
2119 int
2120 pcib_adjust_resource(device_t bus, device_t child, int type, struct resource *r,
2121     rman_res_t start, rman_res_t end)
2122 {
2123 	struct pcib_softc *sc;
2124 
2125 	sc = device_get_softc(bus);
2126 	if (pcib_is_resource_managed(sc, type, r))
2127 		return (rman_adjust_resource(r, start, end));
2128 	return (bus_generic_adjust_resource(bus, child, type, r, start, end));
2129 }
2130 
2131 int
2132 pcib_release_resource(device_t dev, device_t child, int type, int rid,
2133     struct resource *r)
2134 {
2135 	struct pcib_softc *sc;
2136 	int error;
2137 
2138 	sc = device_get_softc(dev);
2139 	if (pcib_is_resource_managed(sc, type, r)) {
2140 		if (rman_get_flags(r) & RF_ACTIVE) {
2141 			error = bus_deactivate_resource(child, type, rid, r);
2142 			if (error)
2143 				return (error);
2144 		}
2145 		return (rman_release_resource(r));
2146 	}
2147 	return (bus_generic_release_resource(dev, child, type, rid, r));
2148 }
2149 #else
2150 /*
2151  * We have to trap resource allocation requests and ensure that the bridge
2152  * is set up to, or capable of handling them.
2153  */
2154 struct resource *
2155 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid,
2156     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
2157 {
2158 	struct pcib_softc	*sc = device_get_softc(dev);
2159 	const char *name, *suffix;
2160 	int ok;
2161 
2162 	/*
2163 	 * Fail the allocation for this range if it's not supported.
2164 	 */
2165 	name = device_get_nameunit(child);
2166 	if (name == NULL) {
2167 		name = "";
2168 		suffix = "";
2169 	} else
2170 		suffix = " ";
2171 	switch (type) {
2172 	case SYS_RES_IOPORT:
2173 		ok = 0;
2174 		if (!pcib_is_io_open(sc))
2175 			break;
2176 		ok = (start >= sc->iobase && end <= sc->iolimit);
2177 
2178 		/*
2179 		 * Make sure we allow access to VGA I/O addresses when the
2180 		 * bridge has the "VGA Enable" bit set.
2181 		 */
2182 		if (!ok && pci_is_vga_ioport_range(start, end))
2183 			ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
2184 
2185 		if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
2186 			if (!ok) {
2187 				if (start < sc->iobase)
2188 					start = sc->iobase;
2189 				if (end > sc->iolimit)
2190 					end = sc->iolimit;
2191 				if (start < end)
2192 					ok = 1;
2193 			}
2194 		} else {
2195 			ok = 1;
2196 #if 0
2197 			/*
2198 			 * If we overlap with the subtractive range, then
2199 			 * pick the upper range to use.
2200 			 */
2201 			if (start < sc->iolimit && end > sc->iobase)
2202 				start = sc->iolimit + 1;
2203 #endif
2204 		}
2205 		if (end < start) {
2206 			device_printf(dev, "ioport: end (%jx) < start (%jx)\n",
2207 			    end, start);
2208 			start = 0;
2209 			end = 0;
2210 			ok = 0;
2211 		}
2212 		if (!ok) {
2213 			device_printf(dev, "%s%srequested unsupported I/O "
2214 			    "range 0x%jx-0x%jx (decoding 0x%x-0x%x)\n",
2215 			    name, suffix, start, end, sc->iobase, sc->iolimit);
2216 			return (NULL);
2217 		}
2218 		if (bootverbose)
2219 			device_printf(dev,
2220 			    "%s%srequested I/O range 0x%jx-0x%jx: in range\n",
2221 			    name, suffix, start, end);
2222 		break;
2223 
2224 	case SYS_RES_MEMORY:
2225 		ok = 0;
2226 		if (pcib_is_nonprefetch_open(sc))
2227 			ok = ok || (start >= sc->membase && end <= sc->memlimit);
2228 		if (pcib_is_prefetch_open(sc))
2229 			ok = ok || (start >= sc->pmembase && end <= sc->pmemlimit);
2230 
2231 		/*
2232 		 * Make sure we allow access to VGA memory addresses when the
2233 		 * bridge has the "VGA Enable" bit set.
2234 		 */
2235 		if (!ok && pci_is_vga_memory_range(start, end))
2236 			ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
2237 
2238 		if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
2239 			if (!ok) {
2240 				ok = 1;
2241 				if (flags & RF_PREFETCHABLE) {
2242 					if (pcib_is_prefetch_open(sc)) {
2243 						if (start < sc->pmembase)
2244 							start = sc->pmembase;
2245 						if (end > sc->pmemlimit)
2246 							end = sc->pmemlimit;
2247 					} else {
2248 						ok = 0;
2249 					}
2250 				} else {	/* non-prefetchable */
2251 					if (pcib_is_nonprefetch_open(sc)) {
2252 						if (start < sc->membase)
2253 							start = sc->membase;
2254 						if (end > sc->memlimit)
2255 							end = sc->memlimit;
2256 					} else {
2257 						ok = 0;
2258 					}
2259 				}
2260 			}
2261 		} else if (!ok) {
2262 			ok = 1;	/* subtractive bridge: always ok */
2263 #if 0
2264 			if (pcib_is_nonprefetch_open(sc)) {
2265 				if (start < sc->memlimit && end > sc->membase)
2266 					start = sc->memlimit + 1;
2267 			}
2268 			if (pcib_is_prefetch_open(sc)) {
2269 				if (start < sc->pmemlimit && end > sc->pmembase)
2270 					start = sc->pmemlimit + 1;
2271 			}
2272 #endif
2273 		}
2274 		if (end < start) {
2275 			device_printf(dev, "memory: end (%jx) < start (%jx)\n",
2276 			    end, start);
2277 			start = 0;
2278 			end = 0;
2279 			ok = 0;
2280 		}
2281 		if (!ok && bootverbose)
2282 			device_printf(dev,
2283 			    "%s%srequested unsupported memory range %#jx-%#jx "
2284 			    "(decoding %#jx-%#jx, %#jx-%#jx)\n",
2285 			    name, suffix, start, end,
2286 			    (uintmax_t)sc->membase, (uintmax_t)sc->memlimit,
2287 			    (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
2288 		if (!ok)
2289 			return (NULL);
2290 		if (bootverbose)
2291 			device_printf(dev,"%s%srequested memory range "
2292 			    "0x%jx-0x%jx: good\n",
2293 			    name, suffix, start, end);
2294 		break;
2295 
2296 	default:
2297 		break;
2298 	}
2299 	/*
2300 	 * Bridge is OK decoding this resource, so pass it up.
2301 	 */
2302 	return (bus_generic_alloc_resource(dev, child, type, rid, start, end,
2303 	    count, flags));
2304 }
2305 #endif
2306 
2307 /*
2308  * If ARI is enabled on this downstream port, translate the function number
2309  * to the non-ARI slot/function.  The downstream port will convert it back in
2310  * hardware.  If ARI is not enabled slot and func are not modified.
2311  */
2312 static __inline void
2313 pcib_xlate_ari(device_t pcib, int bus, int *slot, int *func)
2314 {
2315 	struct pcib_softc *sc;
2316 	int ari_func;
2317 
2318 	sc = device_get_softc(pcib);
2319 	ari_func = *func;
2320 
2321 	if (sc->flags & PCIB_ENABLE_ARI) {
2322 		KASSERT(*slot == 0,
2323 		    ("Non-zero slot number with ARI enabled!"));
2324 		*slot = PCIE_ARI_SLOT(ari_func);
2325 		*func = PCIE_ARI_FUNC(ari_func);
2326 	}
2327 }
2328 
2329 
2330 static void
2331 pcib_enable_ari(struct pcib_softc *sc, uint32_t pcie_pos)
2332 {
2333 	uint32_t ctl2;
2334 
2335 	ctl2 = pci_read_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, 4);
2336 	ctl2 |= PCIEM_CTL2_ARI;
2337 	pci_write_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, ctl2, 4);
2338 
2339 	sc->flags |= PCIB_ENABLE_ARI;
2340 }
2341 
2342 /*
2343  * PCIB interface.
2344  */
2345 int
2346 pcib_maxslots(device_t dev)
2347 {
2348 	return (PCI_SLOTMAX);
2349 }
2350 
2351 static int
2352 pcib_ari_maxslots(device_t dev)
2353 {
2354 	struct pcib_softc *sc;
2355 
2356 	sc = device_get_softc(dev);
2357 
2358 	if (sc->flags & PCIB_ENABLE_ARI)
2359 		return (PCIE_ARI_SLOTMAX);
2360 	else
2361 		return (PCI_SLOTMAX);
2362 }
2363 
2364 static int
2365 pcib_ari_maxfuncs(device_t dev)
2366 {
2367 	struct pcib_softc *sc;
2368 
2369 	sc = device_get_softc(dev);
2370 
2371 	if (sc->flags & PCIB_ENABLE_ARI)
2372 		return (PCIE_ARI_FUNCMAX);
2373 	else
2374 		return (PCI_FUNCMAX);
2375 }
2376 
2377 static void
2378 pcib_ari_decode_rid(device_t pcib, uint16_t rid, int *bus, int *slot,
2379     int *func)
2380 {
2381 	struct pcib_softc *sc;
2382 
2383 	sc = device_get_softc(pcib);
2384 
2385 	*bus = PCI_RID2BUS(rid);
2386 	if (sc->flags & PCIB_ENABLE_ARI) {
2387 		*slot = PCIE_ARI_RID2SLOT(rid);
2388 		*func = PCIE_ARI_RID2FUNC(rid);
2389 	} else {
2390 		*slot = PCI_RID2SLOT(rid);
2391 		*func = PCI_RID2FUNC(rid);
2392 	}
2393 }
2394 
2395 /*
2396  * Since we are a child of a PCI bus, its parent must support the pcib interface.
2397  */
2398 static uint32_t
2399 pcib_read_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, int width)
2400 {
2401 #ifdef PCI_HP
2402 	struct pcib_softc *sc;
2403 
2404 	sc = device_get_softc(dev);
2405 	if (!pcib_present(sc)) {
2406 		switch (width) {
2407 		case 2:
2408 			return (0xffff);
2409 		case 1:
2410 			return (0xff);
2411 		default:
2412 			return (0xffffffff);
2413 		}
2414 	}
2415 #endif
2416 	pcib_xlate_ari(dev, b, &s, &f);
2417 	return(PCIB_READ_CONFIG(device_get_parent(device_get_parent(dev)), b, s,
2418 	    f, reg, width));
2419 }
2420 
2421 static void
2422 pcib_write_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, uint32_t val, int width)
2423 {
2424 #ifdef PCI_HP
2425 	struct pcib_softc *sc;
2426 
2427 	sc = device_get_softc(dev);
2428 	if (!pcib_present(sc))
2429 		return;
2430 #endif
2431 	pcib_xlate_ari(dev, b, &s, &f);
2432 	PCIB_WRITE_CONFIG(device_get_parent(device_get_parent(dev)), b, s, f,
2433 	    reg, val, width);
2434 }
2435 
2436 /*
2437  * Route an interrupt across a PCI bridge.
2438  */
2439 int
2440 pcib_route_interrupt(device_t pcib, device_t dev, int pin)
2441 {
2442     device_t	bus;
2443     int		parent_intpin;
2444     int		intnum;
2445 
2446     /*
2447      *
2448      * The PCI standard defines a swizzle of the child-side device/intpin to
2449      * the parent-side intpin as follows.
2450      *
2451      * device = device on child bus
2452      * child_intpin = intpin on child bus slot (0-3)
2453      * parent_intpin = intpin on parent bus slot (0-3)
2454      *
2455      * parent_intpin = (device + child_intpin) % 4
2456      */
2457     parent_intpin = (pci_get_slot(dev) + (pin - 1)) % 4;
2458 
2459     /*
2460      * Our parent is a PCI bus.  Its parent must export the pcib interface
2461      * which includes the ability to route interrupts.
2462      */
2463     bus = device_get_parent(pcib);
2464     intnum = PCIB_ROUTE_INTERRUPT(device_get_parent(bus), pcib, parent_intpin + 1);
2465     if (PCI_INTERRUPT_VALID(intnum) && bootverbose) {
2466 	device_printf(pcib, "slot %d INT%c is routed to irq %d\n",
2467 	    pci_get_slot(dev), 'A' + pin - 1, intnum);
2468     }
2469     return(intnum);
2470 }
2471 
2472 /* Pass request to alloc MSI/MSI-X messages up to the parent bridge. */
2473 int
2474 pcib_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
2475 {
2476 	struct pcib_softc *sc = device_get_softc(pcib);
2477 	device_t bus;
2478 
2479 	if (sc->flags & PCIB_DISABLE_MSI)
2480 		return (ENXIO);
2481 	bus = device_get_parent(pcib);
2482 	return (PCIB_ALLOC_MSI(device_get_parent(bus), dev, count, maxcount,
2483 	    irqs));
2484 }
2485 
2486 /* Pass request to release MSI/MSI-X messages up to the parent bridge. */
2487 int
2488 pcib_release_msi(device_t pcib, device_t dev, int count, int *irqs)
2489 {
2490 	device_t bus;
2491 
2492 	bus = device_get_parent(pcib);
2493 	return (PCIB_RELEASE_MSI(device_get_parent(bus), dev, count, irqs));
2494 }
2495 
2496 /* Pass request to alloc an MSI-X message up to the parent bridge. */
2497 int
2498 pcib_alloc_msix(device_t pcib, device_t dev, int *irq)
2499 {
2500 	struct pcib_softc *sc = device_get_softc(pcib);
2501 	device_t bus;
2502 
2503 	if (sc->flags & PCIB_DISABLE_MSIX)
2504 		return (ENXIO);
2505 	bus = device_get_parent(pcib);
2506 	return (PCIB_ALLOC_MSIX(device_get_parent(bus), dev, irq));
2507 }
2508 
2509 /* Pass request to release an MSI-X message up to the parent bridge. */
2510 int
2511 pcib_release_msix(device_t pcib, device_t dev, int irq)
2512 {
2513 	device_t bus;
2514 
2515 	bus = device_get_parent(pcib);
2516 	return (PCIB_RELEASE_MSIX(device_get_parent(bus), dev, irq));
2517 }
2518 
2519 /* Pass request to map MSI/MSI-X message up to parent bridge. */
2520 int
2521 pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
2522     uint32_t *data)
2523 {
2524 	device_t bus;
2525 	int error;
2526 
2527 	bus = device_get_parent(pcib);
2528 	error = PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data);
2529 	if (error)
2530 		return (error);
2531 
2532 	pci_ht_map_msi(pcib, *addr);
2533 	return (0);
2534 }
2535 
2536 /* Pass request for device power state up to parent bridge. */
2537 int
2538 pcib_power_for_sleep(device_t pcib, device_t dev, int *pstate)
2539 {
2540 	device_t bus;
2541 
2542 	bus = device_get_parent(pcib);
2543 	return (PCIB_POWER_FOR_SLEEP(bus, dev, pstate));
2544 }
2545 
2546 static int
2547 pcib_ari_enabled(device_t pcib)
2548 {
2549 	struct pcib_softc *sc;
2550 
2551 	sc = device_get_softc(pcib);
2552 
2553 	return ((sc->flags & PCIB_ENABLE_ARI) != 0);
2554 }
2555 
2556 static int
2557 pcib_ari_get_id(device_t pcib, device_t dev, enum pci_id_type type,
2558     uintptr_t *id)
2559 {
2560 	struct pcib_softc *sc;
2561 	device_t bus_dev;
2562 	uint8_t bus, slot, func;
2563 
2564 	if (type != PCI_ID_RID) {
2565 		bus_dev = device_get_parent(pcib);
2566 		return (PCIB_GET_ID(device_get_parent(bus_dev), dev, type, id));
2567 	}
2568 
2569 	sc = device_get_softc(pcib);
2570 
2571 	if (sc->flags & PCIB_ENABLE_ARI) {
2572 		bus = pci_get_bus(dev);
2573 		func = pci_get_function(dev);
2574 
2575 		*id = (PCI_ARI_RID(bus, func));
2576 	} else {
2577 		bus = pci_get_bus(dev);
2578 		slot = pci_get_slot(dev);
2579 		func = pci_get_function(dev);
2580 
2581 		*id = (PCI_RID(bus, slot, func));
2582 	}
2583 
2584 	return (0);
2585 }
2586 
2587 /*
2588  * Check that the downstream port (pcib) and the endpoint device (dev) both
2589  * support ARI.  If so, enable it and return 0, otherwise return an error.
2590  */
2591 static int
2592 pcib_try_enable_ari(device_t pcib, device_t dev)
2593 {
2594 	struct pcib_softc *sc;
2595 	int error;
2596 	uint32_t cap2;
2597 	int ari_cap_off;
2598 	uint32_t ari_ver;
2599 	uint32_t pcie_pos;
2600 
2601 	sc = device_get_softc(pcib);
2602 
2603 	/*
2604 	 * ARI is controlled in a register in the PCIe capability structure.
2605 	 * If the downstream port does not have the PCIe capability structure
2606 	 * then it does not support ARI.
2607 	 */
2608 	error = pci_find_cap(pcib, PCIY_EXPRESS, &pcie_pos);
2609 	if (error != 0)
2610 		return (ENODEV);
2611 
2612 	/* Check that the PCIe port advertises ARI support. */
2613 	cap2 = pci_read_config(pcib, pcie_pos + PCIER_DEVICE_CAP2, 4);
2614 	if (!(cap2 & PCIEM_CAP2_ARI))
2615 		return (ENODEV);
2616 
2617 	/*
2618 	 * Check that the endpoint device advertises ARI support via the ARI
2619 	 * extended capability structure.
2620 	 */
2621 	error = pci_find_extcap(dev, PCIZ_ARI, &ari_cap_off);
2622 	if (error != 0)
2623 		return (ENODEV);
2624 
2625 	/*
2626 	 * Finally, check that the endpoint device supports the same version
2627 	 * of ARI that we do.
2628 	 */
2629 	ari_ver = pci_read_config(dev, ari_cap_off, 4);
2630 	if (PCI_EXTCAP_VER(ari_ver) != PCIB_SUPPORTED_ARI_VER) {
2631 		if (bootverbose)
2632 			device_printf(pcib,
2633 			    "Unsupported version of ARI (%d) detected\n",
2634 			    PCI_EXTCAP_VER(ari_ver));
2635 
2636 		return (ENXIO);
2637 	}
2638 
2639 	pcib_enable_ari(sc, pcie_pos);
2640 
2641 	return (0);
2642 }
2643