xref: /freebsd/sys/dev/pci/pci_pci.c (revision 1edb7116)
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, int type, struct resource *r)
168 {
169 	switch (type) {
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, int type, struct resource *r)
192 {
193 
194 #ifdef PCI_RES_BUS
195 	if (type == PCI_RES_BUS)
196 		return (rman_is_region_manager(r, &sc->bus.rman));
197 #endif
198 	return (pcib_get_resource_window(sc, type, 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 	return (res);
731 }
732 
733 /*
734  * Attempt to grow the secondary bus range.  This is much simpler than
735  * for I/O windows as the range can only be grown by increasing
736  * subbus.
737  */
738 static int
739 pcib_grow_subbus(struct pcib_secbus *bus, rman_res_t new_end)
740 {
741 	rman_res_t old_end;
742 	int error;
743 
744 	old_end = rman_get_end(bus->res);
745 	KASSERT(new_end > old_end, ("attempt to shrink subbus"));
746 	error = bus_adjust_resource(bus->dev, PCI_RES_BUS, bus->res,
747 	    rman_get_start(bus->res), new_end);
748 	if (error)
749 		return (error);
750 	if (bootverbose)
751 		device_printf(bus->dev, "grew bus range to %ju-%ju\n",
752 		    rman_get_start(bus->res), rman_get_end(bus->res));
753 	error = rman_manage_region(&bus->rman, old_end + 1,
754 	    rman_get_end(bus->res));
755 	if (error)
756 		panic("Failed to add resource to rman");
757 	bus->sub = rman_get_end(bus->res);
758 	pci_write_config(bus->dev, bus->sub_reg, bus->sub, 1);
759 	return (0);
760 }
761 
762 struct resource *
763 pcib_alloc_subbus(struct pcib_secbus *bus, device_t child, int *rid,
764     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
765 {
766 	struct resource *res;
767 	rman_res_t start_free, end_free, new_end;
768 
769 	/*
770 	 * First, see if the request can be satisified by the existing
771 	 * bus range.
772 	 */
773 	res = pcib_suballoc_bus(bus, child, rid, start, end, count, flags);
774 	if (res != NULL)
775 		return (res);
776 
777 	/*
778 	 * Figure out a range to grow the bus range.  First, find the
779 	 * first bus number after the last allocated bus in the rman and
780 	 * enforce that as a minimum starting point for the range.
781 	 */
782 	if (rman_last_free_region(&bus->rman, &start_free, &end_free) != 0 ||
783 	    end_free != bus->sub)
784 		start_free = bus->sub + 1;
785 	if (start_free < start)
786 		start_free = start;
787 	new_end = start_free + count - 1;
788 
789 	/*
790 	 * See if this new range would satisfy the request if it
791 	 * succeeds.
792 	 */
793 	if (new_end > end)
794 		return (NULL);
795 
796 	/* Finally, attempt to grow the existing resource. */
797 	if (bootverbose) {
798 		device_printf(bus->dev,
799 		    "attempting to grow bus range for %ju buses\n", count);
800 		printf("\tback candidate range: %ju-%ju\n", start_free,
801 		    new_end);
802 	}
803 	if (pcib_grow_subbus(bus, new_end) == 0)
804 		return (pcib_suballoc_bus(bus, child, rid, start, end, count,
805 		    flags));
806 	return (NULL);
807 }
808 #endif
809 
810 #else
811 
812 /*
813  * Is the prefetch window open (eg, can we allocate memory in it?)
814  */
815 static int
816 pcib_is_prefetch_open(struct pcib_softc *sc)
817 {
818 	return (sc->pmembase > 0 && sc->pmembase < sc->pmemlimit);
819 }
820 
821 /*
822  * Is the nonprefetch window open (eg, can we allocate memory in it?)
823  */
824 static int
825 pcib_is_nonprefetch_open(struct pcib_softc *sc)
826 {
827 	return (sc->membase > 0 && sc->membase < sc->memlimit);
828 }
829 
830 /*
831  * Is the io window open (eg, can we allocate ports in it?)
832  */
833 static int
834 pcib_is_io_open(struct pcib_softc *sc)
835 {
836 	return (sc->iobase > 0 && sc->iobase < sc->iolimit);
837 }
838 
839 /*
840  * Get current I/O decode.
841  */
842 static void
843 pcib_get_io_decode(struct pcib_softc *sc)
844 {
845 	device_t	dev;
846 	uint32_t	iolow;
847 
848 	dev = sc->dev;
849 
850 	iolow = pci_read_config(dev, PCIR_IOBASEL_1, 1);
851 	if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
852 		sc->iobase = PCI_PPBIOBASE(
853 		    pci_read_config(dev, PCIR_IOBASEH_1, 2), iolow);
854 	else
855 		sc->iobase = PCI_PPBIOBASE(0, iolow);
856 
857 	iolow = pci_read_config(dev, PCIR_IOLIMITL_1, 1);
858 	if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
859 		sc->iolimit = PCI_PPBIOLIMIT(
860 		    pci_read_config(dev, PCIR_IOLIMITH_1, 2), iolow);
861 	else
862 		sc->iolimit = PCI_PPBIOLIMIT(0, iolow);
863 }
864 
865 /*
866  * Get current memory decode.
867  */
868 static void
869 pcib_get_mem_decode(struct pcib_softc *sc)
870 {
871 	device_t	dev;
872 	pci_addr_t	pmemlow;
873 
874 	dev = sc->dev;
875 
876 	sc->membase = PCI_PPBMEMBASE(0,
877 	    pci_read_config(dev, PCIR_MEMBASE_1, 2));
878 	sc->memlimit = PCI_PPBMEMLIMIT(0,
879 	    pci_read_config(dev, PCIR_MEMLIMIT_1, 2));
880 
881 	pmemlow = pci_read_config(dev, PCIR_PMBASEL_1, 2);
882 	if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64)
883 		sc->pmembase = PCI_PPBMEMBASE(
884 		    pci_read_config(dev, PCIR_PMBASEH_1, 4), pmemlow);
885 	else
886 		sc->pmembase = PCI_PPBMEMBASE(0, pmemlow);
887 
888 	pmemlow = pci_read_config(dev, PCIR_PMLIMITL_1, 2);
889 	if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64)
890 		sc->pmemlimit = PCI_PPBMEMLIMIT(
891 		    pci_read_config(dev, PCIR_PMLIMITH_1, 4), pmemlow);
892 	else
893 		sc->pmemlimit = PCI_PPBMEMLIMIT(0, pmemlow);
894 }
895 
896 /*
897  * Restore previous I/O decode.
898  */
899 static void
900 pcib_set_io_decode(struct pcib_softc *sc)
901 {
902 	device_t	dev;
903 	uint32_t	iohi;
904 
905 	dev = sc->dev;
906 
907 	iohi = sc->iobase >> 16;
908 	if (iohi > 0)
909 		pci_write_config(dev, PCIR_IOBASEH_1, iohi, 2);
910 	pci_write_config(dev, PCIR_IOBASEL_1, sc->iobase >> 8, 1);
911 
912 	iohi = sc->iolimit >> 16;
913 	if (iohi > 0)
914 		pci_write_config(dev, PCIR_IOLIMITH_1, iohi, 2);
915 	pci_write_config(dev, PCIR_IOLIMITL_1, sc->iolimit >> 8, 1);
916 }
917 
918 /*
919  * Restore previous memory decode.
920  */
921 static void
922 pcib_set_mem_decode(struct pcib_softc *sc)
923 {
924 	device_t	dev;
925 	pci_addr_t	pmemhi;
926 
927 	dev = sc->dev;
928 
929 	pci_write_config(dev, PCIR_MEMBASE_1, sc->membase >> 16, 2);
930 	pci_write_config(dev, PCIR_MEMLIMIT_1, sc->memlimit >> 16, 2);
931 
932 	pmemhi = sc->pmembase >> 32;
933 	if (pmemhi > 0)
934 		pci_write_config(dev, PCIR_PMBASEH_1, pmemhi, 4);
935 	pci_write_config(dev, PCIR_PMBASEL_1, sc->pmembase >> 16, 2);
936 
937 	pmemhi = sc->pmemlimit >> 32;
938 	if (pmemhi > 0)
939 		pci_write_config(dev, PCIR_PMLIMITH_1, pmemhi, 4);
940 	pci_write_config(dev, PCIR_PMLIMITL_1, sc->pmemlimit >> 16, 2);
941 }
942 #endif
943 
944 #ifdef PCI_HP
945 /*
946  * PCI-express HotPlug support.
947  */
948 static int pci_enable_pcie_hp = 1;
949 SYSCTL_INT(_hw_pci, OID_AUTO, enable_pcie_hp, CTLFLAG_RDTUN,
950     &pci_enable_pcie_hp, 0,
951     "Enable support for native PCI-express HotPlug.");
952 
953 TASKQUEUE_DEFINE_THREAD(pci_hp);
954 
955 static void
956 pcib_probe_hotplug(struct pcib_softc *sc)
957 {
958 	device_t dev;
959 	uint32_t link_cap;
960 	uint16_t link_sta, slot_sta;
961 
962 	if (!pci_enable_pcie_hp)
963 		return;
964 
965 	dev = sc->dev;
966 	if (pci_find_cap(dev, PCIY_EXPRESS, NULL) != 0)
967 		return;
968 
969 	if (!(pcie_read_config(dev, PCIER_FLAGS, 2) & PCIEM_FLAGS_SLOT))
970 		return;
971 
972 	sc->pcie_slot_cap = pcie_read_config(dev, PCIER_SLOT_CAP, 4);
973 
974 	if ((sc->pcie_slot_cap & PCIEM_SLOT_CAP_HPC) == 0)
975 		return;
976 	link_cap = pcie_read_config(dev, PCIER_LINK_CAP, 4);
977 	if ((link_cap & PCIEM_LINK_CAP_DL_ACTIVE) == 0)
978 		return;
979 
980 	/*
981 	 * Some devices report that they have an MRL when they actually
982 	 * do not.  Since they always report that the MRL is open, child
983 	 * devices would be ignored.  Try to detect these devices and
984 	 * ignore their claim of HotPlug support.
985 	 *
986 	 * If there is an open MRL but the Data Link Layer is active,
987 	 * the MRL is not real.
988 	 */
989 	if ((sc->pcie_slot_cap & PCIEM_SLOT_CAP_MRLSP) != 0) {
990 		link_sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
991 		slot_sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
992 		if ((slot_sta & PCIEM_SLOT_STA_MRLSS) != 0 &&
993 		    (link_sta & PCIEM_LINK_STA_DL_ACTIVE) != 0) {
994 			return;
995 		}
996 	}
997 
998 	/*
999 	 * Now that we're sure we want to do hot plug, ask the
1000 	 * firmware, if any, if that's OK.
1001 	 */
1002 	if (pcib_request_feature(dev, PCI_FEATURE_HP) != 0) {
1003 		if (bootverbose)
1004 			device_printf(dev, "Unable to activate hot plug feature.\n");
1005 		return;
1006 	}
1007 
1008 	sc->flags |= PCIB_HOTPLUG;
1009 }
1010 
1011 /*
1012  * Send a HotPlug command to the slot control register.  If this slot
1013  * uses command completion interrupts and a previous command is still
1014  * in progress, then the command is dropped.  Once the previous
1015  * command completes or times out, pcib_pcie_hotplug_update() will be
1016  * invoked to post a new command based on the slot's state at that
1017  * time.
1018  */
1019 static void
1020 pcib_pcie_hotplug_command(struct pcib_softc *sc, uint16_t val, uint16_t mask)
1021 {
1022 	device_t dev;
1023 	uint16_t ctl, new;
1024 
1025 	dev = sc->dev;
1026 
1027 	if (sc->flags & PCIB_HOTPLUG_CMD_PENDING)
1028 		return;
1029 
1030 	ctl = pcie_read_config(dev, PCIER_SLOT_CTL, 2);
1031 	new = (ctl & ~mask) | val;
1032 	if (new == ctl)
1033 		return;
1034 	if (bootverbose)
1035 		device_printf(dev, "HotPlug command: %04x -> %04x\n", ctl, new);
1036 	pcie_write_config(dev, PCIER_SLOT_CTL, new, 2);
1037 	if (!(sc->pcie_slot_cap & PCIEM_SLOT_CAP_NCCS) &&
1038 	    (ctl & new) & PCIEM_SLOT_CTL_CCIE) {
1039 		sc->flags |= PCIB_HOTPLUG_CMD_PENDING;
1040 		if (!cold)
1041 			taskqueue_enqueue_timeout(taskqueue_pci_hp,
1042 			    &sc->pcie_cc_task, hz);
1043 	}
1044 }
1045 
1046 static void
1047 pcib_pcie_hotplug_command_completed(struct pcib_softc *sc)
1048 {
1049 	device_t dev;
1050 
1051 	dev = sc->dev;
1052 
1053 	if (bootverbose)
1054 		device_printf(dev, "Command Completed\n");
1055 	if (!(sc->flags & PCIB_HOTPLUG_CMD_PENDING))
1056 		return;
1057 	taskqueue_cancel_timeout(taskqueue_pci_hp, &sc->pcie_cc_task, NULL);
1058 	sc->flags &= ~PCIB_HOTPLUG_CMD_PENDING;
1059 	wakeup(sc);
1060 }
1061 
1062 /*
1063  * Returns true if a card is fully inserted from the user's
1064  * perspective.  It may not yet be ready for access, but the driver
1065  * can now start enabling access if necessary.
1066  */
1067 static bool
1068 pcib_hotplug_inserted(struct pcib_softc *sc)
1069 {
1070 
1071 	/* Pretend the card isn't present if a detach is forced. */
1072 	if (sc->flags & PCIB_DETACHING)
1073 		return (false);
1074 
1075 	/* Card must be present in the slot. */
1076 	if ((sc->pcie_slot_sta & PCIEM_SLOT_STA_PDS) == 0)
1077 		return (false);
1078 
1079 	/* A power fault implicitly turns off power to the slot. */
1080 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_PFD)
1081 		return (false);
1082 
1083 	/* If the MRL is disengaged, the slot is powered off. */
1084 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_MRLSP &&
1085 	    (sc->pcie_slot_sta & PCIEM_SLOT_STA_MRLSS) != 0)
1086 		return (false);
1087 
1088 	return (true);
1089 }
1090 
1091 /*
1092  * Returns -1 if the card is fully inserted, powered, and ready for
1093  * access.  Otherwise, returns 0.
1094  */
1095 static int
1096 pcib_hotplug_present(struct pcib_softc *sc)
1097 {
1098 
1099 	/* Card must be inserted. */
1100 	if (!pcib_hotplug_inserted(sc))
1101 		return (0);
1102 
1103 	/* Require the Data Link Layer to be active. */
1104 	if (!(sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE))
1105 		return (0);
1106 
1107 	return (-1);
1108 }
1109 
1110 static int pci_enable_pcie_ei = 0;
1111 SYSCTL_INT(_hw_pci, OID_AUTO, enable_pcie_ei, CTLFLAG_RWTUN,
1112     &pci_enable_pcie_ei, 0,
1113     "Enable support for PCI-express Electromechanical Interlock.");
1114 
1115 static void
1116 pcib_pcie_hotplug_update(struct pcib_softc *sc, uint16_t val, uint16_t mask,
1117     bool schedule_task)
1118 {
1119 	bool card_inserted, ei_engaged;
1120 
1121 	/* Clear DETACHING if Presence Detect has cleared. */
1122 	if ((sc->pcie_slot_sta & (PCIEM_SLOT_STA_PDC | PCIEM_SLOT_STA_PDS)) ==
1123 	    PCIEM_SLOT_STA_PDC)
1124 		sc->flags &= ~PCIB_DETACHING;
1125 
1126 	card_inserted = pcib_hotplug_inserted(sc);
1127 
1128 	/* Turn the power indicator on if a card is inserted. */
1129 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PIP) {
1130 		mask |= PCIEM_SLOT_CTL_PIC;
1131 		if (card_inserted)
1132 			val |= PCIEM_SLOT_CTL_PI_ON;
1133 		else if (sc->flags & PCIB_DETACH_PENDING)
1134 			val |= PCIEM_SLOT_CTL_PI_BLINK;
1135 		else
1136 			val |= PCIEM_SLOT_CTL_PI_OFF;
1137 	}
1138 
1139 	/* Turn the power on via the Power Controller if a card is inserted. */
1140 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PCP) {
1141 		mask |= PCIEM_SLOT_CTL_PCC;
1142 		if (card_inserted)
1143 			val |= PCIEM_SLOT_CTL_PC_ON;
1144 		else
1145 			val |= PCIEM_SLOT_CTL_PC_OFF;
1146 	}
1147 
1148 	/*
1149 	 * If a card is inserted, enable the Electromechanical
1150 	 * Interlock.  If a card is not inserted (or we are in the
1151 	 * process of detaching), disable the Electromechanical
1152 	 * Interlock.
1153 	 */
1154 	if ((sc->pcie_slot_cap & PCIEM_SLOT_CAP_EIP) &&
1155 	    pci_enable_pcie_ei) {
1156 		mask |= PCIEM_SLOT_CTL_EIC;
1157 		ei_engaged = (sc->pcie_slot_sta & PCIEM_SLOT_STA_EIS) != 0;
1158 		if (card_inserted != ei_engaged)
1159 			val |= PCIEM_SLOT_CTL_EIC;
1160 	}
1161 
1162 	/*
1163 	 * Start a timer to see if the Data Link Layer times out.
1164 	 * Note that we only start the timer if Presence Detect or MRL Sensor
1165 	 * changed on this interrupt.  Stop any scheduled timer if
1166 	 * the Data Link Layer is active.
1167 	 */
1168 	if (card_inserted &&
1169 	    !(sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE) &&
1170 	    sc->pcie_slot_sta &
1171 	    (PCIEM_SLOT_STA_MRLSC | PCIEM_SLOT_STA_PDC)) {
1172 		if (cold)
1173 			device_printf(sc->dev,
1174 			    "Data Link Layer inactive\n");
1175 		else
1176 			taskqueue_enqueue_timeout(taskqueue_pci_hp,
1177 			    &sc->pcie_dll_task, hz);
1178 	} else if (sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE)
1179 		taskqueue_cancel_timeout(taskqueue_pci_hp, &sc->pcie_dll_task,
1180 		    NULL);
1181 
1182 	pcib_pcie_hotplug_command(sc, val, mask);
1183 
1184 	/*
1185 	 * During attach the child "pci" device is added synchronously;
1186 	 * otherwise, the task is scheduled to manage the child
1187 	 * device.
1188 	 */
1189 	if (schedule_task &&
1190 	    (pcib_hotplug_present(sc) != 0) != (sc->child != NULL))
1191 		taskqueue_enqueue(taskqueue_pci_hp, &sc->pcie_hp_task);
1192 }
1193 
1194 static void
1195 pcib_pcie_intr_hotplug(void *arg)
1196 {
1197 	struct pcib_softc *sc;
1198 	device_t dev;
1199 	uint16_t old_slot_sta;
1200 
1201 	sc = arg;
1202 	dev = sc->dev;
1203 	PCIB_HP_LOCK(sc);
1204 	old_slot_sta = sc->pcie_slot_sta;
1205 	sc->pcie_slot_sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
1206 
1207 	/* Clear the events just reported. */
1208 	pcie_write_config(dev, PCIER_SLOT_STA, sc->pcie_slot_sta, 2);
1209 
1210 	if (bootverbose)
1211 		device_printf(dev, "HotPlug interrupt: %#x\n",
1212 		    sc->pcie_slot_sta);
1213 
1214 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_ABP) {
1215 		if (sc->flags & PCIB_DETACH_PENDING) {
1216 			device_printf(dev,
1217 			    "Attention Button Pressed: Detach Cancelled\n");
1218 			sc->flags &= ~PCIB_DETACH_PENDING;
1219 			taskqueue_cancel_timeout(taskqueue_pci_hp,
1220 			    &sc->pcie_ab_task, NULL);
1221 		} else if (old_slot_sta & PCIEM_SLOT_STA_PDS) {
1222 			/* Only initiate detach sequence if device present. */
1223 			device_printf(dev,
1224 		    "Attention Button Pressed: Detaching in 5 seconds\n");
1225 			sc->flags |= PCIB_DETACH_PENDING;
1226 			taskqueue_enqueue_timeout(taskqueue_pci_hp,
1227 			    &sc->pcie_ab_task, 5 * hz);
1228 		}
1229 	}
1230 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_PFD)
1231 		device_printf(dev, "Power Fault Detected\n");
1232 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_MRLSC)
1233 		device_printf(dev, "MRL Sensor Changed to %s\n",
1234 		    sc->pcie_slot_sta & PCIEM_SLOT_STA_MRLSS ? "open" :
1235 		    "closed");
1236 	if (bootverbose && sc->pcie_slot_sta & PCIEM_SLOT_STA_PDC)
1237 		device_printf(dev, "Presence Detect Changed to %s\n",
1238 		    sc->pcie_slot_sta & PCIEM_SLOT_STA_PDS ? "card present" :
1239 		    "empty");
1240 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_CC)
1241 		pcib_pcie_hotplug_command_completed(sc);
1242 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_DLLSC) {
1243 		sc->pcie_link_sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
1244 		if (bootverbose)
1245 			device_printf(dev,
1246 			    "Data Link Layer State Changed to %s\n",
1247 			    sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE ?
1248 			    "active" : "inactive");
1249 	}
1250 
1251 	pcib_pcie_hotplug_update(sc, 0, 0, true);
1252 	PCIB_HP_UNLOCK(sc);
1253 }
1254 
1255 static void
1256 pcib_pcie_hotplug_task(void *context, int pending)
1257 {
1258 	struct pcib_softc *sc;
1259 	device_t dev;
1260 
1261 	sc = context;
1262 	PCIB_HP_LOCK(sc);
1263 	dev = sc->dev;
1264 	if (pcib_hotplug_present(sc) != 0) {
1265 		if (sc->child == NULL) {
1266 			sc->child = device_add_child(dev, "pci", -1);
1267 			bus_generic_attach(dev);
1268 		}
1269 	} else {
1270 		if (sc->child != NULL) {
1271 			if (device_delete_child(dev, sc->child) == 0)
1272 				sc->child = NULL;
1273 		}
1274 	}
1275 	PCIB_HP_UNLOCK(sc);
1276 }
1277 
1278 static void
1279 pcib_pcie_ab_timeout(void *arg, int pending)
1280 {
1281 	struct pcib_softc *sc = arg;
1282 
1283 	PCIB_HP_LOCK(sc);
1284 	if (sc->flags & PCIB_DETACH_PENDING) {
1285 		sc->flags |= PCIB_DETACHING;
1286 		sc->flags &= ~PCIB_DETACH_PENDING;
1287 		pcib_pcie_hotplug_update(sc, 0, 0, true);
1288 	}
1289 	PCIB_HP_UNLOCK(sc);
1290 }
1291 
1292 static void
1293 pcib_pcie_cc_timeout(void *arg, int pending)
1294 {
1295 	struct pcib_softc *sc = arg;
1296 	device_t dev = sc->dev;
1297 	uint16_t sta;
1298 
1299 	PCIB_HP_LOCK(sc);
1300 	sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
1301 	if (!(sta & PCIEM_SLOT_STA_CC)) {
1302 		device_printf(dev, "HotPlug Command Timed Out\n");
1303 		sc->flags &= ~PCIB_HOTPLUG_CMD_PENDING;
1304 	} else {
1305 		device_printf(dev,
1306 	    "Missed HotPlug interrupt waiting for Command Completion\n");
1307 		pcib_pcie_intr_hotplug(sc);
1308 	}
1309 	PCIB_HP_UNLOCK(sc);
1310 }
1311 
1312 static void
1313 pcib_pcie_dll_timeout(void *arg, int pending)
1314 {
1315 	struct pcib_softc *sc = arg;
1316 	device_t dev = sc->dev;
1317 	uint16_t sta;
1318 
1319 	PCIB_HP_LOCK(sc);
1320 	sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
1321 	if (!(sta & PCIEM_LINK_STA_DL_ACTIVE)) {
1322 		device_printf(dev,
1323 		    "Timed out waiting for Data Link Layer Active\n");
1324 		sc->flags |= PCIB_DETACHING;
1325 		pcib_pcie_hotplug_update(sc, 0, 0, true);
1326 	} else if (sta != sc->pcie_link_sta) {
1327 		device_printf(dev,
1328 		    "Missed HotPlug interrupt waiting for DLL Active\n");
1329 		pcib_pcie_intr_hotplug(sc);
1330 	}
1331 	PCIB_HP_UNLOCK(sc);
1332 }
1333 
1334 static int
1335 pcib_alloc_pcie_irq(struct pcib_softc *sc)
1336 {
1337 	device_t dev;
1338 	int count, error, mem_rid, rid;
1339 
1340 	rid = -1;
1341 	dev = sc->dev;
1342 
1343 	/*
1344 	 * For simplicity, only use MSI-X if there is a single message.
1345 	 * To support a device with multiple messages we would have to
1346 	 * use remap intr if the MSI number is not 0.
1347 	 */
1348 	count = pci_msix_count(dev);
1349 	if (count == 1) {
1350 		mem_rid = pci_msix_table_bar(dev);
1351 		sc->pcie_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
1352 		    &mem_rid, RF_ACTIVE);
1353 		if (sc->pcie_mem == NULL) {
1354 			device_printf(dev,
1355 			    "Failed to allocate BAR for MSI-X table\n");
1356 		} else {
1357 			error = pci_alloc_msix(dev, &count);
1358 			if (error == 0)
1359 				rid = 1;
1360 		}
1361 	}
1362 
1363 	if (rid < 0 && pci_msi_count(dev) > 0) {
1364 		count = 1;
1365 		error = pci_alloc_msi(dev, &count);
1366 		if (error == 0)
1367 			rid = 1;
1368 	}
1369 
1370 	if (rid < 0)
1371 		rid = 0;
1372 
1373 	sc->pcie_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1374 	    RF_ACTIVE | RF_SHAREABLE);
1375 	if (sc->pcie_irq == NULL) {
1376 		device_printf(dev,
1377 		    "Failed to allocate interrupt for PCI-e events\n");
1378 		if (rid > 0)
1379 			pci_release_msi(dev);
1380 		return (ENXIO);
1381 	}
1382 
1383 	error = bus_setup_intr(dev, sc->pcie_irq, INTR_TYPE_MISC|INTR_MPSAFE,
1384 	    NULL, pcib_pcie_intr_hotplug, sc, &sc->pcie_ihand);
1385 	if (error) {
1386 		device_printf(dev, "Failed to setup PCI-e interrupt handler\n");
1387 		bus_release_resource(dev, SYS_RES_IRQ, rid, sc->pcie_irq);
1388 		if (rid > 0)
1389 			pci_release_msi(dev);
1390 		return (error);
1391 	}
1392 	return (0);
1393 }
1394 
1395 static int
1396 pcib_release_pcie_irq(struct pcib_softc *sc)
1397 {
1398 	device_t dev;
1399 	int error;
1400 
1401 	dev = sc->dev;
1402 	error = bus_teardown_intr(dev, sc->pcie_irq, sc->pcie_ihand);
1403 	if (error)
1404 		return (error);
1405 	error = bus_free_resource(dev, SYS_RES_IRQ, sc->pcie_irq);
1406 	if (error)
1407 		return (error);
1408 	error = pci_release_msi(dev);
1409 	if (error)
1410 		return (error);
1411 	if (sc->pcie_mem != NULL)
1412 		error = bus_free_resource(dev, SYS_RES_MEMORY, sc->pcie_mem);
1413 	return (error);
1414 }
1415 
1416 static void
1417 pcib_setup_hotplug(struct pcib_softc *sc)
1418 {
1419 	device_t dev;
1420 	uint16_t mask, val;
1421 
1422 	dev = sc->dev;
1423 	TASK_INIT(&sc->pcie_hp_task, 0, pcib_pcie_hotplug_task, sc);
1424 	TIMEOUT_TASK_INIT(taskqueue_pci_hp, &sc->pcie_ab_task, 0,
1425 	    pcib_pcie_ab_timeout, sc);
1426 	TIMEOUT_TASK_INIT(taskqueue_pci_hp, &sc->pcie_cc_task, 0,
1427 	    pcib_pcie_cc_timeout, sc);
1428 	TIMEOUT_TASK_INIT(taskqueue_pci_hp, &sc->pcie_dll_task, 0,
1429 	    pcib_pcie_dll_timeout, sc);
1430 	sc->pcie_hp_lock = bus_topo_mtx();
1431 
1432 	/* Allocate IRQ. */
1433 	if (pcib_alloc_pcie_irq(sc) != 0)
1434 		return;
1435 
1436 	sc->pcie_link_sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
1437 	sc->pcie_slot_sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
1438 
1439 	/* Clear any events previously pending. */
1440 	pcie_write_config(dev, PCIER_SLOT_STA, sc->pcie_slot_sta, 2);
1441 
1442 	/* Enable HotPlug events. */
1443 	mask = PCIEM_SLOT_CTL_DLLSCE | PCIEM_SLOT_CTL_HPIE |
1444 	    PCIEM_SLOT_CTL_CCIE | PCIEM_SLOT_CTL_PDCE | PCIEM_SLOT_CTL_MRLSCE |
1445 	    PCIEM_SLOT_CTL_PFDE | PCIEM_SLOT_CTL_ABPE;
1446 	val = PCIEM_SLOT_CTL_DLLSCE | PCIEM_SLOT_CTL_HPIE | PCIEM_SLOT_CTL_PDCE;
1447 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_APB)
1448 		val |= PCIEM_SLOT_CTL_ABPE;
1449 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PCP)
1450 		val |= PCIEM_SLOT_CTL_PFDE;
1451 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_MRLSP)
1452 		val |= PCIEM_SLOT_CTL_MRLSCE;
1453 	if (!(sc->pcie_slot_cap & PCIEM_SLOT_CAP_NCCS))
1454 		val |= PCIEM_SLOT_CTL_CCIE;
1455 
1456 	/* Turn the attention indicator off. */
1457 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_AIP) {
1458 		mask |= PCIEM_SLOT_CTL_AIC;
1459 		val |= PCIEM_SLOT_CTL_AI_OFF;
1460 	}
1461 
1462 	pcib_pcie_hotplug_update(sc, val, mask, false);
1463 }
1464 
1465 static int
1466 pcib_detach_hotplug(struct pcib_softc *sc)
1467 {
1468 	uint16_t mask, val;
1469 	int error;
1470 
1471 	/* Disable the card in the slot and force it to detach. */
1472 	if (sc->flags & PCIB_DETACH_PENDING) {
1473 		sc->flags &= ~PCIB_DETACH_PENDING;
1474 		taskqueue_cancel_timeout(taskqueue_pci_hp, &sc->pcie_ab_task,
1475 		    NULL);
1476 	}
1477 	sc->flags |= PCIB_DETACHING;
1478 
1479 	if (sc->flags & PCIB_HOTPLUG_CMD_PENDING) {
1480 		taskqueue_cancel_timeout(taskqueue_pci_hp, &sc->pcie_cc_task,
1481 		    NULL);
1482 		tsleep(sc, 0, "hpcmd", hz);
1483 		sc->flags &= ~PCIB_HOTPLUG_CMD_PENDING;
1484 	}
1485 
1486 	/* Disable HotPlug events. */
1487 	mask = PCIEM_SLOT_CTL_DLLSCE | PCIEM_SLOT_CTL_HPIE |
1488 	    PCIEM_SLOT_CTL_CCIE | PCIEM_SLOT_CTL_PDCE | PCIEM_SLOT_CTL_MRLSCE |
1489 	    PCIEM_SLOT_CTL_PFDE | PCIEM_SLOT_CTL_ABPE;
1490 	val = 0;
1491 
1492 	/* Turn the attention indicator off. */
1493 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_AIP) {
1494 		mask |= PCIEM_SLOT_CTL_AIC;
1495 		val |= PCIEM_SLOT_CTL_AI_OFF;
1496 	}
1497 
1498 	pcib_pcie_hotplug_update(sc, val, mask, false);
1499 
1500 	error = pcib_release_pcie_irq(sc);
1501 	if (error)
1502 		return (error);
1503 	taskqueue_drain(taskqueue_pci_hp, &sc->pcie_hp_task);
1504 	taskqueue_drain_timeout(taskqueue_pci_hp, &sc->pcie_ab_task);
1505 	taskqueue_drain_timeout(taskqueue_pci_hp, &sc->pcie_cc_task);
1506 	taskqueue_drain_timeout(taskqueue_pci_hp, &sc->pcie_dll_task);
1507 	return (0);
1508 }
1509 #endif
1510 
1511 /*
1512  * Get current bridge configuration.
1513  */
1514 static void
1515 pcib_cfg_save(struct pcib_softc *sc)
1516 {
1517 #ifndef NEW_PCIB
1518 	device_t	dev;
1519 	uint16_t command;
1520 
1521 	dev = sc->dev;
1522 
1523 	command = pci_read_config(dev, PCIR_COMMAND, 2);
1524 	if (command & PCIM_CMD_PORTEN)
1525 		pcib_get_io_decode(sc);
1526 	if (command & PCIM_CMD_MEMEN)
1527 		pcib_get_mem_decode(sc);
1528 #endif
1529 }
1530 
1531 /*
1532  * Restore previous bridge configuration.
1533  */
1534 static void
1535 pcib_cfg_restore(struct pcib_softc *sc)
1536 {
1537 #ifndef NEW_PCIB
1538 	uint16_t command;
1539 #endif
1540 
1541 #ifdef NEW_PCIB
1542 	pcib_write_windows(sc, WIN_IO | WIN_MEM | WIN_PMEM);
1543 #else
1544 	command = pci_read_config(sc->dev, PCIR_COMMAND, 2);
1545 	if (command & PCIM_CMD_PORTEN)
1546 		pcib_set_io_decode(sc);
1547 	if (command & PCIM_CMD_MEMEN)
1548 		pcib_set_mem_decode(sc);
1549 #endif
1550 }
1551 
1552 /*
1553  * Generic device interface
1554  */
1555 static int
1556 pcib_probe(device_t dev)
1557 {
1558     if ((pci_get_class(dev) == PCIC_BRIDGE) &&
1559 	(pci_get_subclass(dev) == PCIS_BRIDGE_PCI)) {
1560 	device_set_desc(dev, "PCI-PCI bridge");
1561 	return(-10000);
1562     }
1563     return(ENXIO);
1564 }
1565 
1566 void
1567 pcib_attach_common(device_t dev)
1568 {
1569     struct pcib_softc	*sc;
1570     struct sysctl_ctx_list *sctx;
1571     struct sysctl_oid	*soid;
1572     int comma;
1573 
1574     sc = device_get_softc(dev);
1575     sc->dev = dev;
1576 
1577     /*
1578      * Get current bridge configuration.
1579      */
1580     sc->domain = pci_get_domain(dev);
1581 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
1582     sc->bus.sec = pci_read_config(dev, PCIR_SECBUS_1, 1);
1583     sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
1584 #endif
1585     sc->bridgectl = pci_read_config(dev, PCIR_BRIDGECTL_1, 2);
1586     pcib_cfg_save(sc);
1587 
1588     /*
1589      * The primary bus register should always be the bus of the
1590      * parent.
1591      */
1592     sc->pribus = pci_get_bus(dev);
1593     pci_write_config(dev, PCIR_PRIBUS_1, sc->pribus, 1);
1594 
1595     /*
1596      * Setup sysctl reporting nodes
1597      */
1598     sctx = device_get_sysctl_ctx(dev);
1599     soid = device_get_sysctl_tree(dev);
1600     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "domain",
1601       CTLFLAG_RD, &sc->domain, 0, "Domain number");
1602     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "pribus",
1603       CTLFLAG_RD, &sc->pribus, 0, "Primary bus number");
1604     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "secbus",
1605       CTLFLAG_RD, &sc->bus.sec, 0, "Secondary bus number");
1606     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "subbus",
1607       CTLFLAG_RD, &sc->bus.sub, 0, "Subordinate bus number");
1608 
1609     /*
1610      * Quirk handling.
1611      */
1612     switch (pci_get_devid(dev)) {
1613 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
1614     case 0x12258086:		/* Intel 82454KX/GX (Orion) */
1615 	{
1616 	    uint8_t	supbus;
1617 
1618 	    supbus = pci_read_config(dev, 0x41, 1);
1619 	    if (supbus != 0xff) {
1620 		sc->bus.sec = supbus + 1;
1621 		sc->bus.sub = supbus + 1;
1622 	    }
1623 	    break;
1624 	}
1625 #endif
1626 
1627     /*
1628      * The i82380FB mobile docking controller is a PCI-PCI bridge,
1629      * and it is a subtractive bridge.  However, the ProgIf is wrong
1630      * so the normal setting of PCIB_SUBTRACTIVE bit doesn't
1631      * happen.  There are also Toshiba and Cavium ThunderX bridges
1632      * that behave this way.
1633      */
1634     case 0xa002177d:		/* Cavium ThunderX */
1635     case 0x124b8086:		/* Intel 82380FB Mobile */
1636     case 0x060513d7:		/* Toshiba ???? */
1637 	sc->flags |= PCIB_SUBTRACTIVE;
1638 	break;
1639 
1640 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
1641     /* Compaq R3000 BIOS sets wrong subordinate bus number. */
1642     case 0x00dd10de:
1643 	{
1644 	    char *cp;
1645 
1646 	    if ((cp = kern_getenv("smbios.planar.maker")) == NULL)
1647 		break;
1648 	    if (strncmp(cp, "Compal", 6) != 0) {
1649 		freeenv(cp);
1650 		break;
1651 	    }
1652 	    freeenv(cp);
1653 	    if ((cp = kern_getenv("smbios.planar.product")) == NULL)
1654 		break;
1655 	    if (strncmp(cp, "08A0", 4) != 0) {
1656 		freeenv(cp);
1657 		break;
1658 	    }
1659 	    freeenv(cp);
1660 	    if (sc->bus.sub < 0xa) {
1661 		pci_write_config(dev, PCIR_SUBBUS_1, 0xa, 1);
1662 		sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
1663 	    }
1664 	    break;
1665 	}
1666 #endif
1667     }
1668 
1669     if (pci_msi_device_blacklisted(dev))
1670 	sc->flags |= PCIB_DISABLE_MSI;
1671 
1672     if (pci_msix_device_blacklisted(dev))
1673 	sc->flags |= PCIB_DISABLE_MSIX;
1674 
1675     /*
1676      * Intel 815, 845 and other chipsets say they are PCI-PCI bridges,
1677      * but have a ProgIF of 0x80.  The 82801 family (AA, AB, BAM/CAM,
1678      * BA/CA/DB and E) PCI bridges are HUB-PCI bridges, in Intelese.
1679      * This means they act as if they were subtractively decoding
1680      * bridges and pass all transactions.  Mark them and real ProgIf 1
1681      * parts as subtractive.
1682      */
1683     if ((pci_get_devid(dev) & 0xff00ffff) == 0x24008086 ||
1684       pci_read_config(dev, PCIR_PROGIF, 1) == PCIP_BRIDGE_PCI_SUBTRACTIVE)
1685 	sc->flags |= PCIB_SUBTRACTIVE;
1686 
1687 #ifdef PCI_HP
1688     pcib_probe_hotplug(sc);
1689 #endif
1690 #ifdef NEW_PCIB
1691 #ifdef PCI_RES_BUS
1692     pcib_setup_secbus(dev, &sc->bus, 1);
1693 #endif
1694     pcib_probe_windows(sc);
1695 #endif
1696 #ifdef PCI_HP
1697     if (sc->flags & PCIB_HOTPLUG)
1698 	    pcib_setup_hotplug(sc);
1699 #endif
1700     if (bootverbose) {
1701 	device_printf(dev, "  domain            %d\n", sc->domain);
1702 	device_printf(dev, "  secondary bus     %d\n", sc->bus.sec);
1703 	device_printf(dev, "  subordinate bus   %d\n", sc->bus.sub);
1704 #ifdef NEW_PCIB
1705 	if (pcib_is_window_open(&sc->io))
1706 	    device_printf(dev, "  I/O decode        0x%jx-0x%jx\n",
1707 	      (uintmax_t)sc->io.base, (uintmax_t)sc->io.limit);
1708 	if (pcib_is_window_open(&sc->mem))
1709 	    device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1710 	      (uintmax_t)sc->mem.base, (uintmax_t)sc->mem.limit);
1711 	if (pcib_is_window_open(&sc->pmem))
1712 	    device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1713 	      (uintmax_t)sc->pmem.base, (uintmax_t)sc->pmem.limit);
1714 #else
1715 	if (pcib_is_io_open(sc))
1716 	    device_printf(dev, "  I/O decode        0x%x-0x%x\n",
1717 	      sc->iobase, sc->iolimit);
1718 	if (pcib_is_nonprefetch_open(sc))
1719 	    device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1720 	      (uintmax_t)sc->membase, (uintmax_t)sc->memlimit);
1721 	if (pcib_is_prefetch_open(sc))
1722 	    device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1723 	      (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
1724 #endif
1725 	if (sc->bridgectl & (PCIB_BCR_ISA_ENABLE | PCIB_BCR_VGA_ENABLE) ||
1726 	    sc->flags & PCIB_SUBTRACTIVE) {
1727 		device_printf(dev, "  special decode    ");
1728 		comma = 0;
1729 		if (sc->bridgectl & PCIB_BCR_ISA_ENABLE) {
1730 			printf("ISA");
1731 			comma = 1;
1732 		}
1733 		if (sc->bridgectl & PCIB_BCR_VGA_ENABLE) {
1734 			printf("%sVGA", comma ? ", " : "");
1735 			comma = 1;
1736 		}
1737 		if (sc->flags & PCIB_SUBTRACTIVE)
1738 			printf("%ssubtractive", comma ? ", " : "");
1739 		printf("\n");
1740 	}
1741     }
1742 
1743     /*
1744      * Always enable busmastering on bridges so that transactions
1745      * initiated on the secondary bus are passed through to the
1746      * primary bus.
1747      */
1748     pci_enable_busmaster(dev);
1749 }
1750 
1751 #ifdef PCI_HP
1752 static int
1753 pcib_present(struct pcib_softc *sc)
1754 {
1755 
1756 	if (sc->flags & PCIB_HOTPLUG)
1757 		return (pcib_hotplug_present(sc) != 0);
1758 	return (1);
1759 }
1760 #endif
1761 
1762 int
1763 pcib_attach_child(device_t dev)
1764 {
1765 	struct pcib_softc *sc;
1766 
1767 	sc = device_get_softc(dev);
1768 	if (sc->bus.sec == 0) {
1769 		/* no secondary bus; we should have fixed this */
1770 		return(0);
1771 	}
1772 
1773 #ifdef PCI_HP
1774 	if (!pcib_present(sc)) {
1775 		/* An empty HotPlug slot, so don't add a PCI bus yet. */
1776 		return (0);
1777 	}
1778 #endif
1779 
1780 	sc->child = device_add_child(dev, "pci", -1);
1781 	return (bus_generic_attach(dev));
1782 }
1783 
1784 int
1785 pcib_attach(device_t dev)
1786 {
1787 
1788     pcib_attach_common(dev);
1789     return (pcib_attach_child(dev));
1790 }
1791 
1792 int
1793 pcib_detach(device_t dev)
1794 {
1795 #if defined(PCI_HP) || defined(NEW_PCIB)
1796 	struct pcib_softc *sc;
1797 #endif
1798 	int error;
1799 
1800 #if defined(PCI_HP) || defined(NEW_PCIB)
1801 	sc = device_get_softc(dev);
1802 #endif
1803 	error = bus_generic_detach(dev);
1804 	if (error)
1805 		return (error);
1806 #ifdef PCI_HP
1807 	if (sc->flags & PCIB_HOTPLUG) {
1808 		error = pcib_detach_hotplug(sc);
1809 		if (error)
1810 			return (error);
1811 	}
1812 #endif
1813 	error = device_delete_children(dev);
1814 	if (error)
1815 		return (error);
1816 #ifdef NEW_PCIB
1817 	pcib_free_windows(sc);
1818 #ifdef PCI_RES_BUS
1819 	pcib_free_secbus(dev, &sc->bus);
1820 #endif
1821 #endif
1822 	return (0);
1823 }
1824 
1825 int
1826 pcib_suspend(device_t dev)
1827 {
1828 
1829 	pcib_cfg_save(device_get_softc(dev));
1830 	return (bus_generic_suspend(dev));
1831 }
1832 
1833 int
1834 pcib_resume(device_t dev)
1835 {
1836 
1837 	pcib_cfg_restore(device_get_softc(dev));
1838 
1839 	/*
1840 	 * Restore the Command register only after restoring the windows.
1841 	 * The bridge should not be claiming random windows.
1842 	 */
1843 	pci_write_config(dev, PCIR_COMMAND, pci_get_cmdreg(dev), 2);
1844 	return (bus_generic_resume(dev));
1845 }
1846 
1847 void
1848 pcib_bridge_init(device_t dev)
1849 {
1850 	pci_write_config(dev, PCIR_IOBASEL_1, 0xff, 1);
1851 	pci_write_config(dev, PCIR_IOBASEH_1, 0xffff, 2);
1852 	pci_write_config(dev, PCIR_IOLIMITL_1, 0, 1);
1853 	pci_write_config(dev, PCIR_IOLIMITH_1, 0, 2);
1854 	pci_write_config(dev, PCIR_MEMBASE_1, 0xffff, 2);
1855 	pci_write_config(dev, PCIR_MEMLIMIT_1, 0, 2);
1856 	pci_write_config(dev, PCIR_PMBASEL_1, 0xffff, 2);
1857 	pci_write_config(dev, PCIR_PMBASEH_1, 0xffffffff, 4);
1858 	pci_write_config(dev, PCIR_PMLIMITL_1, 0, 2);
1859 	pci_write_config(dev, PCIR_PMLIMITH_1, 0, 4);
1860 }
1861 
1862 int
1863 pcib_child_present(device_t dev, device_t child)
1864 {
1865 #ifdef PCI_HP
1866 	struct pcib_softc *sc = device_get_softc(dev);
1867 	int retval;
1868 
1869 	retval = bus_child_present(dev);
1870 	if (retval != 0 && sc->flags & PCIB_HOTPLUG)
1871 		retval = pcib_hotplug_present(sc);
1872 	return (retval);
1873 #else
1874 	return (bus_child_present(dev));
1875 #endif
1876 }
1877 
1878 int
1879 pcib_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1880 {
1881     struct pcib_softc	*sc = device_get_softc(dev);
1882 
1883     switch (which) {
1884     case PCIB_IVAR_DOMAIN:
1885 	*result = sc->domain;
1886 	return(0);
1887     case PCIB_IVAR_BUS:
1888 	*result = sc->bus.sec;
1889 	return(0);
1890     }
1891     return(ENOENT);
1892 }
1893 
1894 int
1895 pcib_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1896 {
1897 
1898     switch (which) {
1899     case PCIB_IVAR_DOMAIN:
1900 	return(EINVAL);
1901     case PCIB_IVAR_BUS:
1902 	return(EINVAL);
1903     }
1904     return(ENOENT);
1905 }
1906 
1907 #ifdef NEW_PCIB
1908 /*
1909  * Attempt to allocate a resource from the existing resources assigned
1910  * to a window.
1911  */
1912 static struct resource *
1913 pcib_suballoc_resource(struct pcib_softc *sc, struct pcib_window *w,
1914     device_t child, int type, int *rid, rman_res_t start, rman_res_t end,
1915     rman_res_t count, u_int flags)
1916 {
1917 	struct resource *res;
1918 
1919 	if (!pcib_is_window_open(w))
1920 		return (NULL);
1921 
1922 	res = rman_reserve_resource(&w->rman, start, end, count,
1923 	    flags & ~RF_ACTIVE, child);
1924 	if (res == NULL)
1925 		return (NULL);
1926 
1927 	if (bootverbose)
1928 		device_printf(sc->dev,
1929 		    "allocated %s range (%#jx-%#jx) for rid %x of %s\n",
1930 		    w->name, rman_get_start(res), rman_get_end(res), *rid,
1931 		    pcib_child_name(child));
1932 	rman_set_rid(res, *rid);
1933 
1934 	if (flags & RF_ACTIVE) {
1935 		if (bus_activate_resource(child, type, *rid, res) != 0) {
1936 			rman_release_resource(res);
1937 			return (NULL);
1938 		}
1939 	}
1940 
1941 	return (res);
1942 }
1943 
1944 /* Allocate a fresh resource range for an unconfigured window. */
1945 static int
1946 pcib_alloc_new_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1947     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1948 {
1949 	struct resource *res;
1950 	rman_res_t base, limit, wmask;
1951 	int rid;
1952 
1953 	/*
1954 	 * If this is an I/O window on a bridge with ISA enable set
1955 	 * and the start address is below 64k, then try to allocate an
1956 	 * initial window of 0x1000 bytes long starting at address
1957 	 * 0xf000 and walking down.  Note that if the original request
1958 	 * was larger than the non-aliased range size of 0x100 our
1959 	 * caller would have raised the start address up to 64k
1960 	 * already.
1961 	 */
1962 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1963 	    start < 65536) {
1964 		for (base = 0xf000; (long)base >= 0; base -= 0x1000) {
1965 			limit = base + 0xfff;
1966 
1967 			/*
1968 			 * Skip ranges that wouldn't work for the
1969 			 * original request.  Note that the actual
1970 			 * window that overlaps are the non-alias
1971 			 * ranges within [base, limit], so this isn't
1972 			 * quite a simple comparison.
1973 			 */
1974 			if (start + count > limit - 0x400)
1975 				continue;
1976 			if (base == 0) {
1977 				/*
1978 				 * The first open region for the window at
1979 				 * 0 is 0x400-0x4ff.
1980 				 */
1981 				if (end - count + 1 < 0x400)
1982 					continue;
1983 			} else {
1984 				if (end - count + 1 < base)
1985 					continue;
1986 			}
1987 
1988 			if (pcib_alloc_nonisa_ranges(sc, base, limit) == 0) {
1989 				w->base = base;
1990 				w->limit = limit;
1991 				return (0);
1992 			}
1993 		}
1994 		return (ENOSPC);
1995 	}
1996 
1997 	wmask = ((rman_res_t)1 << w->step) - 1;
1998 	if (RF_ALIGNMENT(flags) < w->step) {
1999 		flags &= ~RF_ALIGNMENT_MASK;
2000 		flags |= RF_ALIGNMENT_LOG2(w->step);
2001 	}
2002 	start &= ~wmask;
2003 	end |= wmask;
2004 	count = roundup2(count, (rman_res_t)1 << w->step);
2005 	rid = w->reg;
2006 	res = bus_alloc_resource(sc->dev, type, &rid, start, end, count,
2007 	    flags | RF_ACTIVE | RF_UNMAPPED);
2008 	if (res == NULL)
2009 		return (ENOSPC);
2010 	pcib_add_window_resources(w, &res, 1);
2011 	pcib_activate_window(sc, type);
2012 	w->base = rman_get_start(res);
2013 	w->limit = rman_get_end(res);
2014 	return (0);
2015 }
2016 
2017 /* Try to expand an existing window to the requested base and limit. */
2018 static int
2019 pcib_expand_window(struct pcib_softc *sc, struct pcib_window *w, int type,
2020     rman_res_t base, rman_res_t limit)
2021 {
2022 	struct resource *res;
2023 	int error, i, force_64k_base;
2024 
2025 	KASSERT(base <= w->base && limit >= w->limit,
2026 	    ("attempting to shrink window"));
2027 
2028 	/*
2029 	 * XXX: pcib_grow_window() doesn't try to do this anyway and
2030 	 * the error handling for all the edge cases would be tedious.
2031 	 */
2032 	KASSERT(limit == w->limit || base == w->base,
2033 	    ("attempting to grow both ends of a window"));
2034 
2035 	/*
2036 	 * Yet more special handling for requests to expand an I/O
2037 	 * window behind an ISA-enabled bridge.  Since I/O windows
2038 	 * have to grow in 0x1000 increments and the end of the 0xffff
2039 	 * range is an alias, growing a window below 64k will always
2040 	 * result in allocating new resources and never adjusting an
2041 	 * existing resource.
2042 	 */
2043 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
2044 	    (limit <= 65535 || (base <= 65535 && base != w->base))) {
2045 		KASSERT(limit == w->limit || limit <= 65535,
2046 		    ("attempting to grow both ends across 64k ISA alias"));
2047 
2048 		if (base != w->base)
2049 			error = pcib_alloc_nonisa_ranges(sc, base, w->base - 1);
2050 		else
2051 			error = pcib_alloc_nonisa_ranges(sc, w->limit + 1,
2052 			    limit);
2053 		if (error == 0) {
2054 			w->base = base;
2055 			w->limit = limit;
2056 		}
2057 		return (error);
2058 	}
2059 
2060 	/*
2061 	 * Find the existing resource to adjust.  Usually there is only one,
2062 	 * but for an ISA-enabled bridge we might be growing the I/O window
2063 	 * above 64k and need to find the existing resource that maps all
2064 	 * of the area above 64k.
2065 	 */
2066 	for (i = 0; i < w->count; i++) {
2067 		if (rman_get_end(w->res[i]) == w->limit)
2068 			break;
2069 	}
2070 	KASSERT(i != w->count, ("did not find existing resource"));
2071 	res = w->res[i];
2072 
2073 	/*
2074 	 * Usually the resource we found should match the window's
2075 	 * existing range.  The one exception is the ISA-enabled case
2076 	 * mentioned above in which case the resource should start at
2077 	 * 64k.
2078 	 */
2079 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
2080 	    w->base <= 65535) {
2081 		KASSERT(rman_get_start(res) == 65536,
2082 		    ("existing resource mismatch"));
2083 		force_64k_base = 1;
2084 	} else {
2085 		KASSERT(w->base == rman_get_start(res),
2086 		    ("existing resource mismatch"));
2087 		force_64k_base = 0;
2088 	}
2089 
2090 	error = bus_adjust_resource(sc->dev, type, res, force_64k_base ?
2091 	    rman_get_start(res) : base, limit);
2092 	if (error)
2093 		return (error);
2094 
2095 	/* Add the newly allocated region to the resource manager. */
2096 	if (w->base != base) {
2097 		error = rman_manage_region(&w->rman, base, w->base - 1);
2098 		w->base = base;
2099 	} else {
2100 		error = rman_manage_region(&w->rman, w->limit + 1, limit);
2101 		w->limit = limit;
2102 	}
2103 	if (error) {
2104 		if (bootverbose)
2105 			device_printf(sc->dev,
2106 			    "failed to expand %s resource manager\n", w->name);
2107 		(void)bus_adjust_resource(sc->dev, type, res, force_64k_base ?
2108 		    rman_get_start(res) : w->base, w->limit);
2109 	}
2110 	return (error);
2111 }
2112 
2113 /*
2114  * Attempt to grow a window to make room for a given resource request.
2115  */
2116 static int
2117 pcib_grow_window(struct pcib_softc *sc, struct pcib_window *w, int type,
2118     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
2119 {
2120 	rman_res_t align, start_free, end_free, front, back, wmask;
2121 	int error;
2122 
2123 	/*
2124 	 * Clamp the desired resource range to the maximum address
2125 	 * this window supports.  Reject impossible requests.
2126 	 *
2127 	 * For I/O port requests behind a bridge with the ISA enable
2128 	 * bit set, force large allocations to start above 64k.
2129 	 */
2130 	if (!w->valid)
2131 		return (EINVAL);
2132 	if (sc->bridgectl & PCIB_BCR_ISA_ENABLE && count > 0x100 &&
2133 	    start < 65536)
2134 		start = 65536;
2135 	if (end > w->rman.rm_end)
2136 		end = w->rman.rm_end;
2137 	if (start + count - 1 > end || start + count < start)
2138 		return (EINVAL);
2139 	wmask = ((rman_res_t)1 << w->step) - 1;
2140 
2141 	/*
2142 	 * If there is no resource at all, just try to allocate enough
2143 	 * aligned space for this resource.
2144 	 */
2145 	if (w->res == NULL) {
2146 		error = pcib_alloc_new_window(sc, w, type, start, end, count,
2147 		    flags);
2148 		if (error) {
2149 			if (bootverbose)
2150 				device_printf(sc->dev,
2151 		    "failed to allocate initial %s window (%#jx-%#jx,%#jx)\n",
2152 				    w->name, start, end, count);
2153 			return (error);
2154 		}
2155 		if (bootverbose)
2156 			device_printf(sc->dev,
2157 			    "allocated initial %s window of %#jx-%#jx\n",
2158 			    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
2159 		goto updatewin;
2160 	}
2161 
2162 	/*
2163 	 * See if growing the window would help.  Compute the minimum
2164 	 * amount of address space needed on both the front and back
2165 	 * ends of the existing window to satisfy the allocation.
2166 	 *
2167 	 * For each end, build a candidate region adjusting for the
2168 	 * required alignment, etc.  If there is a free region at the
2169 	 * edge of the window, grow from the inner edge of the free
2170 	 * region.  Otherwise grow from the window boundary.
2171 	 *
2172 	 * Growing an I/O window below 64k for a bridge with the ISA
2173 	 * enable bit doesn't require any special magic as the step
2174 	 * size of an I/O window (1k) always includes multiple
2175 	 * non-alias ranges when it is grown in either direction.
2176 	 *
2177 	 * XXX: Special case: if w->res is completely empty and the
2178 	 * request size is larger than w->res, we should find the
2179 	 * optimal aligned buffer containing w->res and allocate that.
2180 	 */
2181 	if (bootverbose)
2182 		device_printf(sc->dev,
2183 		    "attempting to grow %s window for (%#jx-%#jx,%#jx)\n",
2184 		    w->name, start, end, count);
2185 	align = (rman_res_t)1 << RF_ALIGNMENT(flags);
2186 	if (start < w->base) {
2187 		if (rman_first_free_region(&w->rman, &start_free, &end_free) !=
2188 		    0 || start_free != w->base)
2189 			end_free = w->base;
2190 		if (end_free > end)
2191 			end_free = end + 1;
2192 
2193 		/* Move end_free down until it is properly aligned. */
2194 		end_free &= ~(align - 1);
2195 		end_free--;
2196 		front = end_free - (count - 1);
2197 
2198 		/*
2199 		 * The resource would now be allocated at (front,
2200 		 * end_free).  Ensure that fits in the (start, end)
2201 		 * bounds.  end_free is checked above.  If 'front' is
2202 		 * ok, ensure it is properly aligned for this window.
2203 		 * Also check for underflow.
2204 		 */
2205 		if (front >= start && front <= end_free) {
2206 			if (bootverbose)
2207 				printf("\tfront candidate range: %#jx-%#jx\n",
2208 				    front, end_free);
2209 			front &= ~wmask;
2210 			front = w->base - front;
2211 		} else
2212 			front = 0;
2213 	} else
2214 		front = 0;
2215 	if (end > w->limit) {
2216 		if (rman_last_free_region(&w->rman, &start_free, &end_free) !=
2217 		    0 || end_free != w->limit)
2218 			start_free = w->limit + 1;
2219 		if (start_free < start)
2220 			start_free = start;
2221 
2222 		/* Move start_free up until it is properly aligned. */
2223 		start_free = roundup2(start_free, align);
2224 		back = start_free + count - 1;
2225 
2226 		/*
2227 		 * The resource would now be allocated at (start_free,
2228 		 * back).  Ensure that fits in the (start, end)
2229 		 * bounds.  start_free is checked above.  If 'back' is
2230 		 * ok, ensure it is properly aligned for this window.
2231 		 * Also check for overflow.
2232 		 */
2233 		if (back <= end && start_free <= back) {
2234 			if (bootverbose)
2235 				printf("\tback candidate range: %#jx-%#jx\n",
2236 				    start_free, back);
2237 			back |= wmask;
2238 			back -= w->limit;
2239 		} else
2240 			back = 0;
2241 	} else
2242 		back = 0;
2243 
2244 	/*
2245 	 * Try to allocate the smallest needed region first.
2246 	 * If that fails, fall back to the other region.
2247 	 */
2248 	error = ENOSPC;
2249 	while (front != 0 || back != 0) {
2250 		if (front != 0 && (front <= back || back == 0)) {
2251 			error = pcib_expand_window(sc, w, type, w->base - front,
2252 			    w->limit);
2253 			if (error == 0)
2254 				break;
2255 			front = 0;
2256 		} else {
2257 			error = pcib_expand_window(sc, w, type, w->base,
2258 			    w->limit + back);
2259 			if (error == 0)
2260 				break;
2261 			back = 0;
2262 		}
2263 	}
2264 
2265 	if (error)
2266 		return (error);
2267 	if (bootverbose)
2268 		device_printf(sc->dev, "grew %s window to %#jx-%#jx\n",
2269 		    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
2270 
2271 updatewin:
2272 	/* Write the new window. */
2273 	KASSERT((w->base & wmask) == 0, ("start address is not aligned"));
2274 	KASSERT((w->limit & wmask) == wmask, ("end address is not aligned"));
2275 	pcib_write_windows(sc, w->mask);
2276 	return (0);
2277 }
2278 
2279 /*
2280  * We have to trap resource allocation requests and ensure that the bridge
2281  * is set up to, or capable of handling them.
2282  */
2283 static struct resource *
2284 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid,
2285     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
2286 {
2287 	struct pcib_softc *sc;
2288 	struct resource *r;
2289 
2290 	sc = device_get_softc(dev);
2291 
2292 	/*
2293 	 * VGA resources are decoded iff the VGA enable bit is set in
2294 	 * the bridge control register.  VGA resources do not fall into
2295 	 * the resource windows and are passed up to the parent.
2296 	 */
2297 	if ((type == SYS_RES_IOPORT && pci_is_vga_ioport_range(start, end)) ||
2298 	    (type == SYS_RES_MEMORY && pci_is_vga_memory_range(start, end))) {
2299 		if (sc->bridgectl & PCIB_BCR_VGA_ENABLE)
2300 			return (bus_generic_alloc_resource(dev, child, type,
2301 			    rid, start, end, count, flags));
2302 		else
2303 			return (NULL);
2304 	}
2305 
2306 	switch (type) {
2307 #ifdef PCI_RES_BUS
2308 	case PCI_RES_BUS:
2309 		return (pcib_alloc_subbus(&sc->bus, child, rid, start, end,
2310 		    count, flags));
2311 #endif
2312 	case SYS_RES_IOPORT:
2313 		if (pcib_is_isa_range(sc, start, end, count))
2314 			return (NULL);
2315 		r = pcib_suballoc_resource(sc, &sc->io, child, type, rid, start,
2316 		    end, count, flags);
2317 		if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
2318 			break;
2319 		if (pcib_grow_window(sc, &sc->io, type, start, end, count,
2320 		    flags) == 0)
2321 			r = pcib_suballoc_resource(sc, &sc->io, child, type,
2322 			    rid, start, end, count, flags);
2323 		break;
2324 	case SYS_RES_MEMORY:
2325 		/*
2326 		 * For prefetchable resources, prefer the prefetchable
2327 		 * memory window, but fall back to the regular memory
2328 		 * window if that fails.  Try both windows before
2329 		 * attempting to grow a window in case the firmware
2330 		 * has used a range in the regular memory window to
2331 		 * map a prefetchable BAR.
2332 		 */
2333 		if (flags & RF_PREFETCHABLE) {
2334 			r = pcib_suballoc_resource(sc, &sc->pmem, child, type,
2335 			    rid, start, end, count, flags);
2336 			if (r != NULL)
2337 				break;
2338 		}
2339 		r = pcib_suballoc_resource(sc, &sc->mem, child, type, rid,
2340 		    start, end, count, flags);
2341 		if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
2342 			break;
2343 		if (flags & RF_PREFETCHABLE) {
2344 			if (pcib_grow_window(sc, &sc->pmem, type, start, end,
2345 			    count, flags) == 0) {
2346 				r = pcib_suballoc_resource(sc, &sc->pmem, child,
2347 				    type, rid, start, end, count, flags);
2348 				if (r != NULL)
2349 					break;
2350 			}
2351 		}
2352 		if (pcib_grow_window(sc, &sc->mem, type, start, end, count,
2353 		    flags & ~RF_PREFETCHABLE) == 0)
2354 			r = pcib_suballoc_resource(sc, &sc->mem, child, type,
2355 			    rid, start, end, count, flags);
2356 		break;
2357 	default:
2358 		return (bus_generic_alloc_resource(dev, child, type, rid,
2359 		    start, end, count, flags));
2360 	}
2361 
2362 	/*
2363 	 * If attempts to suballocate from the window fail but this is a
2364 	 * subtractive bridge, pass the request up the tree.
2365 	 */
2366 	if (sc->flags & PCIB_SUBTRACTIVE && r == NULL)
2367 		return (bus_generic_alloc_resource(dev, child, type, rid,
2368 		    start, end, count, flags));
2369 	return (r);
2370 }
2371 
2372 static int
2373 pcib_adjust_resource(device_t bus, device_t child, int type, struct resource *r,
2374     rman_res_t start, rman_res_t end)
2375 {
2376 	struct pcib_softc *sc;
2377 	struct pcib_window *w;
2378 	rman_res_t wmask;
2379 	int error;
2380 
2381 	sc = device_get_softc(bus);
2382 
2383 	/*
2384 	 * If the resource wasn't sub-allocated from one of our region
2385 	 * managers then just pass the request up.
2386 	 */
2387 	if (!pcib_is_resource_managed(sc, type, r))
2388 		return (bus_generic_adjust_resource(bus, child, type, r,
2389 		    start, end));
2390 
2391 #ifdef PCI_RES_BUS
2392 	if (type == PCI_RES_BUS) {
2393 		/*
2394 		 * If our bus range isn't big enough to grow the sub-allocation
2395 		 * then we need to grow our bus range. Any request that would
2396 		 * require us to decrease the start of our own bus range is
2397 		 * invalid, we can only extend the end; ignore such requests
2398 		 * and let rman_adjust_resource fail below.
2399 		 */
2400 		if (start >= sc->bus.sec && end > sc->bus.sub) {
2401 			error = pcib_grow_subbus(&sc->bus, end);
2402 			if (error != 0)
2403 				return (error);
2404 		}
2405 	} else
2406 #endif
2407 	{
2408 		/*
2409 		 * Resource is managed and not a secondary bus number, must
2410 		 * be from one of our windows.
2411 		 */
2412 		w = pcib_get_resource_window(sc, type, r);
2413 		KASSERT(w != NULL,
2414 		    ("%s: no window for resource (%#jx-%#jx) type %d",
2415 		    __func__, rman_get_start(r), rman_get_end(r), type));
2416 
2417 		/*
2418 		 * If our window isn't big enough to grow the sub-allocation
2419 		 * then we need to expand the window.
2420 		 */
2421 		if (start < w->base || end > w->limit) {
2422 			wmask = ((rman_res_t)1 << w->step) - 1;
2423 			error = pcib_expand_window(sc, w, type,
2424 			    MIN(start & ~wmask, w->base),
2425 			    MAX(end | wmask, w->limit));
2426 			if (error != 0)
2427 				return (error);
2428 			if (bootverbose)
2429 				device_printf(sc->dev,
2430 				    "grew %s window to %#jx-%#jx\n",
2431 				    w->name, (uintmax_t)w->base,
2432 				    (uintmax_t)w->limit);
2433 			pcib_write_windows(sc, w->mask);
2434 		}
2435 	}
2436 
2437 	return (rman_adjust_resource(r, start, end));
2438 }
2439 
2440 static int
2441 pcib_release_resource(device_t dev, device_t child, int type, int rid,
2442     struct resource *r)
2443 {
2444 	struct pcib_softc *sc;
2445 	int error;
2446 
2447 	sc = device_get_softc(dev);
2448 	if (pcib_is_resource_managed(sc, type, r)) {
2449 		if (rman_get_flags(r) & RF_ACTIVE) {
2450 			error = bus_deactivate_resource(child, type, rid, r);
2451 			if (error)
2452 				return (error);
2453 		}
2454 		return (rman_release_resource(r));
2455 	}
2456 	return (bus_generic_release_resource(dev, child, type, rid, r));
2457 }
2458 
2459 static int
2460 pcib_activate_resource(device_t dev, device_t child, int type, int rid,
2461     struct resource *r)
2462 {
2463 	struct pcib_softc *sc = device_get_softc(dev);
2464 	struct resource_map map;
2465 	int error;
2466 
2467 	if (!pcib_is_resource_managed(sc, type, r))
2468 		return (bus_generic_activate_resource(dev, child, type, rid,
2469 		    r));
2470 
2471 	error = rman_activate_resource(r);
2472 	if (error != 0)
2473 		return (error);
2474 
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, type, 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, int type, int rid,
2490     struct resource *r)
2491 {
2492 	struct pcib_softc *sc = device_get_softc(dev);
2493 	struct resource_map map;
2494 	int error;
2495 
2496 	if (!pcib_is_resource_managed(sc, type, r))
2497 		return (bus_generic_deactivate_resource(dev, child, type, rid,
2498 		    r));
2499 
2500 	error = rman_deactivate_resource(r);
2501 	if (error != 0)
2502 		return (error);
2503 
2504 	if ((rman_get_flags(r) & RF_UNMAPPED) == 0 &&
2505 	    (type == SYS_RES_MEMORY || type == SYS_RES_IOPORT)) {
2506 		rman_get_mapping(r, &map);
2507 		BUS_UNMAP_RESOURCE(dev, child, type, r, &map);
2508 	}
2509 	return (0);
2510 }
2511 
2512 static struct resource *
2513 pcib_find_parent_resource(struct pcib_window *w, struct resource *r)
2514 {
2515 	for (int i = 0; i < w->count; i++) {
2516 		if (rman_get_start(w->res[i]) <= rman_get_start(r) &&
2517 		    rman_get_end(w->res[i]) >= rman_get_end(r))
2518 			return (w->res[i]);
2519 	}
2520 	return (NULL);
2521 }
2522 
2523 static int
2524 pcib_map_resource(device_t dev, device_t child, int type, struct resource *r,
2525     struct resource_map_request *argsp, struct resource_map *map)
2526 {
2527 	struct pcib_softc *sc = device_get_softc(dev);
2528 	struct resource_map_request args;
2529 	struct pcib_window *w;
2530 	struct resource *pres;
2531 	rman_res_t length, start;
2532 	int error;
2533 
2534 	w = pcib_get_resource_window(sc, type, r);
2535 	if (w == NULL)
2536 		return (bus_generic_map_resource(dev, child, type, r, argsp,
2537 		    map));
2538 
2539 	/* Resources must be active to be mapped. */
2540 	if (!(rman_get_flags(r) & RF_ACTIVE))
2541 		return (ENXIO);
2542 
2543 	resource_init_map_request(&args);
2544 	error = resource_validate_map_request(r, argsp, &args, &start, &length);
2545 	if (error)
2546 		return (error);
2547 
2548 	pres = pcib_find_parent_resource(w, r);
2549 	if (pres == NULL)
2550 		return (ENOENT);
2551 
2552 	args.offset = start - rman_get_start(pres);
2553 	args.length = length;
2554 	return (bus_generic_map_resource(dev, child, type, pres, &args, map));
2555 }
2556 
2557 static int
2558 pcib_unmap_resource(device_t dev, device_t child, int type, struct resource *r,
2559     struct resource_map *map)
2560 {
2561 	struct pcib_softc *sc = device_get_softc(dev);
2562 	struct pcib_window *w;
2563 
2564 	w = pcib_get_resource_window(sc, type, r);
2565 	if (w != NULL) {
2566 		r = pcib_find_parent_resource(w, r);
2567 		if (r == NULL)
2568 			return (ENOENT);
2569 	}
2570 	return (bus_generic_unmap_resource(dev, child, type, r, map));
2571 }
2572 #else
2573 /*
2574  * We have to trap resource allocation requests and ensure that the bridge
2575  * is set up to, or capable of handling them.
2576  */
2577 static struct resource *
2578 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid,
2579     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
2580 {
2581 	struct pcib_softc	*sc = device_get_softc(dev);
2582 	const char *name, *suffix;
2583 	int ok;
2584 
2585 	/*
2586 	 * Fail the allocation for this range if it's not supported.
2587 	 */
2588 	name = device_get_nameunit(child);
2589 	if (name == NULL) {
2590 		name = "";
2591 		suffix = "";
2592 	} else
2593 		suffix = " ";
2594 	switch (type) {
2595 	case SYS_RES_IOPORT:
2596 		ok = 0;
2597 		if (!pcib_is_io_open(sc))
2598 			break;
2599 		ok = (start >= sc->iobase && end <= sc->iolimit);
2600 
2601 		/*
2602 		 * Make sure we allow access to VGA I/O addresses when the
2603 		 * bridge has the "VGA Enable" bit set.
2604 		 */
2605 		if (!ok && pci_is_vga_ioport_range(start, end))
2606 			ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
2607 
2608 		if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
2609 			if (!ok) {
2610 				if (start < sc->iobase)
2611 					start = sc->iobase;
2612 				if (end > sc->iolimit)
2613 					end = sc->iolimit;
2614 				if (start < end)
2615 					ok = 1;
2616 			}
2617 		} else {
2618 			ok = 1;
2619 #if 0
2620 			/*
2621 			 * If we overlap with the subtractive range, then
2622 			 * pick the upper range to use.
2623 			 */
2624 			if (start < sc->iolimit && end > sc->iobase)
2625 				start = sc->iolimit + 1;
2626 #endif
2627 		}
2628 		if (end < start) {
2629 			device_printf(dev, "ioport: end (%jx) < start (%jx)\n",
2630 			    end, start);
2631 			start = 0;
2632 			end = 0;
2633 			ok = 0;
2634 		}
2635 		if (!ok) {
2636 			device_printf(dev, "%s%srequested unsupported I/O "
2637 			    "range 0x%jx-0x%jx (decoding 0x%x-0x%x)\n",
2638 			    name, suffix, start, end, sc->iobase, sc->iolimit);
2639 			return (NULL);
2640 		}
2641 		if (bootverbose)
2642 			device_printf(dev,
2643 			    "%s%srequested I/O range 0x%jx-0x%jx: in range\n",
2644 			    name, suffix, start, end);
2645 		break;
2646 
2647 	case SYS_RES_MEMORY:
2648 		ok = 0;
2649 		if (pcib_is_nonprefetch_open(sc))
2650 			ok = ok || (start >= sc->membase && end <= sc->memlimit);
2651 		if (pcib_is_prefetch_open(sc))
2652 			ok = ok || (start >= sc->pmembase && end <= sc->pmemlimit);
2653 
2654 		/*
2655 		 * Make sure we allow access to VGA memory addresses when the
2656 		 * bridge has the "VGA Enable" bit set.
2657 		 */
2658 		if (!ok && pci_is_vga_memory_range(start, end))
2659 			ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
2660 
2661 		if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
2662 			if (!ok) {
2663 				ok = 1;
2664 				if (flags & RF_PREFETCHABLE) {
2665 					if (pcib_is_prefetch_open(sc)) {
2666 						if (start < sc->pmembase)
2667 							start = sc->pmembase;
2668 						if (end > sc->pmemlimit)
2669 							end = sc->pmemlimit;
2670 					} else {
2671 						ok = 0;
2672 					}
2673 				} else {	/* non-prefetchable */
2674 					if (pcib_is_nonprefetch_open(sc)) {
2675 						if (start < sc->membase)
2676 							start = sc->membase;
2677 						if (end > sc->memlimit)
2678 							end = sc->memlimit;
2679 					} else {
2680 						ok = 0;
2681 					}
2682 				}
2683 			}
2684 		} else if (!ok) {
2685 			ok = 1;	/* subtractive bridge: always ok */
2686 #if 0
2687 			if (pcib_is_nonprefetch_open(sc)) {
2688 				if (start < sc->memlimit && end > sc->membase)
2689 					start = sc->memlimit + 1;
2690 			}
2691 			if (pcib_is_prefetch_open(sc)) {
2692 				if (start < sc->pmemlimit && end > sc->pmembase)
2693 					start = sc->pmemlimit + 1;
2694 			}
2695 #endif
2696 		}
2697 		if (end < start) {
2698 			device_printf(dev, "memory: end (%jx) < start (%jx)\n",
2699 			    end, start);
2700 			start = 0;
2701 			end = 0;
2702 			ok = 0;
2703 		}
2704 		if (!ok && bootverbose)
2705 			device_printf(dev,
2706 			    "%s%srequested unsupported memory range %#jx-%#jx "
2707 			    "(decoding %#jx-%#jx, %#jx-%#jx)\n",
2708 			    name, suffix, start, end,
2709 			    (uintmax_t)sc->membase, (uintmax_t)sc->memlimit,
2710 			    (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
2711 		if (!ok)
2712 			return (NULL);
2713 		if (bootverbose)
2714 			device_printf(dev,"%s%srequested memory range "
2715 			    "0x%jx-0x%jx: good\n",
2716 			    name, suffix, start, end);
2717 		break;
2718 
2719 	default:
2720 		break;
2721 	}
2722 	/*
2723 	 * Bridge is OK decoding this resource, so pass it up.
2724 	 */
2725 	return (bus_generic_alloc_resource(dev, child, type, rid, start, end,
2726 	    count, flags));
2727 }
2728 #endif
2729 
2730 /*
2731  * If ARI is enabled on this downstream port, translate the function number
2732  * to the non-ARI slot/function.  The downstream port will convert it back in
2733  * hardware.  If ARI is not enabled slot and func are not modified.
2734  */
2735 static __inline void
2736 pcib_xlate_ari(device_t pcib, int bus, int *slot, int *func)
2737 {
2738 	struct pcib_softc *sc;
2739 	int ari_func;
2740 
2741 	sc = device_get_softc(pcib);
2742 	ari_func = *func;
2743 
2744 	if (sc->flags & PCIB_ENABLE_ARI) {
2745 		KASSERT(*slot == 0,
2746 		    ("Non-zero slot number with ARI enabled!"));
2747 		*slot = PCIE_ARI_SLOT(ari_func);
2748 		*func = PCIE_ARI_FUNC(ari_func);
2749 	}
2750 }
2751 
2752 static void
2753 pcib_enable_ari(struct pcib_softc *sc, uint32_t pcie_pos)
2754 {
2755 	uint32_t ctl2;
2756 
2757 	ctl2 = pci_read_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, 4);
2758 	ctl2 |= PCIEM_CTL2_ARI;
2759 	pci_write_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, ctl2, 4);
2760 
2761 	sc->flags |= PCIB_ENABLE_ARI;
2762 }
2763 
2764 /*
2765  * PCIB interface.
2766  */
2767 int
2768 pcib_maxslots(device_t dev)
2769 {
2770 #if !defined(__amd64__) && !defined(__i386__)
2771 	uint32_t pcie_pos;
2772 	uint16_t val;
2773 
2774 	/*
2775 	 * If this is a PCIe rootport or downstream switch port, there's only
2776 	 * one slot permitted.
2777 	 */
2778 	if (pci_find_cap(dev, PCIY_EXPRESS, &pcie_pos) == 0) {
2779 		val = pci_read_config(dev, pcie_pos + PCIER_FLAGS, 2);
2780 		val &= PCIEM_FLAGS_TYPE;
2781 		if (val == PCIEM_TYPE_ROOT_PORT ||
2782 		    val == PCIEM_TYPE_DOWNSTREAM_PORT)
2783 			return (0);
2784 	}
2785 #endif
2786 	return (PCI_SLOTMAX);
2787 }
2788 
2789 static int
2790 pcib_ari_maxslots(device_t dev)
2791 {
2792 	struct pcib_softc *sc;
2793 
2794 	sc = device_get_softc(dev);
2795 
2796 	if (sc->flags & PCIB_ENABLE_ARI)
2797 		return (PCIE_ARI_SLOTMAX);
2798 	else
2799 		return (pcib_maxslots(dev));
2800 }
2801 
2802 static int
2803 pcib_ari_maxfuncs(device_t dev)
2804 {
2805 	struct pcib_softc *sc;
2806 
2807 	sc = device_get_softc(dev);
2808 
2809 	if (sc->flags & PCIB_ENABLE_ARI)
2810 		return (PCIE_ARI_FUNCMAX);
2811 	else
2812 		return (PCI_FUNCMAX);
2813 }
2814 
2815 static void
2816 pcib_ari_decode_rid(device_t pcib, uint16_t rid, int *bus, int *slot,
2817     int *func)
2818 {
2819 	struct pcib_softc *sc;
2820 
2821 	sc = device_get_softc(pcib);
2822 
2823 	*bus = PCI_RID2BUS(rid);
2824 	if (sc->flags & PCIB_ENABLE_ARI) {
2825 		*slot = PCIE_ARI_RID2SLOT(rid);
2826 		*func = PCIE_ARI_RID2FUNC(rid);
2827 	} else {
2828 		*slot = PCI_RID2SLOT(rid);
2829 		*func = PCI_RID2FUNC(rid);
2830 	}
2831 }
2832 
2833 /*
2834  * Since we are a child of a PCI bus, its parent must support the pcib interface.
2835  */
2836 static uint32_t
2837 pcib_read_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, int width)
2838 {
2839 #ifdef PCI_HP
2840 	struct pcib_softc *sc;
2841 
2842 	sc = device_get_softc(dev);
2843 	if (!pcib_present(sc)) {
2844 		switch (width) {
2845 		case 2:
2846 			return (0xffff);
2847 		case 1:
2848 			return (0xff);
2849 		default:
2850 			return (0xffffffff);
2851 		}
2852 	}
2853 #endif
2854 	pcib_xlate_ari(dev, b, &s, &f);
2855 	return(PCIB_READ_CONFIG(device_get_parent(device_get_parent(dev)), b, s,
2856 	    f, reg, width));
2857 }
2858 
2859 static void
2860 pcib_write_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, uint32_t val, int width)
2861 {
2862 #ifdef PCI_HP
2863 	struct pcib_softc *sc;
2864 
2865 	sc = device_get_softc(dev);
2866 	if (!pcib_present(sc))
2867 		return;
2868 #endif
2869 	pcib_xlate_ari(dev, b, &s, &f);
2870 	PCIB_WRITE_CONFIG(device_get_parent(device_get_parent(dev)), b, s, f,
2871 	    reg, val, width);
2872 }
2873 
2874 /*
2875  * Route an interrupt across a PCI bridge.
2876  */
2877 int
2878 pcib_route_interrupt(device_t pcib, device_t dev, int pin)
2879 {
2880     device_t	bus;
2881     int		parent_intpin;
2882     int		intnum;
2883 
2884     /*
2885      *
2886      * The PCI standard defines a swizzle of the child-side device/intpin to
2887      * the parent-side intpin as follows.
2888      *
2889      * device = device on child bus
2890      * child_intpin = intpin on child bus slot (0-3)
2891      * parent_intpin = intpin on parent bus slot (0-3)
2892      *
2893      * parent_intpin = (device + child_intpin) % 4
2894      */
2895     parent_intpin = (pci_get_slot(dev) + (pin - 1)) % 4;
2896 
2897     /*
2898      * Our parent is a PCI bus.  Its parent must export the pcib interface
2899      * which includes the ability to route interrupts.
2900      */
2901     bus = device_get_parent(pcib);
2902     intnum = PCIB_ROUTE_INTERRUPT(device_get_parent(bus), pcib, parent_intpin + 1);
2903     if (PCI_INTERRUPT_VALID(intnum) && bootverbose) {
2904 	device_printf(pcib, "slot %d INT%c is routed to irq %d\n",
2905 	    pci_get_slot(dev), 'A' + pin - 1, intnum);
2906     }
2907     return(intnum);
2908 }
2909 
2910 /* Pass request to alloc MSI/MSI-X messages up to the parent bridge. */
2911 int
2912 pcib_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
2913 {
2914 	struct pcib_softc *sc = device_get_softc(pcib);
2915 	device_t bus;
2916 
2917 	if (sc->flags & PCIB_DISABLE_MSI)
2918 		return (ENXIO);
2919 	bus = device_get_parent(pcib);
2920 	return (PCIB_ALLOC_MSI(device_get_parent(bus), dev, count, maxcount,
2921 	    irqs));
2922 }
2923 
2924 /* Pass request to release MSI/MSI-X messages up to the parent bridge. */
2925 int
2926 pcib_release_msi(device_t pcib, device_t dev, int count, int *irqs)
2927 {
2928 	device_t bus;
2929 
2930 	bus = device_get_parent(pcib);
2931 	return (PCIB_RELEASE_MSI(device_get_parent(bus), dev, count, irqs));
2932 }
2933 
2934 /* Pass request to alloc an MSI-X message up to the parent bridge. */
2935 int
2936 pcib_alloc_msix(device_t pcib, device_t dev, int *irq)
2937 {
2938 	struct pcib_softc *sc = device_get_softc(pcib);
2939 	device_t bus;
2940 
2941 	if (sc->flags & PCIB_DISABLE_MSIX)
2942 		return (ENXIO);
2943 	bus = device_get_parent(pcib);
2944 	return (PCIB_ALLOC_MSIX(device_get_parent(bus), dev, irq));
2945 }
2946 
2947 /* Pass request to release an MSI-X message up to the parent bridge. */
2948 int
2949 pcib_release_msix(device_t pcib, device_t dev, int irq)
2950 {
2951 	device_t bus;
2952 
2953 	bus = device_get_parent(pcib);
2954 	return (PCIB_RELEASE_MSIX(device_get_parent(bus), dev, irq));
2955 }
2956 
2957 /* Pass request to map MSI/MSI-X message up to parent bridge. */
2958 int
2959 pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
2960     uint32_t *data)
2961 {
2962 	device_t bus;
2963 	int error;
2964 
2965 	bus = device_get_parent(pcib);
2966 	error = PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data);
2967 	if (error)
2968 		return (error);
2969 
2970 	pci_ht_map_msi(pcib, *addr);
2971 	return (0);
2972 }
2973 
2974 /* Pass request for device power state up to parent bridge. */
2975 int
2976 pcib_power_for_sleep(device_t pcib, device_t dev, int *pstate)
2977 {
2978 	device_t bus;
2979 
2980 	bus = device_get_parent(pcib);
2981 	return (PCIB_POWER_FOR_SLEEP(bus, dev, pstate));
2982 }
2983 
2984 static int
2985 pcib_ari_enabled(device_t pcib)
2986 {
2987 	struct pcib_softc *sc;
2988 
2989 	sc = device_get_softc(pcib);
2990 
2991 	return ((sc->flags & PCIB_ENABLE_ARI) != 0);
2992 }
2993 
2994 static int
2995 pcib_ari_get_id(device_t pcib, device_t dev, enum pci_id_type type,
2996     uintptr_t *id)
2997 {
2998 	struct pcib_softc *sc;
2999 	device_t bus_dev;
3000 	uint8_t bus, slot, func;
3001 
3002 	if (type != PCI_ID_RID) {
3003 		bus_dev = device_get_parent(pcib);
3004 		return (PCIB_GET_ID(device_get_parent(bus_dev), dev, type, id));
3005 	}
3006 
3007 	sc = device_get_softc(pcib);
3008 
3009 	if (sc->flags & PCIB_ENABLE_ARI) {
3010 		bus = pci_get_bus(dev);
3011 		func = pci_get_function(dev);
3012 
3013 		*id = (PCI_ARI_RID(bus, func));
3014 	} else {
3015 		bus = pci_get_bus(dev);
3016 		slot = pci_get_slot(dev);
3017 		func = pci_get_function(dev);
3018 
3019 		*id = (PCI_RID(bus, slot, func));
3020 	}
3021 
3022 	return (0);
3023 }
3024 
3025 /*
3026  * Check that the downstream port (pcib) and the endpoint device (dev) both
3027  * support ARI.  If so, enable it and return 0, otherwise return an error.
3028  */
3029 static int
3030 pcib_try_enable_ari(device_t pcib, device_t dev)
3031 {
3032 	struct pcib_softc *sc;
3033 	int error;
3034 	uint32_t cap2;
3035 	int ari_cap_off;
3036 	uint32_t ari_ver;
3037 	uint32_t pcie_pos;
3038 
3039 	sc = device_get_softc(pcib);
3040 
3041 	/*
3042 	 * ARI is controlled in a register in the PCIe capability structure.
3043 	 * If the downstream port does not have the PCIe capability structure
3044 	 * then it does not support ARI.
3045 	 */
3046 	error = pci_find_cap(pcib, PCIY_EXPRESS, &pcie_pos);
3047 	if (error != 0)
3048 		return (ENODEV);
3049 
3050 	/* Check that the PCIe port advertises ARI support. */
3051 	cap2 = pci_read_config(pcib, pcie_pos + PCIER_DEVICE_CAP2, 4);
3052 	if (!(cap2 & PCIEM_CAP2_ARI))
3053 		return (ENODEV);
3054 
3055 	/*
3056 	 * Check that the endpoint device advertises ARI support via the ARI
3057 	 * extended capability structure.
3058 	 */
3059 	error = pci_find_extcap(dev, PCIZ_ARI, &ari_cap_off);
3060 	if (error != 0)
3061 		return (ENODEV);
3062 
3063 	/*
3064 	 * Finally, check that the endpoint device supports the same version
3065 	 * of ARI that we do.
3066 	 */
3067 	ari_ver = pci_read_config(dev, ari_cap_off, 4);
3068 	if (PCI_EXTCAP_VER(ari_ver) != PCIB_SUPPORTED_ARI_VER) {
3069 		if (bootverbose)
3070 			device_printf(pcib,
3071 			    "Unsupported version of ARI (%d) detected\n",
3072 			    PCI_EXTCAP_VER(ari_ver));
3073 
3074 		return (ENXIO);
3075 	}
3076 
3077 	pcib_enable_ari(sc, pcie_pos);
3078 
3079 	return (0);
3080 }
3081 
3082 int
3083 pcib_request_feature_allow(device_t pcib, device_t dev,
3084     enum pci_feature feature)
3085 {
3086 	/*
3087 	 * No host firmware we have to negotiate with, so we allow
3088 	 * every valid feature requested.
3089 	 */
3090 	switch (feature) {
3091 	case PCI_FEATURE_AER:
3092 	case PCI_FEATURE_HP:
3093 		break;
3094 	default:
3095 		return (EINVAL);
3096 	}
3097 
3098 	return (0);
3099 }
3100 
3101 int
3102 pcib_request_feature(device_t dev, enum pci_feature feature)
3103 {
3104 
3105 	/*
3106 	 * Invoke PCIB_REQUEST_FEATURE of this bridge first in case
3107 	 * the firmware overrides the method of PCI-PCI bridges.
3108 	 */
3109 	return (PCIB_REQUEST_FEATURE(dev, dev, feature));
3110 }
3111 
3112 /*
3113  * Pass the request to use this PCI feature up the tree. Either there's a
3114  * firmware like ACPI that's using this feature that will approve (or deny) the
3115  * request to take it over, or the platform has no such firmware, in which case
3116  * the request will be approved. If the request is approved, the OS is expected
3117  * to make use of the feature or render it harmless.
3118  */
3119 static int
3120 pcib_request_feature_default(device_t pcib, device_t dev,
3121     enum pci_feature feature)
3122 {
3123 	device_t bus;
3124 
3125 	/*
3126 	 * Our parent is necessarily a pci bus. Its parent will either be
3127 	 * another pci bridge (which passes it up) or a host bridge that can
3128 	 * approve or reject the request.
3129 	 */
3130 	bus = device_get_parent(pcib);
3131 	return (PCIB_REQUEST_FEATURE(device_get_parent(bus), dev, feature));
3132 }
3133 
3134 static int
3135 pcib_reset_child(device_t dev, device_t child, int flags)
3136 {
3137 	struct pci_devinfo *pdinfo;
3138 	int error;
3139 
3140 	error = 0;
3141 	if (dev == NULL || device_get_parent(child) != dev)
3142 		goto out;
3143 	error = ENXIO;
3144 	if (device_get_devclass(child) != devclass_find("pci"))
3145 		goto out;
3146 	pdinfo = device_get_ivars(dev);
3147 	if (pdinfo->cfg.pcie.pcie_location != 0 &&
3148 	    (pdinfo->cfg.pcie.pcie_type == PCIEM_TYPE_DOWNSTREAM_PORT ||
3149 	    pdinfo->cfg.pcie.pcie_type == PCIEM_TYPE_ROOT_PORT)) {
3150 		error = bus_helper_reset_prepare(child, flags);
3151 		if (error == 0) {
3152 			error = pcie_link_reset(dev,
3153 			    pdinfo->cfg.pcie.pcie_location);
3154 			/* XXXKIB call _post even if error != 0 ? */
3155 			bus_helper_reset_post(child, flags);
3156 		}
3157 	}
3158 out:
3159 	return (error);
3160 }
3161