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