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