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